Merge branch 'main' into feature/openrouter-anthropic-caching

This commit is contained in:
ferenci84 2025-08-29 22:04:57 +02:00
commit 05c45277ed
988 changed files with 105608 additions and 11565 deletions

View file

@ -52,7 +52,7 @@ Retrieve the following sites per these providers, and consider these notes on ho
// TODO: add info for openai, ollama, etc
For any other providers, search the web for "latest [provider] models" and find the most relevant model information using your best judgement.
Generally, ignore models that do not support text output. These models will be used in a coding assistant client that only supports text/image input and text/output, so extraneous capabilities can be ignored.
Generally, ignore models that do not support text output. These models will be used in a coding agent client that only supports text/image input and text/output, so extraneous capabilities can be ignored.
Sometimes, "Experimental", "Preview", or similar versions of models are available. The latest-date version of each should have its own information maintained.
3. UPDATE THE INFORMATION

View file

@ -0,0 +1,19 @@
---
name: Bigger Picture Description Rules
description: Guidelines for explaining how code works in context
alwaysApply: false
---
When a user asks how a certain part of the code works:
## 1. Describe what the code does in isolation
Explain the functionality of the code without considering its interactions with other parts of the codebase.
## 2. Describe interactions with other parts of the codebase
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. Include parent function for clarity
When describing each use-case, include the parent function for clarity.

View file

@ -1,13 +0,0 @@
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.

63
.continue/rules/colors.md Normal file
View file

@ -0,0 +1,63 @@
---
name: Extension Color Themes
description: Guidelines for using theme colors in GUI components
alwaysApply: false
globs: "gui/**/*.tsx"
---
When adding colors to components, use tailwind color classes.
Do NOT use explicit colors like text-gray-400. Instead, use theme colors.
## Available theme colors
### Normal text
- `foreground`, `description`, `description-muted`
### Other text, icons, etc
- `success`, `warning`, `error`, `accent`, `link`
### General components
- `background`, `border`, `border-focus`
### 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`
## Usage examples
Any of these colors can be used in tailwind classes:
- `bg-primary`
- `text-success`
- `border-error`
- `hover:bg-list-hover`
## Excluded colors
The following less-used colors are excluded from this guide:
- 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

@ -1,27 +0,0 @@
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,8 @@
---
globs: docs/**/*.{md,mdx}
description: This rule applies to all documentation files to ensure consistent
SEO optimization and improve discoverability. It helps users and search
engines understand the content of each page before reading it.
---
Every file in the docs folder must include a 'description' field in its frontmatter that accurately summarizes the content of the page in 100-160 characters. The description should be concise, keyword-rich, and explain what users will learn or accomplish from the page.

View file

@ -1,8 +0,0 @@
---
patterns: ["EditAggregator", "processEdit"]
glob: "**/*.tsx"
name: "Enforce EditAggregator Singleton"
description: "Ensure that EditAggregator is used as a singleton in the codebase."
---
When you encounter usage of EditAggregator, be sure that this is compatible with the singleton nature of the EditAggregator class. If you are creating a new instance of EditAggregator, you should instead use the existing singleton. Refer to the `aggregateEdits.ts` to examine how the singleton pattern is used. Do not create a new instance of EditAggregator.

View file

@ -0,0 +1,20 @@
---
name: IntelliJ Plugin Test Execution
description: Guidelines for running IntelliJ plugin tests with Gradle
alwaysApply: false
globs: extensions/intellij/**/*Test.kt
---
Run IntelliJ plugin tests using Gradle with the fully qualified test class or method name:
## Run test class
```bash
./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest"
```
## Run specific test method
```bash
./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest.should*"
```

View file

@ -1,15 +0,0 @@
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

@ -1,10 +0,0 @@
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

@ -1,6 +1,7 @@
---
name: New protocol message
description: Create a new protocol message from core/gui/ide to core/gui/ide
alwaysApply: false
---
Create a new protocol message by taking the following steps:

View file

@ -0,0 +1,37 @@
---
name: Unit Testing Rules
description: Guidelines for unit testing in this project
alwaysApply: false
---
For unit testing in this project:
## 1. Testing frameworks
The project uses Vitest and Jest for testing. Prefer Vitest.
## 2. Test execution location
Run tests from within the specific package directory (e.g., `cd core && ..`).
## 3. Vitest tests
- Test files follow the pattern `*.vitest.ts`
- Run tests using `vitest` from within the specific package/module directory:
```bash
cd [directory] && vitest -- [test file path]
```
## 4. Jest tests
- Test files follow the pattern `*.test.ts`
- Run tests using `npm test` from within the specific package/module directory:
```bash
cd [directory] && npm test -- [test file path]
```
- The test script uses experimental VM modules via NODE_OPTIONS flag
## 5. Test structure
- Write tests as top-level `test()` functions - DO NOT use `describe()` blocks
- Include the function name being tested in the test description for clarity

View file

@ -1,28 +0,0 @@
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 Vitest and Jest for testing. Prefer Vitest
2. Run tests from within the specific package directory (e.g., `cd core && ..`
3. For vitest tests,
- Test files follow the pattern `*.vitest.ts`
- Run tests using `vitest` from within the specific package/module
directory: `cd [directory] && vitest -- [test file path]`
4. For jest tests,
- Test files follow the pattern `*.test.ts`
- Run tests using `npm test` from within the specific package/module
directory: `cd [directory] && npm test -- [test file path]`
- The test script uses experimental VM modules via NODE_OPTIONS flag
5. For both
- Write tests as top-level `test()` functions - DO NOT use `describe()`
blocks
- Include the function name being tested in the test description for
clarity

View file

@ -29,7 +29,7 @@ body:
- **Continue version**: v0.9.4
- **IDE version**: VSCode 1.85.1
- Model: Claude Sonnet 3.5
- Assistant configuration
- Agent configuration
value: |
- OS:
- Continue version:
@ -39,7 +39,7 @@ body:
```yaml
```
OR link to assistant in Continue hub:
OR link to agent in Continue hub:
render: Markdown
validations:
required: false

View file

@ -105,7 +105,9 @@ runs:
shell: bash
run: |
cd gui
npm run build
npm run build --max-old-space-size=4096
env:
NODE_OPTIONS: "--max-old-space-size=4096"
- name: Prepackage the extension
shell: bash
@ -156,4 +158,4 @@ runs:
npx vsce package --pre-release --no-dependencies --target ${{ steps.set-target.outputs.target }}
else
npx vsce package --no-dependencies --target ${{ steps.set-target.outputs.target }}
fi
fi

View file

@ -44,6 +44,7 @@ runs:
- name: Setup FFmpeg
uses: AnimMouse/setup-ffmpeg@v1
with:
version: 7.1
token: ${{ inputs.github-token }}
- name: Setup Gradle
@ -93,6 +94,13 @@ runs:
path: binary/node_modules
key: ${{ runner.os }}-binary-node-modules-${{ hashFiles('binary/package-lock.json') }}
- name: Install binary dependencies
if: steps.binary-cache.outputs.cache-hit != 'true'
shell: bash
run: |
cd binary
npm ci
- name: Build the binaries
shell: bash
run: |
@ -128,14 +136,22 @@ runs:
shell: bash
run: |
cd extensions/intellij
mv video build/reports
if [ -d "video" ]; then
mv video build/reports
else
echo "No video directory found to move"
fi
- name: Copy logs
if: ${{ failure() }}
shell: bash
run: |
cd extensions/intellij
mv build/idea-sandbox/system/log/ build/reports
if [ -d "build/idea-sandbox/system/log/" ]; then
mv build/idea-sandbox/system/log/ build/reports
else
echo "No log directory found to copy"
fi
- name: Save fails report
if: ${{ failure() }}

19
.github/actions/track-rerun/action.yml vendored Normal file
View file

@ -0,0 +1,19 @@
name: Track Workflow Rerun
description: Track when GitHub Actions workflows are rerun (attempt > 1)
runs:
using: composite
steps:
# Eventually we can start logging this to monitor codebase health (e.g. to Slack, PostHog, etc.)
- name: Track workflow rerun
if: github.run_attempt > 1
shell: bash
run: |
echo "🔄 Workflow rerun detected - Attempt #${{ github.run_attempt }}"
echo "📊 Workflow: ${{ github.workflow }}"
echo "🔀 PR: ${{ github.event.pull_request.number || 'N/A' }}"
echo "📝 Commit: ${{ github.sha }}"
echo "👤 Actor: ${{ github.actor }}"
echo "⏰ Timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo ""
echo "::notice title=Workflow Rerun Detected::This is attempt #${{ github.run_attempt }} of workflow '${{ github.workflow }}'"

View file

@ -2,6 +2,11 @@
[ What changed? Feel free to be brief. ]
## AI Code Review
- **Team members only**: AI review runs automatically when PR is opened or marked ready for review
- Team members can also trigger a review by commenting `@continue-general-review` or `@continue-detailed-review`
## Checklist
- [] I've read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md)

View file

@ -14,7 +14,7 @@ jobs:
uses: pozil/auto-assign-issue@v2
with:
repo-token: ${{ secrets.CI_GITHUB_TOKEN }}
assignees: Patrick-Erichsen,tomasz-stefaniak,RomneyDa,tingwai
assignees: Patrick-Erichsen,tomasz-stefaniak,RomneyDa,tingwai,uinstinct
numOfAssignee: 1
# - name: "Add default labels"
# uses: actions-ecosystem/action-add-labels@v1

View file

@ -16,7 +16,7 @@ jobs:
contents: write # Needed for creating releases
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Get version from package.json
id: get_version
@ -45,7 +45,7 @@ jobs:
contents: write # Needed for creating releases
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0

115
.github/workflows/beta-release.yml vendored Normal file
View file

@ -0,0 +1,115 @@
name: Beta Release
on:
schedule:
# Run every day at 9am UTC
- cron: "0 9 * * *"
workflow_dispatch:
# Allow manual triggering
permissions:
contents: write
issues: write
pull-requests: write
jobs:
beta-release:
name: Beta Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v5
with:
fetch-depth: 0
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
registry-url: "https://registry.npmjs.org"
always-auth: true
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
uses: ./.github/actions/setup-component
with:
component: core
include-root: true
- name: Build core
run: |
cd core
npm run build
- name: Install CLI dependencies
working-directory: extensions/cli
run: npm ci
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Get current version
id: get_version
working-directory: extensions/cli
run: |
# Get the latest version from package.json or npm registry
CURRENT_VERSION=$(node -p "require('./package.json').version")
if [[ "$CURRENT_VERSION" == "0.0.0-dev" ]]; then
# If it's dev version, get latest from npm registry
LATEST_VERSION=$(npm view @continuedev/cli version --silent 2>/dev/null || echo "0.0.0")
echo "Using latest npm version: $LATEST_VERSION"
CURRENT_VERSION=$LATEST_VERSION
fi
# Create beta version with current date
DATE_SUFFIX=$(date -u +%Y%m%d)
BETA_VERSION="${CURRENT_VERSION}-beta.${DATE_SUFFIX}"
# Check if this version already exists on npm
if npm view @continuedev/cli@$BETA_VERSION version --silent >/dev/null 2>&1; then
echo "Version $BETA_VERSION already exists, adding timestamp"
# Add hour and minute to make it unique
TIMESTAMP_SUFFIX=$(date -u +%Y%m%d.%H%M)
BETA_VERSION="${CURRENT_VERSION}-beta.${TIMESTAMP_SUFFIX}"
echo "Using timestamped version: $BETA_VERSION"
fi
echo "current_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT
echo "beta_version=$BETA_VERSION" >> $GITHUB_OUTPUT
echo "date_suffix=$DATE_SUFFIX" >> $GITHUB_OUTPUT
- name: Update package.json for beta
working-directory: extensions/cli
run: |
# Update version in package.json
npm version ${{ steps.get_version.outputs.beta_version }} --no-git-tag-version
- name: Build
working-directory: extensions/cli
run: npm run build
- name: Publish beta to npm
working-directory: extensions/cli
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
npm publish --tag beta
echo "Published beta version: ${{ steps.get_version.outputs.beta_version }}"
- name: Create beta release on GitHub
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
run: |
# Create a git tag for the beta
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git tag "v${{ steps.get_version.outputs.beta_version }}"
git push origin "v${{ steps.get_version.outputs.beta_version }}"
# Create GitHub release
gh release create "v${{ steps.get_version.outputs.beta_version }}" \
--title "Beta Release v${{ steps.get_version.outputs.beta_version }}" \
--notes "Daily beta release for testing. This version will be promoted to stable after 7 days if no critical issues are found." \
--prerelease

View file

@ -27,5 +27,5 @@ jobs:
path-to-document: "https://github.com/continuedev/continue/blob/main/CLA.md"
branch: cla-signatures
# Bots and CLAs signed outside of GitHub
allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline
allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline,agent@continue.dev
signed-commit-message: "CLA signed in $pullRequestNo"

135
.github/workflows/cli-pr-checks.yml vendored Normal file
View file

@ -0,0 +1,135 @@
name: CLI PR Checks
on:
pull_request:
branches: [main]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
track-rerun:
runs-on: ubuntu-latest
if: github.run_attempt > 1
steps:
- uses: actions/checkout@v5
- name: Track workflow rerun
uses: ./.github/actions/track-rerun
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: "npm"
cache-dependency-path: extensions/cli/package-lock.json
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
uses: ./.github/actions/setup-component
with:
component: core
include-root: true
- name: Build core
run: |
cd core
npm run build
- name: Install dependencies
run: |
cd extensions/cli
npm ci --include=optional
- name: Run linting
run: |
cd extensions/cli
npm run lint
test:
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [18, 20, 22, 24]
runs-on: ${{ matrix.os }}
steps:
- name: Checkout code
uses: actions/checkout@v5
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- name: Cache CLI node_modules
uses: actions/cache@v4
with:
path: extensions/cli/node_modules
key: ${{ runner.os }}-node${{ matrix.node-version }}-cli-modules-${{ hashFiles('extensions/cli/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node${{ matrix.node-version }}-cli-modules-
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
uses: ./.github/actions/setup-component
with:
component: core
include-root: true
- name: Build core
run: |
cd core
npm run build
- name: Install dependencies
run: |
cd extensions/cli
npm ci --include=optional
- name: Build
run: |
cd extensions/cli
npm run build
- name: Run smoke tests
run: |
cd extensions/cli
npm run test:smoke
- name: Run tests
run: |
cd extensions/cli
npm test
# e2e tests are failing on Windows specifically - likely due to stdout flush issues
- name: Run e2e tests
if: matrix.os != 'windows-latest'
run: |
cd extensions/cli
npm run test:e2e
# GitHub does not have a way of requiring that all checks pass (you must manually select each job)
# This action at least lets us manage the list of required tests via source control
# so that creators of new jobs can add them to this list
require-all-checks-to-pass-cli:
if: always()
runs-on: ubuntu-latest
needs:
- lint
- test
steps:
- name: Decide whether the needed jobs succeeded or failed
uses: re-actors/alls-green@release/v1
with:
jobs: ${{ toJSON(needs) }}

View file

@ -36,7 +36,7 @@ jobs:
else
echo "❌ PR title does not follow conventional commit format"
echo "valid=false" >> $GITHUB_OUTPUT
exit 1
# Don't exit with failure - just mark as invalid for comment
fi
- name: Add PR title guidance comment
@ -101,7 +101,7 @@ jobs:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v4
@ -134,7 +134,7 @@ jobs:
if: ${{ !github.event.pull_request.draft }}
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Check required files
run: |

View file

@ -0,0 +1,25 @@
name: Continue Detailed Review
on:
pull_request:
types: [opened, ready_for_review]
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
detailed-code-review:
name: Continue Detailed Review
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Run Detailed PR Review
uses: continuedev/continue/actions/detailed-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: continuedev
continue-config: continuedev/review-bot

View file

@ -0,0 +1,25 @@
name: Continue General Review
on:
pull_request:
types: [opened, ready_for_review]
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
general-code-review:
name: Continue General Review
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Run Continue PR Review Action
uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "continuedev"
continue-config: "continuedev/review-bot"

View file

@ -1,32 +0,0 @@
name: Docs Check
on:
push:
paths:
- 'docs2/**'
pull_request:
paths:
- 'docs2/**'
jobs:
check-broken-links:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
cache-dependency-path: docs2/package-lock.json
- name: Install dependencies
working-directory: ./docs2
run: npm ci
- name: Check for broken links
working-directory: ./docs2
run: npx mintlify broken-links

View file

@ -56,7 +56,7 @@ jobs:
# steps:
# # 0. Setup git
# - name: Checkout
# uses: actions/checkout@v4
# uses: actions/checkout@v5
# - name: Set up Git
# run: |
@ -102,7 +102,7 @@ jobs:
steps:
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
ref: ${{ github.event.release.tag_name }}
@ -120,7 +120,7 @@ jobs:
# # Set up Java environment for the next steps
- name: Setup Java
uses: actions/setup-java@v4
uses: actions/setup-java@v5
with:
distribution: zulu
java-version: 17
@ -189,6 +189,8 @@ jobs:
cd ../../gui
npm ci
npm run build
env:
NODE_OPTIONS: "--max-old-space-size=8192"
# Run prepackage.js script
- name: Run prepackage script
@ -255,6 +257,7 @@ jobs:
# Publish the plugin to JetBrains Marketplace
- name: Publish EAP Plugin
if: github.event_name == 'release' || (github.event.inputs.eap_channel == 'true' && github.event.inputs.build_only != 'true')
continue-on-error: true
env:
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
@ -265,6 +268,7 @@ jobs:
- name: Publish Stable Plugin
if: github.event_name == 'release' || (github.event.inputs.stable_channel == 'true' && github.event.inputs.build_only != 'true')
continue-on-error: true
env:
PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }}
CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }}
@ -362,7 +366,7 @@ jobs:
steps:
# 1. Check-out repository
- name: Check-out repository
uses: actions/checkout@v4
uses: actions/checkout@v5
# 2. Install npm dependencies
- name: Use Node.js from .nvmrc
@ -429,11 +433,11 @@ jobs:
steps:
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
uses: actions/checkout@v5
# Set up Java environment for the next steps
- name: Setup Java
uses: actions/setup-java@v4
uses: actions/setup-java@v5
with:
distribution: zulu
java-version: 17
@ -456,12 +460,6 @@ jobs:
name: tests-result
path: ${{ github.workspace }}/extensions/intellij/build/reports/tests
# Upload the Kover report to CodeCov
# - name: Upload Code Coverage Report
# uses: codecov/codecov-action@v4
# with:
# files: ${{ github.workspace }}/build/reports/kover/report.xml
# Run Qodana inspections and provide report
inspectCode:
if: false
@ -482,18 +480,18 @@ jobs:
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
uses: actions/checkout@v5
# Set up Java environment for the next steps
- name: Setup Java
uses: actions/setup-java@v4
uses: actions/setup-java@v5
with:
distribution: zulu
java-version: 17
# Run Qodana inspections
- name: Qodana - Code Inspection
uses: JetBrains/qodana-action@v2025.1.1
uses: JetBrains/qodana-action@v2025.2.1
with:
cache-default-branch-only: true
@ -513,11 +511,11 @@ jobs:
# Check out current repository
- name: Fetch Sources
uses: actions/checkout@v4
uses: actions/checkout@v5
# Set up Java environment for the next steps
- name: Setup Java
uses: actions/setup-java@v4
uses: actions/setup-java@v5
with:
distribution: zulu
java-version: 17

View file

@ -13,7 +13,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Check if author is in tier list
id: check-author

View file

@ -18,23 +18,25 @@ jobs:
matrix:
platform: [Linux, macOS]
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 2 # Get the last 2 commits to find the merge commit
- name: Get merged PR number
id: get-pr
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
# Get the commit message of the merge commit
COMMIT_MSG=$(git log --format=%B -n 1 HEAD)
echo "Commit message: $COMMIT_MSG"
# Get PR number for the current commit using GitHub API
COMMIT_SHA=$(git rev-parse HEAD)
echo "Getting PR for commit: $COMMIT_SHA"
# Extract PR number from merge commit message (format: "Merge pull request #123 from...")
PR_NUMBER=$(echo "$COMMIT_MSG" | grep -o "Merge pull request #[0-9]*" | grep -o "[0-9]*" || echo "6723")
PR_NUMBER=$(curl -s -H "Authorization: token $GH_TOKEN" \
"https://api.github.com/repos/${{ github.repository }}/commits/$COMMIT_SHA/pulls" \
| jq -r '.[0].number // empty')
if [ -z "$PR_NUMBER" ]; then
echo "❌ Could not extract PR number from commit message. This might not be a PR merge."
echo "Commit message was: $COMMIT_MSG"
echo "❌ Could not find PR for commit $COMMIT_SHA"
exit 1
fi

View file

@ -9,7 +9,7 @@ on:
publish_build:
description: "Whether or not to publish the built extension to the VS Code marketplace"
required: true
default: false
default: "false"
jobs:
check_release_name:
@ -66,7 +66,7 @@ jobs:
arch: arm64
npm_config_arch: arm64
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0
@ -92,7 +92,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 0 # This ensures all tags are fetched
@ -112,7 +112,7 @@ jobs:
- build
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Set up Git
run: |
@ -145,7 +145,7 @@ jobs:
steps:
# 0. Setup git
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Set up Git
run: |

View file

@ -24,7 +24,7 @@ jobs:
runner: macos-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0

View file

@ -11,10 +11,18 @@ on:
- main
jobs:
track-rerun:
runs-on: ubuntu-latest
if: github.run_attempt > 1
steps:
- uses: actions/checkout@v5
- name: Track workflow rerun
uses: ./.github/actions/track-rerun
prettier-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -35,7 +43,7 @@ jobs:
core-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
@ -71,7 +79,7 @@ jobs:
gui-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
@ -101,7 +109,7 @@ jobs:
binary-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
@ -123,7 +131,7 @@ jobs:
vscode-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Setup core component
@ -156,7 +164,7 @@ jobs:
outputs:
packages: ${{ steps.get-packages.outputs.packages }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Get package list
id: get-packages
run: |
@ -171,7 +179,7 @@ jobs:
matrix:
package: ${{ fromJson(needs.get-packages-matrix.outputs.packages) }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Setup packages
uses: ./.github/actions/setup-packages
@ -197,7 +205,7 @@ jobs:
outputs:
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -257,7 +265,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0
@ -289,7 +297,7 @@ jobs:
test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }}
command: ["e2e:ci:run", "e2e:ci:run-yaml"]
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Run VS Code E2E test
uses: ./.github/actions/run-vscode-e2e-test
with:
@ -303,7 +311,7 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Run JetBrains tests
uses: ./.github/actions/run-jetbrains-tests
with:
@ -312,6 +320,32 @@ jobs:
# GitHub does not have a way of requiring that all checks pass (you must manually select each job)
# This action at least lets us manage the list of required tests via source control
pr-review-action-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Cache PR review action node modules
uses: actions/cache@v4
id: pr-review-cache
with:
path: actions/detailed-review/node_modules
key: ${{ runner.os }}-pr-review-action-${{ hashFiles('actions/detailed-review/package.json') }}
- name: Install dependencies
if: steps.pr-review-cache.outputs.cache-hit != 'true'
run: |
cd actions/detailed-review
npm install
- name: Run tests
run: |
cd actions/detailed-review
npm test
# so that creators of new jobs can add them to this list
require-all-checks-to-pass:
if: always()
@ -328,6 +362,7 @@ jobs:
- vscode-package-extension-linux
- vscode-e2e-tests
- jetbrains-tests
- pr-review-action-tests
steps:
- name: Decide whether the needed jobs succeeded or failed

View file

@ -9,7 +9,7 @@ on:
publish_build:
description: "Whether or not to publish the built extension to the VS Code marketplace"
required: true
default: false
default: "false"
jobs:
check_release_name:
@ -20,7 +20,7 @@ jobs:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v1.1.*-vscode ]]; then
if [[ "${{ github.event.release.tag_name }}" == v1.3.*-vscode ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT
@ -66,7 +66,7 @@ jobs:
arch: arm64
npm_config_arch: arm64
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 0
@ -96,7 +96,7 @@ jobs:
- build
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Set up Git
run: |
@ -131,7 +131,7 @@ jobs:
steps:
# 0. Setup git
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Set up Git
run: |

View file

@ -47,10 +47,13 @@ jobs:
working-directory: ${{ inputs.package-path }}
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Setup packages
uses: ./.github/actions/setup-packages
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
with:

View file

@ -7,6 +7,8 @@ on:
jobs:
analyze:
# Disabling for now due to bugs
if: false
runs-on: ubuntu-latest
permissions:
issues: write
@ -14,30 +16,30 @@ jobs:
steps:
- name: Checkout deja-view
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
repository: 'bdougie/deja-view'
repository: "bdougie/deja-view"
# Option 1: Pin to specific commit (most secure)
ref: '45e7696' # Pin to specific commit for stability
ref: "45e7696" # Pin to specific commit for stability
# Option 2: Use a tag (recommended after creating releases)
# ref: 'v1.0.0'
# Option 3: Use main branch (least secure, gets latest changes)
# ref: 'main'
path: deja-view
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
python-version: "3.11"
- name: Install dependencies
run: |
cd deja-view
pip install -r requirements.txt
- name: Index repository if needed
env:
CHROMA_API_KEY: ${{ secrets.CHROMA_CLOUD_API_KEY }}
@ -46,10 +48,10 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
cd deja-view
# Index the repository (this will update existing index)
python cli.py index "${{ github.repository }}" --max-issues 200 || true
- name: Search for similar issues
id: search
env:
@ -59,7 +61,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
cd deja-view
# Determine if this is an issue or PR
if [ "${{ github.event_name }}" = "pull_request" ]; then
ISSUE_URL="https://github.com/${{ github.repository }}/pull/${{ github.event.pull_request.number }}"
@ -70,26 +72,26 @@ jobs:
THRESHOLD="0.7"
TOP_K="5"
fi
# Create a Python script to search and format as JSON
cat << 'PYTHON_SCRIPT' > search_similar.py
import sys
import json
import os
from github_similarity_service import SimilarityService
issue_url = sys.argv[1]
threshold = float(sys.argv[2])
top_k = int(sys.argv[3])
# Parse issue number from URL
issue_number = int(issue_url.split('/')[-1])
repo_parts = issue_url.split('/')
owner = repo_parts[3]
repo = repo_parts[4]
service = SimilarityService()
# Find similar issues
similar = service.find_similar_issues(
owner=owner,
@ -98,26 +100,26 @@ jobs:
top_k=top_k,
min_similarity=threshold
)
# Format as JSON
print(json.dumps(similar))
PYTHON_SCRIPT
# Search for similar issues
SIMILAR_ISSUES=$(python search_similar.py "$ISSUE_URL" "$THRESHOLD" "$TOP_K")
# Save to output
echo "similar_issues<<EOF" >> $GITHUB_OUTPUT
echo "$SIMILAR_ISSUES" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
# Check if any similar issues found
if [ "$(echo "$SIMILAR_ISSUES" | jq '. | length')" -gt 0 ]; then
echo "has_similar=true" >> $GITHUB_OUTPUT
else
echo "has_similar=false" >> $GITHUB_OUTPUT
fi
- name: Check if issue should be a discussion
id: discussion_check
if: github.event_name == 'issues'
@ -128,19 +130,19 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
cd deja-view
# Create a Python script to analyze the issue
cat << 'PYTHON_SCRIPT' > check_discussion.py
import os
import json
import re
from github_similarity_service import SimilarityService
# Get issue details from environment
issue_title = os.environ.get('ISSUE_TITLE', '')
issue_body = os.environ.get('ISSUE_BODY', '')
issue_labels = json.loads(os.environ.get('ISSUE_LABELS', '[]'))
# Mock Issue object for analysis
class MockIssue:
def __init__(self):
@ -152,41 +154,41 @@ jobs:
self.created_at = ''
self.updated_at = ''
self.url = ''
service = SimilarityService()
issue = MockIssue()
score, reasons = service._calculate_discussion_score(issue)
result = {
'score': score,
'reasons': reasons,
'should_be_discussion': score >= 0.5,
'confidence': 'high' if score >= 0.7 else 'medium' if score >= 0.5 else 'low'
}
print(json.dumps(result))
PYTHON_SCRIPT
# Run the analysis
DISCUSSION_ANALYSIS=$(ISSUE_TITLE="${{ github.event.issue.title }}" \
ISSUE_BODY='${{ github.event.issue.body }}' \
ISSUE_LABELS='${{ toJson(github.event.issue.labels.*.name) }}' \
ISSUE_NUMBER="${{ github.event.issue.number }}" \
python check_discussion.py)
echo "analysis<<EOF" >> $GITHUB_OUTPUT
echo "$DISCUSSION_ANALYSIS" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
# Extract whether it should be a discussion
SHOULD_BE_DISCUSSION=$(echo "$DISCUSSION_ANALYSIS" | jq -r '.should_be_discussion')
echo "should_be_discussion=$SHOULD_BE_DISCUSSION" >> $GITHUB_OUTPUT
# Extract confidence level
CONFIDENCE=$(echo "$DISCUSSION_ANALYSIS" | jq -r '.confidence')
echo "confidence=$CONFIDENCE" >> $GITHUB_OUTPUT
- name: Comment with analysis
uses: actions/github-script@v7
with:
@ -195,7 +197,7 @@ jobs:
const hasSimilar = '${{ steps.search.outputs.has_similar }}' === 'true';
const isPR = '${{ github.event_name }}' === 'pull_request';
const shouldBeDiscussion = !isPR && '${{ steps.discussion_check.outputs.should_be_discussion }}' === 'true';
// Add similar issues section if found
if (hasSimilar) {
const similarIssues = JSON.parse(`${{ steps.search.outputs.similar_issues }}`);
@ -243,7 +245,7 @@ jobs:
comment += '\n';
}
}
// Add discussion suggestion if applicable
if (shouldBeDiscussion) {
const analysis = JSON.parse(`${{ steps.discussion_check.outputs.analysis }}`);
@ -280,7 +282,7 @@ jobs:
comment += '_Consider converting this to a discussion if it\'s not a bug report or actionable task._\n';
}
// Only comment if we have something to say
if (comment) {
comment += '\n---\n';
@ -302,14 +304,14 @@ jobs:
});
}
}
- name: Add labels
if: github.event_name == 'issues'
uses: actions/github-script@v7
with:
script: |
const labels = [];
// Check for duplicate
if ('${{ steps.search.outputs.has_similar }}' === 'true') {
const similarIssues = JSON.parse(`${{ steps.search.outputs.similar_issues }}`);
@ -319,7 +321,7 @@ jobs:
labels.push('potential-duplicate');
}
}
// Check for discussion suggestion
if ('${{ steps.discussion_check.outputs.should_be_discussion }}' === 'true') {
const confidence = '${{ steps.discussion_check.outputs.confidence }}';
@ -330,7 +332,7 @@ jobs:
labels.push('discussion');
}
}
// Add labels if any
if (labels.length > 0) {
await github.rest.issues.addLabels({

222
.github/workflows/stable-release.yml vendored Normal file
View file

@ -0,0 +1,222 @@
name: Stable Release
on:
schedule:
# Run every Monday at 10am UTC (1 hour after beta release)
- cron: "0 10 * * 1"
workflow_dispatch:
inputs:
release_type:
description: "Release type"
required: true
type: choice
options:
- "promote-beta"
- "direct-stable"
default: "promote-beta"
beta_version:
description: "Specific beta version to promote (required if release_type is 'promote-beta')"
required: false
type: string
stable_version:
description: "Version for direct stable release (e.g., 1.2.3) - required if release_type is 'direct-stable'"
required: false
type: string
permissions:
contents: write
issues: write
pull-requests: write
jobs:
stable-release:
name: Stable Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v5
with:
fetch-depth: 0
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
registry-url: "https://registry.npmjs.org"
always-auth: true
- name: Validate inputs
run: |
RELEASE_TYPE="${{ inputs.release_type || 'promote-beta' }}"
echo "Release type: $RELEASE_TYPE"
if [[ "$RELEASE_TYPE" == "direct-stable" ]]; then
if [[ -z "${{ inputs.stable_version }}" ]]; then
echo "Error: stable_version is required for direct-stable release type"
exit 1
fi
echo "Direct stable release version: ${{ inputs.stable_version }}"
elif [[ "$RELEASE_TYPE" == "promote-beta" ]]; then
echo "Beta promotion release (beta_version: ${{ inputs.beta_version }})"
else
echo "Error: Invalid release type: $RELEASE_TYPE"
exit 1
fi
- name: Find beta version to promote
if: ${{ (inputs.release_type || 'promote-beta') == 'promote-beta' }}
id: find_beta
working-directory: extensions/cli
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [[ -n "${{ inputs.beta_version }}" ]]; then
# Manual input provided
BETA_VERSION="${{ inputs.beta_version }}"
echo "Using manually specified beta version: $BETA_VERSION"
else
# Find beta version that's at least 7 days old
SEVEN_DAYS_AGO=$(date -u -d '7 days ago' +%Y%m%d)
echo "Looking for beta versions from $SEVEN_DAYS_AGO or earlier"
# Get all beta versions from npm
BETA_VERSIONS=$(npm view @continuedev/cli versions --json | jq -r '.[] | select(contains("-beta."))' | sort -V)
CANDIDATE_VERSION=""
for version in $BETA_VERSIONS; do
# Extract date from beta version (format: x.y.z-beta.YYYYMMDD)
if [[ $version =~ -beta\.([0-9]{8}) ]]; then
BETA_DATE="${BASH_REMATCH[1]}"
if [[ $BETA_DATE -le $SEVEN_DAYS_AGO ]]; then
CANDIDATE_VERSION=$version
fi
fi
done
if [[ -z "$CANDIDATE_VERSION" ]]; then
echo "No beta version found that is at least 7 days old"
exit 1
fi
BETA_VERSION=$CANDIDATE_VERSION
echo "Selected beta version for promotion: $BETA_VERSION"
fi
# Extract base version (remove -beta.YYYYMMDD suffix)
STABLE_VERSION=$(echo "$BETA_VERSION" | sed 's/-beta\.[0-9]\{8\}//')
echo "beta_version=$BETA_VERSION" >> $GITHUB_OUTPUT
echo "stable_version=$STABLE_VERSION" >> $GITHUB_OUTPUT
- name: Set version for direct stable release
if: ${{ inputs.release_type == 'direct-stable' }}
id: direct_stable
run: |
echo "stable_version=${{ inputs.stable_version }}" >> $GITHUB_OUTPUT
- name: Download and verify beta package
if: ${{ (inputs.release_type || 'promote-beta') == 'promote-beta' }}
working-directory: extensions/cli
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
# Download the specific beta version
npm pack @continuedev/cli@${{ steps.find_beta.outputs.beta_version }}
# Extract and verify the package
PACKAGE_FILE=$(ls continuedev-cli-*.tgz)
tar -xzf "$PACKAGE_FILE"
echo "Beta package contents verified"
ls -la package/
- name: Prepare package for beta promotion
if: ${{ (inputs.release_type || 'promote-beta') == 'promote-beta' }}
working-directory: extensions/cli
run: |
# Copy the beta package contents
cp -r package/* .
# Update version to stable (remove beta suffix)
npm version ${{ steps.find_beta.outputs.stable_version }} --no-git-tag-version
- name: Setup packages (for direct stable release)
if: ${{ inputs.release_type == 'direct-stable' }}
uses: ./.github/actions/setup-packages
- name: Setup core component (for direct stable release)
if: ${{ inputs.release_type == 'direct-stable' }}
uses: ./.github/actions/setup-component
with:
component: core
include-root: true
- name: Build core
run: |
cd core
npm run build
- name: Prepare package for direct stable release
if: ${{ inputs.release_type == 'direct-stable' }}
working-directory: extensions/cli
run: |
# Install dependencies for direct build
npm ci
# Update version to the specified stable version
npm version ${{ inputs.stable_version }} --no-git-tag-version
- name: Build (verification step)
working-directory: extensions/cli
run: npm run build
- name: Run tests (verification step)
working-directory: extensions/cli
run: npm test
- name: Set final version
id: final_version
run: |
if [[ "${{ inputs.release_type || 'promote-beta' }}" == "direct-stable" ]]; then
STABLE_VERSION="${{ steps.direct_stable.outputs.stable_version }}"
RELEASE_NOTES="Direct stable release from main branch. Version $STABLE_VERSION built and published directly from the latest main branch."
else
STABLE_VERSION="${{ steps.find_beta.outputs.stable_version }}"
RELEASE_NOTES="Stable release promoted from tested beta version ${{ steps.find_beta.outputs.beta_version }}. This version has been thoroughly tested in beta for at least 7 days."
fi
echo "stable_version=$STABLE_VERSION" >> $GITHUB_OUTPUT
echo "release_notes=$RELEASE_NOTES" >> $GITHUB_OUTPUT
- name: Publish stable to npm
working-directory: extensions/cli
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
npm publish --tag latest
echo "Published stable version: ${{ steps.final_version.outputs.stable_version }}"
- name: Create stable release on GitHub
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
run: |
# Create a git tag for the stable release
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git tag "v${{ steps.final_version.outputs.stable_version }}"
git push origin "v${{ steps.final_version.outputs.stable_version }}"
# Create GitHub release
gh release create "v${{ steps.final_version.outputs.stable_version }}" \
--title "Stable Release v${{ steps.final_version.outputs.stable_version }}" \
--notes "${{ steps.final_version.outputs.release_notes }}" \
--latest
- name: Update GitHub release notes for beta promotion
if: ${{ (inputs.release_type || 'promote-beta') == 'promote-beta' }}
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
run: |
# Mark the original beta release as superseded
gh release edit "v${{ steps.find_beta.outputs.beta_version }}" \
--notes "This beta version has been promoted to stable as v${{ steps.final_version.outputs.stable_version }}."

View file

@ -12,9 +12,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
uses: actions/checkout@v5
- name: Setup Java
uses: actions/setup-java@v4
uses: actions/setup-java@v5
with:
distribution: "temurin"
java-version: 17

View file

@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 0 # Fetch all history and tags

2
.gitignore vendored
View file

@ -158,6 +158,7 @@ extensions/intellij/.idea/**
**/.idea/shelf/
**/.idea/inspectionProfiles/Project_Default.xml
**/.idea/php.xml
**/.idea/kotlinc.xml
extensions/intellij/bin
@ -170,4 +171,5 @@ extensions/.continue-debug/
.continuerules
**/.continue/assistants/
**/.continue/agents/
keys

6
.idea/kotlinc.xml generated
View file

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinJpsPluginSettings">
<option name="version" value="1.8.0" />
</component>
</project>

43
.vscode/launch.json vendored
View file

@ -131,6 +131,49 @@
"env": {
"NODE_OPTIONS": "--experimental-vm-modules"
}
},
{
"name": "Debug CLI",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/extensions/cli/src/index.ts",
"args": [],
"env": {
"NODE_ENV": "development"
// "CONTINUE_API_BASE": "http://localhost:3001/",
// "WORKOS_CLIENT_ID": "client_01J0FW6XCPMJMQ3CG51RB4HBZQ",
// "HUB_URL": "http://localhost:3000"
},
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"skipFiles": ["<node_internals>/**"],
"runtimeArgs": ["--loader", "ts-node/esm"],
"sourceMaps": true,
"resolveSourceMapLocations": [
"${workspaceFolder}/**",
"!**/node_modules/**"
],
"preLaunchTask": "watch-logs",
"cwd": "${workspaceFolder}/extensions/cli"
},
{
"name": "Debug CLI Tests",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/extensions/cli/node_modules/.bin/vitest",
"args": ["--run", "--no-cache"],
"env": {
"NODE_ENV": "test"
},
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"skipFiles": ["<node_internals>/**"],
"sourceMaps": true,
"resolveSourceMapLocations": [
"${workspaceFolder}/**",
"!**/node_modules/**"
],
"cwd": "${workspaceFolder}/extensions/cli"
}
]
}

View file

@ -42,7 +42,8 @@
"extensions/vscode/e2e/_output": true,
"extensions/vscode/e2e/storage": true,
"extensions/vscode/e2e/vsix": true,
"extensions/.continue-debug": true
"extensions/.continue-debug": true,
"extensions/cli/dist/**": true
// "sync/**": true
},
"editor.formatOnSave": true,

62
.vscode/tasks.json vendored
View file

@ -311,6 +311,68 @@
"close": true,
"focus": false
}
},
{
"label": "cli:build",
"type": "npm",
"script": "build",
"group": "build",
"presentation": {
"echo": true,
"reveal": "silent",
"focus": false,
"panel": "shared",
"showReuseMessage": true,
"clear": false
},
"problemMatcher": ["$tsc"],
"options": {
"cwd": "${workspaceFolder}/extensions/cli"
}
},
{
"label": "cli:test",
"type": "npm",
"script": "test",
"group": "test",
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared",
"showReuseMessage": true,
"clear": false
},
"options": {
"cwd": "${workspaceFolder}/extensions/cli"
}
},
{
"label": "watch-logs",
"type": "shell",
"command": "npm run watch:logs",
"isBackground": true,
"problemMatcher": {
"pattern": {
"regexp": "^$",
"file": 1,
"location": 2,
"message": 3
},
"background": {
"activeOnStart": true,
"beginsPattern": "^.*$",
"endsPattern": "^.*$"
}
},
"presentation": {
"reveal": "always",
"panel": "new",
"focus": false
},
"options": {
"cwd": "${workspaceFolder}/extensions/cli"
}
}
]
}

View file

@ -288,4 +288,4 @@ We require all contributors to accept the CLA and have made it as easy as commen
I have read the CLA Document and I hereby sign the CLA
```
3. The CLA‑Assistant bot records your signature in the repo and marks the status check as passed.
3. The CLA-Assistant bot records your signature in the repo and marks the status check as passed.

View file

@ -8,15 +8,6 @@
<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, and MCP tools](https://hub.continue.dev)**
</div>
<div align="center">
<a target="_blank" href="https://opensource.org/licenses/Apache-2.0" style="background:none">
<img src="https://img.shields.io/badge/License-Apache_2.0-blue.svg" style="height: 22px;" />
</a>
@ -32,38 +23,42 @@ and [hub of models, rules, and MCP tools](https://hub.continue.dev)**
<p></p>
<div align="center">
**Ship faster with Continuous AI**
**Build and run custom agents across your IDE, terminal, and CI**
</div>
Get started in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue), [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension), or [CLI](https://docs.continue.dev/guides/cli)
## Agent
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
[Agent](/features/agent/quick-start) to work on development tasks together with AI
![agent](docs/images/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](/features/chat/quick-start) to ask general questions and clarify code sections
![chat](docs/images/chat.gif)
## Edit
[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current
file
[Edit](/features/edit/quick-start) to modify a code section without leaving your current file
![edit](docs/images/edit.gif)
## Autocomplete
[Autocomplete](https://continue.dev/docs/autocomplete/how-to-use-it) provides inline code suggestions as you type
[Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type
![autocomplete](docs/images/autocomplete.gif)
</div>
## Getting Started
Learn about how to install and use Continue in the docs [here](https://continue.dev/docs/getting-started/install)
## Contributing
Read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and

251
actions/README.md Normal file
View file

@ -0,0 +1,251 @@
# Continue PR Review Actions
GitHub Actions that provide automated code reviews for pull requests using Continue CLI.
## Available Actions
This repository provides two GitHub Actions for different review styles:
### 1. General Review Action
Provides high-level PR assessment with overall feedback and recommendations.
- **Path:** `continuedev/continue/actions/general-review@<commit-sha>`
- **Trigger:** `@continue-general-review`
- **Output:** Summary comment with strengths, issues, and recommendations
### 2. Detailed Review Action
Provides line-by-line inline comments on specific code changes.
- **Path:** `continuedev/continue/actions/detailed-review@<commit-sha>`
- **Trigger:** `@continue-detailed-review`
- **Output:** Inline review comments on specific lines of code
## Quick Start
### Using Both Actions Together
```yaml
name: PR Reviews
on:
pull_request:
types: [opened, ready_for_review]
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
general-review:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: continuedev/continue/actions/general-review@<commit-sha>
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "your-org-name"
continue-config: "your-org-name/review-bot"
detailed-review:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: continuedev/continue/actions/detailed-review@<commit-sha>
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "your-org-name"
continue-config: "your-org-name/review-bot"
```
### General Review Only
```yaml
name: PR General Review
on:
pull_request:
types: [opened, ready_for_review]
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
review:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: continuedev/continue/actions/general-review@<commit-sha>
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "your-org-name"
continue-config: "your-org-name/review-bot"
```
### Detailed Review Only
```yaml
name: PR Detailed Review
on:
pull_request:
types: [opened, ready_for_review]
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
issues: write
jobs:
review:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: continuedev/continue/actions/detailed-review@<commit-sha>
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "your-org-name"
continue-config: "your-org-name/review-bot"
```
## Inputs
Both actions accept the same inputs:
| Input | Description | Required |
| ------------------ | -------------------------------------- | -------- |
| `continue-api-key` | API key for Continue service | Yes |
| `continue-org` | Organization for Continue config | Yes |
| `continue-config` | Config path (e.g., "myorg/review-bot") | Yes |
## Setup Requirements
### 1. Continue API Key
Add your Continue API key as a secret named `CONTINUE_API_KEY` in your repository:
1. Go to your repository's Settings
2. Navigate to Secrets and variables → Actions
3. Click "New repository secret"
4. Name: `CONTINUE_API_KEY`
5. Value: Your Continue API key
### 2. Continue Configuration
Set up your review bot configuration in Continue:
1. Create a configuration for your organization
2. Configure the review bot settings
3. Note your organization name and config path
### 3. Workflow Permissions
The workflow requires these permissions:
- `contents: read` - To checkout and read repository code
- `pull-requests: write` - To post review comments on PRs
- `issues: write` - To respond to comment triggers
## Triggering Reviews
Both actions can be triggered in two ways:
### Automatic Triggers
- When a PR is opened by a team member (OWNER, MEMBER, or COLLABORATOR)
- When a PR is marked as "ready for review" by a team member
### Manual Triggers
Team members can trigger reviews by commenting on any pull request:
- `@continue-general-review` - Triggers a general review
- `@continue-detailed-review` - Triggers a detailed inline review
## Review Outputs
### General Review Output
The general review provides a structured comment that includes:
- **Strengths**: What was done well in the PR
- **Issues Found**: Categorized by severity (Critical, High, Medium, Low)
- **Suggestions**: Improvement recommendations
- **Overall Assessment**: Final recommendation (APPROVE, REQUEST_CHANGES, or COMMENT)
### Detailed Review Output
The detailed review provides:
- **Inline Comments**: Specific feedback on individual lines of code
- **Position Markers**: Comments appear directly on the changed lines
- **Review Summary**: Overall assessment of the changes
- **Actionable Feedback**: Specific suggestions for each issue found
## How It Works
### General Review Process
1. Checks out repository code
2. Fetches PR diff using GitHub CLI
3. Generates a comprehensive review prompt
4. Runs Continue CLI with specified configuration
5. Posts review as a PR comment
### Detailed Review Process
1. Checks out repository code
2. Fetches PR diff with GitHub API positions
3. Annotates diff with position markers
4. Generates inline review prompt
5. Runs Continue CLI for detailed analysis
6. Posts inline comments using GitHub's review API
## Versioning
We recommend using a specific commit SHA for stability and predictability:
- `@<commit-sha>` - Pins to a specific commit for maximum stability (recommended)
- `@main` - Uses the latest code from the main branch (for bleeding edge)
- `@v1` - Uses a version tag when available
Example:
```yaml
uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe
```
## Troubleshooting
### Review not triggering
- Ensure the PR author or commenter has appropriate permissions (OWNER, MEMBER, or COLLABORATOR)
- Check that the workflow file is in the default branch
- Verify the Continue API key is correctly set as a repository secret
### No review output generated
- Check the action logs for any errors
- Verify your Continue configuration is correct
- Ensure your Continue API key is valid
### Inline comments not appearing (Detailed Review)
- Check that the PR has a valid diff
- Verify GitHub API permissions are correct
- Review action logs for position calculation errors
## Support
For issues or questions:
- [Continue Documentation](https://docs.continue.dev)
- [GitHub Issues](https://github.com/continuedev/continue/issues)
- [Discord Community](https://discord.gg/vapESyrFmJ)

View file

@ -0,0 +1,375 @@
name: 'Continue Detailed PR Review'
description: 'Automated inline code review for pull requests using Continue CLI'
author: 'Continue Dev, Inc.'
inputs:
continue-api-key:
description: 'API key for Continue service'
required: true
continue-org:
description: 'Organization for Continue config'
required: true
continue-config:
description: 'Config path to use (e.g., "myorg/review-bot")'
required: true
runs:
using: 'composite'
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Check Authorization
shell: bash
env:
# Only move the dangerous check to env to prevent shell injection
HAS_TRIGGER_PHRASE: ${{ contains(github.event.comment.body, '@continue-detailed-review') }}
run: |
# Check if this action should run based on event type and user permissions
SHOULD_RUN="false"
if [ "${{ github.event_name }}" = "pull_request" ]; then
# Check if PR is a draft
if [ "${{ github.event.pull_request.draft }}" = "true" ]; then
echo "::notice::Skipping review - PR is a draft"
else
# Check PR author association
AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}"
if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then
SHOULD_RUN="true"
else
echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)"
fi
fi
elif [ "${{ github.event_name }}" = "issue_comment" ]; then
# Check if it's a PR comment with the trigger phrase
if [ "${{ github.event.issue.pull_request }}" != "" ] && [ "$HAS_TRIGGER_PHRASE" = "true" ]; then
COMMENTER_ASSOC="${{ github.event.comment.author_association }}"
if [ "$COMMENTER_ASSOC" = "OWNER" ] || [ "$COMMENTER_ASSOC" = "MEMBER" ] || [ "$COMMENTER_ASSOC" = "COLLABORATOR" ]; then
SHOULD_RUN="true"
else
echo "::notice::Skipping review - Commenter is not a team member (association: $COMMENTER_ASSOC)"
fi
else
echo "::notice::Skipping review - Comment does not contain @continue-detailed-review trigger, or is not on a PR"
fi
else
echo "::notice::Skipping review - Event type ${{ github.event_name }} is not supported"
fi
if [ "$SHOULD_RUN" != "true" ]; then
echo "SKIP_REVIEW=true" >> $GITHUB_ENV
exit 0
fi
echo "SKIP_REVIEW=false" >> $GITHUB_ENV
- name: Setup Node.js
if: env.SKIP_REVIEW != 'true'
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install Continue CLI
if: env.SKIP_REVIEW != 'true'
shell: bash
run: npm install -g @continuedev/cli@1.4.25
- name: Build Inline Review Prompt
if: env.SKIP_REVIEW != 'true'
shell: bash
env:
GH_TOKEN: ${{ github.token }}
run: |
# Get PR number based on event type
if [ "${{ github.event_name }}" = "pull_request" ]; then
PR_NUMBER="${{ github.event.number }}"
else
# For issue_comment event on a PR
PR_NUMBER="${{ github.event.issue.number }}"
fi
# Get PR files with line numbers
gh api repos/${{ github.repository }}/pulls/$PR_NUMBER/files > pr_files.json
# Get PR diff with context
gh pr diff $PR_NUMBER --color=never > pr_diff.txt
# Annotate diff with GitHub API positions
node ${{ github.action_path }}/annotate-diff.js pr_diff.txt > pr_diff_annotated.txt
# Debug: Show sample of annotated diff
echo "=== SAMPLE OF ANNOTATED DIFF ==="
head -100 pr_diff_annotated.txt | grep -E "^\[POS:|^@@|^diff --git" || head -50 pr_diff_annotated.txt
echo "=== END SAMPLE ==="
# Create review prompt for inline comments
cat > inline_review_prompt.txt << 'EOF'
You are conducting a detailed inline code review for a pull request.
Your task is to analyze the code changes and generate specific, actionable review comments for individual lines or small sections of code.
IMPORTANT: The diff below has been annotated with [POS:N] markers showing the exact position for each line.
Example of how to use the position markers:
```
diff --git a/src/app.js b/src/app.js
index abc123..def456 100644
--- a/src/app.js
+++ b/src/app.js
@@ -10,4 +10,6 @@ function example() {
[POS:1] console.log("context");
[POS:2] - const old = "remove this";
[POS:3] + const new = "add this";
[POS:4] + const risky = eval(userInput); <-- To comment here, use position: 4
[POS:5] return result;
[POS:6] + console.log("done");
@@ -20,3 +22,4 @@ function another() {
[POS:1] let x = 1;
[POS:2] + let y = 2; <-- To comment here, use position: 2
```
To comment on a line, simply use the number from its [POS:N] marker as the position value.
For example: {"path": "src/app.js", "position": 4, "body": "Avoid using eval with user input"}
Below is the annotated PR diff:
EOF
cat pr_diff_annotated.txt >> inline_review_prompt.txt
cat >> inline_review_prompt.txt << 'EOF'
Please analyze these changes and provide inline review comments in the following JSON format:
{
"review_summary": "Overall assessment of the PR",
"comments": [
{
"path": "path/to/file.js",
"position": 4,
"body": "Brief, specific comment about this line or section"
}
]
}
Focus on:
1. **Critical Issues**: Security vulnerabilities, bugs that will break functionality
2. **High Priority**: Performance problems, incorrect logic, missing error handling
3. **Medium Priority**: Code style violations, potential edge cases, unclear code
4. **Low Priority**: Suggestions for improvement, refactoring opportunities
Guidelines for comments:
- Be specific and actionable
- Use the [POS:N] number shown in the diff as the position value
- Keep comments concise but informative
- Suggest concrete improvements when pointing out issues
- Only comment on actual problems or important improvements
Important:
- Output ONLY valid JSON, no markdown code blocks or backticks
- Start your response with { and end with }
- Use the exact number from [POS:N] markers as the position
- Only comment on changed lines (lines with + or - prefix)
- Comment on the most important issues first
- Limit to maximum 20 most relevant comments
EOF
- name: Run Continue CLI Inline Review
if: env.SKIP_REVIEW != 'true'
shell: bash
env:
CONTINUE_API_KEY: ${{ inputs.continue-api-key }}
run: |
echo "Running Continue CLI for inline review..."
# Validate required inputs
if [ -z "${{ inputs.continue-org }}" ]; then
echo "Error: continue-org input is required"
exit 1
fi
if [ -z "${{ inputs.continue-config }}" ]; then
echo "Error: continue-config input is required"
exit 1
fi
# Log the prompt for debugging
echo "===== START REVIEW PROMPT ====="
head -n 50 inline_review_prompt.txt
echo "... [diff content] ..."
tail -n 20 inline_review_prompt.txt
echo "===== END REVIEW PROMPT ====="
# Run the CLI and capture JSON output
cn --readonly --format json --org "${{ inputs.continue-org }}" --config "${{ inputs.continue-config }}" -p "$(cat inline_review_prompt.txt)" > inline_review_raw.json
# Log the output for debugging
echo "Initial Continue CLI output:"
cat inline_review_raw.json
# Validate JSON output and use it directly
if ! jq empty inline_review_raw.json 2>/dev/null; then
echo "Error: Invalid JSON output from Continue CLI"
exit 1
fi
# Use the JSON output directly
cp inline_review_raw.json inline_review.json
echo "Review output:"
cat inline_review.json
- name: Post Inline Review Comments
if: env.SKIP_REVIEW != 'true'
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
try {
// Read the review output
let reviewData;
try {
const reviewContent = fs.readFileSync('inline_review.json', 'utf8');
reviewData = JSON.parse(reviewContent);
} catch (parseError) {
console.log('Failed to parse review JSON:', parseError);
reviewData = {
review_summary: 'AI review completed but failed to parse output',
comments: []
};
}
// Get PR number
let prNumber;
if (context.eventName === 'pull_request') {
prNumber = context.payload.pull_request.number;
} else {
prNumber = context.payload.issue.number;
}
// Get the latest commit SHA
const { data: pr } = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: prNumber
});
const commitSha = pr.head.sha;
// Prepare review comments - filter out comments without required fields
const allComments = reviewData.comments || [];
const validComments = allComments.filter(comment =>
comment.position &&
comment.path &&
comment.body &&
typeof comment.position === 'number' &&
comment.position > 0
);
if (validComments.length < allComments.length) {
console.log(`Filtered out ${allComments.length - validComments.length} comments due to missing/invalid position, path, or body`);
const invalidComments = allComments.filter(c => !validComments.includes(c));
console.log('Invalid comments:', JSON.stringify(invalidComments, null, 2));
}
// Deduplicate comments based on path + position + body
const uniqueComments = [];
const seen = new Set();
for (const comment of validComments) {
const key = `${comment.path}:${comment.position}:${comment.body}`;
if (!seen.has(key)) {
seen.add(key);
uniqueComments.push(comment);
}
}
if (uniqueComments.length < validComments.length) {
console.log(`Filtered out ${validComments.length - uniqueComments.length} duplicate comments (same path + position + body)`);
}
const comments = uniqueComments.map(comment => ({
path: comment.path,
position: comment.position,
body: comment.body
}));
// Debug: Log the positions we're trying to use
console.log('Attempting to post comments with positions:');
comments.forEach(c => {
console.log(` ${c.path}: position ${c.position}`);
});
// Create the review
if (comments.length > 0) {
try {
let reviewBody = `${reviewData.review_summary || 'AI Code Review'}\n\n---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`;
// Add triggered by note if from comment
if (context.eventName === 'issue_comment') {
reviewBody = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${reviewBody}`;
}
await github.rest.pulls.createReview({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: prNumber,
commit_id: commitSha,
body: reviewBody,
event: 'COMMENT',
comments: comments
});
console.log(`Successfully created review with ${comments.length} inline comments`);
} catch (reviewError) {
console.log('Failed to create review:', reviewError.message);
// Fallback: post as a regular comment if review creation fails
const fallbackBody = `## AI Code Review\n\n${reviewData.review_summary}\n\n` +
`*Failed to post ${comments.length} inline comments. Please review the changes manually.*\n\n` +
`---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`;
await github.rest.issues.createComment({
issue_number: prNumber,
owner: context.repo.owner,
repo: context.repo.repo,
body: fallbackBody
});
}
} else {
// No inline comments, just post the summary
let summaryBody = `## AI Code Review\n\n${reviewData.review_summary}\n\n*No specific line comments generated.*\n\n` +
`---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`;
// Add triggered by note if from comment
if (context.eventName === 'issue_comment') {
summaryBody = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${summaryBody}`;
}
await github.rest.issues.createComment({
issue_number: prNumber,
owner: context.repo.owner,
repo: context.repo.repo,
body: summaryBody
});
}
} catch (error) {
console.log('Failed to post review:', error.message);
console.log('Error details:', error);
}
env:
GITHUB_TOKEN: ${{ github.token }}
- name: Upload Review Artifacts
if: env.SKIP_REVIEW != 'true' && always()
uses: actions/upload-artifact@v4
with:
name: inline-review-results
path: |
inline_review_raw.json
inline_review.json
inline_review_prompt.txt
pr_diff.txt
pr_diff_annotated.txt
retention-days: 7

View file

@ -0,0 +1,96 @@
#!/usr/bin/env node
/**
* Annotates a git diff with GitHub API positions
*
* Takes a raw diff and adds [POS:N] markers with the correct
* GitHub API positions (cumulative, with +1 between hunks)
*/
const fs = require("fs");
function annotateDiff(diffContent) {
const lines = diffContent.split("\n");
const output = [];
let githubPos = 0;
let inHunk = false;
for (const line of lines) {
// Handle new file - reset position counter
if (line.startsWith("diff --git")) {
githubPos = 0;
inHunk = false;
output.push(line);
continue;
}
// Pass through other git headers unchanged
if (
line.startsWith("index ") ||
line.startsWith("---") ||
line.startsWith("+++") ||
line.startsWith("rename ") ||
line.startsWith("similarity ") ||
line.startsWith("new file") ||
line.startsWith("deleted file") ||
line.startsWith("old mode") ||
line.startsWith("new mode") ||
line.startsWith("Binary files")
) {
output.push(line);
continue;
}
// Handle hunk headers
if (line.startsWith("@@")) {
if (inHunk) {
githubPos++; // GitHub's +1 between hunks
}
inHunk = true;
output.push(line);
continue;
}
// Handle "no newline" marker - it counts as a position but isn't annotated
if (line.startsWith("\\ No newline")) {
if (inHunk) {
githubPos++; // GitHub counts this as a position
}
output.push(line); // Don't annotate it
continue;
}
// Annotate actual diff lines with GitHub positions
if (inHunk) {
githubPos++;
output.push(`[POS:${githubPos}] ${line}`);
} else {
output.push(line);
}
}
return output.join("\n");
}
// Main
function main() {
// Read diff from stdin or file
let input = "";
if (process.argv.length > 2) {
// Read from file
input = fs.readFileSync(process.argv[2], "utf8");
} else {
// Read from stdin
input = fs.readFileSync(0, "utf8");
}
const annotated = annotateDiff(input);
console.log(annotated);
}
if (require.main === module) {
main();
}
module.exports = { annotateDiff };

View file

@ -0,0 +1,363 @@
const { annotateDiff } = require("./annotate-diff.js");
describe("annotateDiff", () => {
test("single file, single hunk", () => {
const diff = `diff --git a/file.js b/file.js
index abc123..def456 100644
--- a/file.js
+++ b/file.js
@@ -1,3 +1,4 @@
line1
line2
+added line
line3`;
const result = annotateDiff(diff);
expect(result).toContain("[POS:1] line1");
expect(result).toContain("[POS:2] line2");
expect(result).toContain("[POS:3] +added line");
expect(result).toContain("[POS:4] line3");
});
test("single file, multiple hunks with +1 between", () => {
const diff = `diff --git a/file.js b/file.js
index abc123..def456 100644
--- a/file.js
+++ b/file.js
@@ -1,3 +1,3 @@
line1
-old line
+new line
line3
@@ -10,3 +10,3 @@
line10
-old line 11
+new line 11
line12`;
const result = annotateDiff(diff);
// First hunk
expect(result).toContain("[POS:1] line1");
expect(result).toContain("[POS:2] -old line");
expect(result).toContain("[POS:3] +new line");
expect(result).toContain("[POS:4] line3");
// Second hunk (should start at 6, because 4 lines + 1 for between hunks)
expect(result).toContain("[POS:6] line10");
expect(result).toContain("[POS:7] -old line 11");
expect(result).toContain("[POS:8] +new line 11");
expect(result).toContain("[POS:9] line12");
});
test("multiple files reset position counter", () => {
const diff = `diff --git a/file1.js b/file1.js
index abc123..def456 100644
--- a/file1.js
+++ b/file1.js
@@ -1,2 +1,2 @@
line1
-old
+new
diff --git a/file2.js b/file2.js
index abc123..def456 100644
--- a/file2.js
+++ b/file2.js
@@ -1,2 +1,2 @@
first
-old2
+new2`;
const result = annotateDiff(diff);
// File 1
expect(result).toContain("[POS:1] line1");
expect(result).toContain("[POS:2] -old");
expect(result).toContain("[POS:3] +new");
// File 2 - positions should reset
const file2Section = result.split("diff --git a/file2.js")[1];
expect(file2Section).toContain("[POS:1] first");
expect(file2Section).toContain("[POS:2] -old2");
expect(file2Section).toContain("[POS:3] +new2");
});
test("handles new file", () => {
const diff = `diff --git a/newfile.js b/newfile.js
new file mode 100644
index 0000000..abc123
--- /dev/null
+++ b/newfile.js
@@ -0,0 +1,3 @@
+line1
+line2
+line3`;
const result = annotateDiff(diff);
expect(result).toContain("new file mode 100644");
expect(result).toContain("[POS:1] +line1");
expect(result).toContain("[POS:2] +line2");
expect(result).toContain("[POS:3] +line3");
});
test("handles deleted file", () => {
const diff = `diff --git a/deleted.js b/deleted.js
deleted file mode 100644
index abc123..0000000
--- a/deleted.js
+++ /dev/null
@@ -1,3 +0,0 @@
-line1
-line2
-line3`;
const result = annotateDiff(diff);
expect(result).toContain("deleted file mode 100644");
expect(result).toContain("[POS:1] -line1");
expect(result).toContain("[POS:2] -line2");
expect(result).toContain("[POS:3] -line3");
});
test("handles renamed file with changes", () => {
const diff = `diff --git a/old-name.js b/new-name.js
similarity index 95%
rename from old-name.js
rename to new-name.js
index abc123..def456 100644
--- a/old-name.js
+++ b/new-name.js
@@ -1,3 +1,3 @@
line1
-old line
+new line
line3`;
const result = annotateDiff(diff);
expect(result).toContain("rename from old-name.js");
expect(result).toContain("rename to new-name.js");
expect(result).toContain("[POS:1] line1");
expect(result).toContain("[POS:2] -old line");
expect(result).toContain("[POS:3] +new line");
});
test("handles no newline at end of file", () => {
const diff = `diff --git a/file.js b/file.js
index abc123..def456 100644
--- a/file.js
+++ b/file.js
@@ -1,2 +1,2 @@
line1
-old line
\\ No newline at end of file
+new line
\\ No newline at end of file`;
const result = annotateDiff(diff);
expect(result).toContain("[POS:1] line1");
expect(result).toContain("[POS:2] -old line");
// Position 3 is the first "No newline" marker (not annotated but counted)
expect(result).toContain("\\ No newline at end of file");
expect(result).toContain("[POS:4] +new line"); // Position 4 due to "No newline" at position 3
// Position 5 is the second "No newline" marker (not annotated but counted)
expect(result).toContain("\\ No newline at end of file");
// No newline markers should not get [POS:N] annotations
expect(result).not.toContain("[POS:3] \\");
expect(result).not.toContain("[POS:5] \\");
});
test("handles file mode changes", () => {
const diff = `diff --git a/script.sh b/script.sh
old mode 100644
new mode 100755
index abc123..def456 100644
--- a/script.sh
+++ b/script.sh
@@ -1,2 +1,2 @@
#!/bin/bash
-echo "old"
+echo "new"`;
const result = annotateDiff(diff);
expect(result).toContain("old mode 100644");
expect(result).toContain("new mode 100755");
expect(result).toContain("[POS:1] #!/bin/bash");
expect(result).toContain('[POS:2] -echo "old"');
expect(result).toContain('[POS:3] +echo "new"');
});
test("empty diff returns empty", () => {
const diff = "";
const result = annotateDiff(diff);
expect(result).toBe("");
});
test("handles binary files - modified", () => {
const diff = `diff --git a/image.png b/image.png
index abc123..def456 100644
Binary files a/image.png and b/image.png differ`;
const result = annotateDiff(diff);
expect(result).toContain("diff --git a/image.png b/image.png");
expect(result).toContain("Binary files a/image.png and b/image.png differ");
// Binary files line should not be annotated
expect(result).not.toContain("[POS:");
});
test("handles binary files - added", () => {
const diff = `diff --git a/newimage.png b/newimage.png
new file mode 100644
index 0000000..abc123
Binary files /dev/null and b/newimage.png differ`;
const result = annotateDiff(diff);
expect(result).toContain("diff --git a/newimage.png b/newimage.png");
expect(result).toContain("new file mode 100644");
expect(result).toContain(
"Binary files /dev/null and b/newimage.png differ",
);
// Binary files line should not be annotated
expect(result).not.toContain("[POS:");
});
test("handles binary files - deleted", () => {
const diff = `diff --git a/oldimage.png b/oldimage.png
deleted file mode 100644
index abc123..0000000
Binary files a/oldimage.png and /dev/null differ`;
const result = annotateDiff(diff);
expect(result).toContain("diff --git a/oldimage.png b/oldimage.png");
expect(result).toContain("deleted file mode 100644");
expect(result).toContain(
"Binary files a/oldimage.png and /dev/null differ",
);
// Binary files line should not be annotated
expect(result).not.toContain("[POS:");
});
test("handles mixed text and binary files", () => {
const diff = `diff --git a/text.js b/text.js
index abc123..def456 100644
--- a/text.js
+++ b/text.js
@@ -1,2 +1,2 @@
line1
-old
+new
diff --git a/image.png b/image.png
index 111111..222222 100644
Binary files a/image.png and b/image.png differ
diff --git a/another.js b/another.js
index 333333..444444 100644
--- a/another.js
+++ b/another.js
@@ -1,1 +1,1 @@
-foo
+bar`;
const result = annotateDiff(diff);
// First file (text)
expect(result).toContain("[POS:1] line1");
expect(result).toContain("[POS:2] -old");
expect(result).toContain("[POS:3] +new");
// Second file (binary) - no positions
expect(result).toContain("Binary files a/image.png and b/image.png differ");
// Third file (text) - positions reset
const lastFileSection = result.split("diff --git a/another.js")[1];
expect(lastFileSection).toContain("[POS:1] -foo");
expect(lastFileSection).toContain("[POS:2] +bar");
});
test("multiple no newline markers accumulate positions", () => {
const diff = `diff --git a/file.js b/file.js
index abc123..def456 100644
--- a/file.js
+++ b/file.js
@@ -1,3 +1,3 @@
line1
-old1
\\ No newline at end of file
+new1
\\ No newline at end of file
@@ -10,3 +10,3 @@
line10
-old2
\\ No newline at end of file
+new2
\\ No newline at end of file`;
const result = annotateDiff(diff);
// First hunk
expect(result).toContain("[POS:1] line1");
expect(result).toContain("[POS:2] -old1");
// Position 3 is the first "No newline" marker
expect(result).toContain("[POS:4] +new1");
// Position 5 is the second "No newline" marker
// Second hunk (starts at position 7 = 5 + 1 for between hunks + 1)
expect(result).toContain("[POS:7] line10");
expect(result).toContain("[POS:8] -old2");
// Position 9 is the third "No newline" marker
expect(result).toContain("[POS:10] +new2");
// Position 11 is the fourth "No newline" marker
// Verify "No newline" markers are not annotated
expect(result).not.toContain("[POS:3] \\");
expect(result).not.toContain("[POS:5] \\");
expect(result).not.toContain("[POS:9] \\");
expect(result).not.toContain("[POS:11] \\");
});
test("complex multi-file, multi-hunk diff", () => {
const diff = `diff --git a/src/app.js b/src/app.js
index abc123..def456 100644
--- a/src/app.js
+++ b/src/app.js
@@ -10,4 +10,5 @@ function example() {
console.log("start");
const x = 1;
- const y = 2;
+ const y = 3;
+ const z = 4;
return x + y;
@@ -20,3 +21,4 @@ function another() {
let a = 1;
let b = 2;
+ let c = 3;
return a + b;
diff --git a/src/util.js b/src/util.js
index 111111..222222 100644
--- a/src/util.js
+++ b/src/util.js
@@ -1,2 +1,3 @@
+import fs from 'fs';
export function util() {
return true;`;
const result = annotateDiff(diff);
// src/app.js - first hunk
expect(result).toContain('[POS:1] console.log("start");');
expect(result).toContain("[POS:2] const x = 1;");
expect(result).toContain("[POS:3] - const y = 2;");
expect(result).toContain("[POS:4] + const y = 3;");
expect(result).toContain("[POS:5] + const z = 4;");
expect(result).toContain("[POS:6] return x + y;");
// src/app.js - second hunk (7 = 6 + 1 for between hunks)
expect(result).toContain("[POS:8] let a = 1;");
expect(result).toContain("[POS:9] let b = 2;");
expect(result).toContain("[POS:10] + let c = 3;");
expect(result).toContain("[POS:11] return a + b;");
// src/util.js - new file, positions reset
const utilSection = result.split("diff --git a/src/util.js")[1];
expect(utilSection).toContain("[POS:1] +import fs from 'fs';");
expect(utilSection).toContain("[POS:2] export function util() {");
expect(utilSection).toContain("[POS:3] return true;");
});
});

View file

@ -0,0 +1,19 @@
{
"name": "@continue/pr-review-scripts",
"version": "1.0.0",
"private": true,
"description": "Scripts for Continue PR Review Action",
"scripts": {
"test": "jest",
"test:watch": "jest --watch"
},
"devDependencies": {
"jest": "^29.7.0"
},
"jest": {
"testEnvironment": "node",
"testMatch": [
"**/*.test.js"
]
}
}

View file

@ -0,0 +1,233 @@
name: 'Continue PR Review'
description: 'Automated code review for pull requests using Continue CLI'
author: 'Continue Dev, Inc.'
inputs:
continue-api-key:
description: 'API key for Continue service'
required: true
continue-org:
description: 'Organization for Continue config'
required: true
continue-config:
description: 'Config path to use (e.g., "myorg/review-bot")'
required: true
runs:
using: 'composite'
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Check Authorization
shell: bash
env:
# Only move the dangerous check to env to prevent shell injection
HAS_TRIGGER_PHRASE: ${{ contains(github.event.comment.body, '@continue-general-review') }}
run: |
# Check if this action should run based on event type and user permissions
SHOULD_RUN="false"
if [ "${{ github.event_name }}" = "pull_request" ]; then
# Check if PR is a draft
if [ "${{ github.event.pull_request.draft }}" = "true" ]; then
echo "::notice::Skipping review - PR is a draft"
else
# Check PR author association
AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}"
if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then
SHOULD_RUN="true"
else
echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)"
fi
fi
elif [ "${{ github.event_name }}" = "issue_comment" ]; then
# Check if it's a PR comment with the trigger phrase
if [ "${{ github.event.issue.pull_request }}" != "" ] && [ "$HAS_TRIGGER_PHRASE" = "true" ]; then
COMMENTER_ASSOC="${{ github.event.comment.author_association }}"
if [ "$COMMENTER_ASSOC" = "OWNER" ] || [ "$COMMENTER_ASSOC" = "MEMBER" ] || [ "$COMMENTER_ASSOC" = "COLLABORATOR" ]; then
SHOULD_RUN="true"
else
echo "::notice::Skipping review - Commenter is not a team member (association: $COMMENTER_ASSOC)"
fi
else
echo "::notice::Skipping review - Comment does not contain @continue-general-review trigger, or is not on a PR"
fi
else
echo "::notice::Skipping review - Unsupported event type: ${{ github.event_name }}"
fi
echo "SHOULD_RUN=$SHOULD_RUN" >> $GITHUB_ENV
- name: Setup Node.js
if: env.SHOULD_RUN == 'true'
uses: actions/setup-node@v4
with:
node-version: 20
- name: Install Continue CLI
if: env.SHOULD_RUN == 'true'
shell: bash
run: npm install -g @continuedev/cli@1.4.25
- name: Build PR Review Prompt
if: env.SHOULD_RUN == 'true'
shell: bash
env:
GH_TOKEN: ${{ github.token }}
run: |
# Get PR number based on event type
if [ "${{ github.event_name }}" = "pull_request" ]; then
PR_NUMBER="${{ github.event.number }}"
else
# For issue_comment event on a PR
PR_NUMBER="${{ github.event.issue.number }}"
fi
# Get PR diff
gh pr diff $PR_NUMBER > pr_diff.txt
# Create review prompt
cat > review_prompt.txt << 'EOF'
You are conducting a code review for a pull request. Below is the git diff showing all the changes:
EOF
echo "--- PR DIFF START ---" >> review_prompt.txt
cat pr_diff.txt >> review_prompt.txt
echo "--- PR DIFF END ---" >> review_prompt.txt
cat >> review_prompt.txt << 'EOF'
Please analyze these changes and provide a comprehensive code review. Consider:
1. **Code Quality**: Are there any bugs, performance issues, or code smells?
2. **Best Practices**: Does the code follow established patterns and conventions?
3. **Security**: Are there any potential security vulnerabilities?
4. **Testing**: Are appropriate tests included or updated?
5. **Documentation**: Is documentation adequate for the changes?
6. **Architecture**: Do the changes fit well with the existing codebase structure?
You can use the available tools to explore the codebase and understand context better.
Format your response as a markdown code review with the following structure:
## Code Review Summary
### ✅ Strengths
- **[Aspect]**: [Description of what was done well]
### ⚠️ Issues Found
Only include the severity subheaders below if you actually found issues at that level:
#### Critical
- **[Issue Title]**: [Description of critical issues that must be fixed before merging]
#### High
- **[Issue Title]**: [Description of high-priority issues that should be fixed]
#### Medium
- **[Issue Title]**: [Description of issues that should be addressed]
#### Low
- **[Issue Title]**: [Description of minor issues or nice-to-have improvements]
### 💡 Suggestions
- **[Suggestion Title]**: [Description of improvement recommendations]
### 🚀 Overall Assessment
[Provide overall recommendation: APPROVE, REQUEST_CHANGES, or COMMENT]
Only call the 'exit' tool if you find critical security vulnerabilities or bugs that would break production.
EOF
- name: Run Continue CLI Review
if: env.SHOULD_RUN == 'true'
shell: bash
env:
CONTINUE_API_KEY: ${{ inputs.continue-api-key }}
CONTINUE_ORG: ${{ inputs.continue-org }}
CONTINUE_CONFIG: ${{ inputs.continue-config }}
run: |
echo "Running Continue CLI with prompt:"
echo "=================================="
cat review_prompt.txt
echo "=================================="
echo ""
# Validate inputs to prevent command injection
if [[ ! "$CONTINUE_ORG" =~ ^[a-zA-Z0-9_-]+$ ]]; then
echo "Error: Invalid organization name. Must contain only alphanumeric characters, hyphens, and underscores."
exit 1
fi
if [[ ! "$CONTINUE_CONFIG" =~ ^[a-zA-Z0-9_/-]+$ ]]; then
echo "Error: Invalid config path. Must contain only alphanumeric characters, hyphens, underscores, and forward slashes."
exit 1
fi
# Run the CLI with validated config
cn --readonly --org "$CONTINUE_ORG" --config "$CONTINUE_CONFIG" -p "$(cat review_prompt.txt)" > code_review.md
- name: Upload Review Results
if: env.SHOULD_RUN == 'true' && always()
uses: actions/upload-artifact@v4
with:
name: code-review-results
path: |
code_review.md
review_prompt.txt
pr_diff.txt
retention-days: 30
- name: Comment PR with Review
if: env.SHOULD_RUN == 'true' && always()
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
try {
let reviewContent = '';
if (fs.existsSync('code_review.md') && fs.statSync('code_review.md').size > 0) {
reviewContent = fs.readFileSync('code_review.md', 'utf8');
} else {
reviewContent = '⚠️ AI review completed but no review output was generated. Check the action logs for details.';
}
// Get PR number based on event type
let prNumber;
if (context.eventName === 'pull_request') {
prNumber = context.payload.pull_request.number;
} else {
// For issue_comment event
prNumber = context.payload.issue.number;
}
// Add a header if triggered by comment
if (context.eventName === 'issue_comment') {
reviewContent = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${reviewContent}`;
}
// Add instructions for re-review
reviewContent += '\n\n---\n*💡 To request a new review, comment `@continue-general-review`*';
// Create new comment
await github.rest.issues.createComment({
issue_number: prNumber,
owner: context.repo.owner,
repo: context.repo.repo,
body: reviewContent
});
console.log(`Successfully created new comment on PR #${prNumber}`);
} catch (error) {
console.log('Failed to post comment:', error.message);
console.log('Error details:', error);
}
branding:
icon: 'code'
color: 'blue'

189
binary/package-lock.json generated
View file

@ -40,7 +40,7 @@
"pkg": "^5.8.1",
"rimraf": "^5.0.7",
"ts-jest": "^29.1.4",
"typescript": "^5.3.3"
"typescript": "^5.6.3"
}
},
"../core": {
@ -59,7 +59,11 @@
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@sentry/cli": "^2.50.2",
"@sentry/core": "^9.43.0",
"@sentry/esbuild-plugin": "^4.0.2",
"@sentry/node": "^9.43.0",
"@sentry/vite-plugin": "^4.0.2",
"@xenova/transformers": "2.14.0",
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
@ -78,7 +82,7 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"iconv-lite": "^0.6.3",
"ignore": "^5.3.1",
"ignore": "^7.0.5",
"is-localhost-ip": "^2.0.0",
"jinja-js": "0.1.8",
"js-tiktoken": "^1.0.8",
@ -91,7 +95,7 @@
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",
"onnxruntime-node": "1.14.0",
"openai": "^4.104.0",
"openai": "^5.13.1",
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",
@ -139,6 +143,8 @@
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
"@typescript-eslint/eslint-plugin": "^8.40.0",
"@typescript-eslint/parser": "^8.40.0",
"cross-env": "^7.0.3",
"esbuild": "0.17.19",
"eslint": "^8",
@ -2890,6 +2896,19 @@
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"dev": true
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/callsites": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
@ -3363,6 +3382,20 @@
"node": ">=8"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/eastasianwidth": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
@ -3411,6 +3444,51 @@
"is-arrayish": "^0.2.1"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-object-atoms": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-set-tostringtag": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.6",
"has-tostringtag": "^1.0.2",
"hasown": "^2.0.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/esbuild": {
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.11.tgz",
@ -3690,12 +3768,15 @@
}
},
"node_modules/form-data": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
"integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
"hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {
@ -3768,7 +3849,6 @@
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"dev": true,
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
@ -3791,6 +3871,30 @@
"node": "6.* || 8.* || >= 10.*"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-package-type": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz",
@ -3800,6 +3904,19 @@
"node": ">=8.0.0"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"license": "MIT",
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/get-stream": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz",
@ -3881,6 +3998,18 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
@ -3904,11 +4033,37 @@
"node": ">=8"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-tostringtag": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
"license": "MIT",
"dependencies": {
"has-symbols": "^1.0.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
"dev": true,
"dependencies": {
"function-bind": "^1.1.2"
},
@ -5179,6 +5334,15 @@
"tmpl": "1.0.5"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/merge-stream": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
@ -6758,10 +6922,11 @@
}
},
"node_modules/typescript": {
"version": "5.4.5",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz",
"integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==",
"version": "5.9.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz",
"integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"

View file

@ -39,7 +39,7 @@
"pkg": "^5.8.1",
"rimraf": "^5.0.7",
"ts-jest": "^29.1.4",
"typescript": "^5.3.3"
"typescript": "^5.6.3"
},
"dependencies": {
"@octokit/rest": "^20.0.2",

4
core/.gitignore vendored
View file

@ -4,4 +4,6 @@ target
npm-debug.log*
.env
test/.continue-test
coverage
coverage
# Sentry Config File
.sentryclirc

View file

@ -6,12 +6,13 @@ import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js";
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
import { isSecurityConcern } from "../indexing/ignore.js";
import { BracketMatchingService } from "./filtering/BracketMatchingService.js";
import { CompletionStreamer } from "./generation/CompletionStreamer.js";
import { postprocessCompletion } from "./postprocessing/index.js";
import { shouldPrefilter } from "./prefiltering/index.js";
import { renderPromptWithTokenLimit } from "./templating/index.js";
import { getAllSnippetsWithoutRace } from "./snippets/index.js";
import { renderPromptWithTokenLimit } from "./templating/index.js";
import { GetLspDefinitionsFunction } from "./types.js";
import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js";
import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js";
@ -150,6 +151,10 @@ export class CompletionProvider {
return undefined;
}
if (isSecurityConcern(input.filepath)) {
return undefined;
}
const options = await this._getAutocompleteOptions(llm);
// Debounce
@ -210,12 +215,6 @@ export class CompletionProvider {
const multiline =
!helper.options.transform || shouldCompleteMultiline(helper);
const rawGeneration = await llm.complete(
prompt,
token,
completionOptions,
);
const completionStream =
this.completionStreamer.streamCompletionWithFilters(
token,

View file

@ -4,7 +4,7 @@ import { IDE } from "../..";
import {
getGlobalContinueIgArray,
getWorkspaceContinueIgArray,
} from "../../indexing/ignore";
} from "../../indexing/continueignore";
import { getConfigJsonPath } from "../../util/paths";
import { findUriInDirs } from "../../util/uri";
import { HelperVars } from "../util/HelperVars";

View file

@ -20,7 +20,7 @@ import {
Highlighter,
} from "shiki";
import { DiffLine } from "..";
import { escapeForSVG, kebabOfStr } from "../util/text";
import { escapeForSVG, kebabOfThemeStr } from "../util/text";
interface CodeRendererOptions {
themesDir?: string;
@ -70,28 +70,29 @@ export class CodeRenderer {
public async setTheme(themeName: string): Promise<void> {
if (
this.themeExists(kebabOfStr(themeName)) ||
this.themeExists(kebabOfThemeStr(themeName)) ||
themeName === "Default Dark Modern"
) {
this.currentTheme =
themeName === "Default Dark Modern"
? "dark-plus"
: kebabOfStr(themeName);
this.highlighter = await getSingletonHighlighter({
langs: ["typescript"],
themes: [this.currentTheme],
});
const th = this.highlighter.getTheme(this.currentTheme);
this.editorBackground = th.bg;
this.editorForeground = th.fg;
this.editorLineHighlight =
th.colors!["editor.lineHighlightBackground"] ?? "#000000";
: kebabOfThemeStr(themeName);
} else {
// Fallback to default theme for unsupported themes.
this.currentTheme = "dark-plus";
}
// Always initialize the highlighter with the current theme.
this.highlighter = await getSingletonHighlighter({
langs: ["typescript"],
themes: [this.currentTheme],
});
const th = this.highlighter.getTheme(this.currentTheme);
this.editorBackground = th.bg;
this.editorForeground = th.fg;
this.editorLineHighlight =
th.colors!["editor.lineHighlightBackground"] ?? "#000000";
}
async init(): Promise<void> {}
@ -243,7 +244,10 @@ export class CodeRenderer {
);
const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${options.dimensions.width}" height="${options.dimensions.height}" shape-rendering="crispEdges">
const lines = code.split("\n");
const actualHeight = lines.length * options.lineHeight;
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${options.dimensions.width}" height="${actualHeight}" shape-rendering="crispEdges">
<style>
:root {
--purple: rgb(112, 114, 209);
@ -252,7 +256,7 @@ export class CodeRenderer {
}
</style>
<g>
<rect x="0" y="0" rx="10" ry="10" width="${options.dimensions.width}" height="${options.dimensions.height}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
<rect x="0" y="0" rx="10" ry="10" width="${options.dimensions.width}" height="${actualHeight}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
${lineBackgrounds}
${guts}
</g>
@ -317,29 +321,46 @@ export class CodeRenderer {
const y = index * options.lineHeight;
const isFirst = index === 0;
const isLast = index === lines.length - 1;
const isSingleLine = isFirst && isLast;
const radius = 10;
// Handle single line case (both first and last)
if (isSingleLine) {
return `<path d="M ${radius} ${y}
L ${options.dimensions.width - radius} ${y}
Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
L ${options.dimensions.width} ${y + options.lineHeight - radius}
Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width - radius} ${y + options.lineHeight}
L ${radius} ${y + options.lineHeight}
Q ${0} ${y + options.lineHeight} ${0} ${y + options.lineHeight - radius}
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
Z"
fill="${bgColor}" />`;
}
// SVG notes:
// By default SVGs have anti-aliasing on.
// This is undesirable in our case because pixel-perfect alignment of these rectangles will introduce thin gaps.
// Turning it off with 'shape-rendering="crispEdges"' solves the issue.
return isFirst
? `<path d="M ${0} ${y + options.lineHeight}
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
L ${options.dimensions.width - radius} ${y}
Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
L ${options.dimensions.width} ${y + options.lineHeight}
Z"
fill="${bgColor}" />`
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
L ${options.dimensions.width - radius} ${y}
Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
L ${options.dimensions.width} ${y + options.lineHeight}
Z"
fill="${bgColor}" />`
: isLast
? `<path d="M ${0} ${y}
L ${0} ${y + options.lineHeight - radius}
Q ${0} ${y + options.lineHeight} ${radius} ${y + options.lineHeight}
L ${options.dimensions.width - radius} ${y + options.lineHeight}
Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width} ${y + options.lineHeight - 10}
L ${options.dimensions.width} ${y}
Z"
fill="${bgColor}" />`
L ${0} ${y + options.lineHeight - radius}
Q ${0} ${y + options.lineHeight} ${radius} ${y + options.lineHeight}
L ${options.dimensions.width - radius} ${y + options.lineHeight}
Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width} ${y + options.lineHeight - 10}
L ${options.dimensions.width} ${y}
Z"
fill="${bgColor}" />`
: `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
})
.join("\n");

View file

@ -1,11 +1,8 @@
import ignore from "ignore";
import type { FileType, IDE, SlashCommand } from "../../..";
import {
DEFAULT_IGNORE,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "../../../indexing/ignore";
import { getGlobalContinueIgArray } from "../../../indexing/continueignore";
import { DEFAULT_IGNORE, gitIgArrayFromFile } from "../../../indexing/ignore";
import { renderChatMessage } from "../../../util/messageContent";
import {
findUriInDirs,

View file

@ -17,10 +17,10 @@ import {
ControlPlaneSessionInfo,
} from "../control-plane/AuthTypes.js";
import { getControlPlaneEnv } from "../control-plane/env.js";
import { logger } from "../util/logger.js";
import { PolicySingleton } from "../control-plane/PolicySingleton.js";
import { Logger } from "../util/Logger.js";
import { Telemetry } from "../util/posthog.js";
import {
ASSISTANTS,
getAllDotContinueDefinitionFiles,
LoadAssistantFilesOptions,
} from "./loadLocalAssistants.js";
@ -45,7 +45,7 @@ export class ConfigHandler {
private organizations: OrgWithProfiles[] = [];
currentProfile: ProfileLifecycleManager | null;
currentOrg: OrgWithProfiles;
currentOrg: OrgWithProfiles | null;
totalConfigReloads: number = 0;
public isInitialized: Promise<void>;
@ -83,16 +83,9 @@ export class ConfigHandler {
this.ide,
);
// Just to be safe, always force a default personal org with local profile manager
this.currentProfile = this.globalLocalProfileManager;
const personalOrg: OrgWithProfiles = {
currentProfile: this.globalLocalProfileManager,
profiles: [this.globalLocalProfileManager],
...this.PERSONAL_ORG_DESC,
};
this.currentOrg = personalOrg;
this.organizations = [personalOrg];
this.currentOrg = null;
this.currentProfile = null;
this.organizations = [];
this.initter = new EventEmitter();
this.isInitialized = new Promise((resolve) => {
@ -132,10 +125,10 @@ export class ConfigHandler {
const firstNonPersonal = orgs.find(
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
);
const fallback = firstNonPersonal ?? orgs[0];
// note, ignoring case of zero orgs since should never happen
const fallback: OrgWithProfiles | null =
firstNonPersonal ?? orgs[0] ?? null;
let selectedOrg: OrgWithProfiles;
let selectedOrg: OrgWithProfiles | null;
if (currentSelection) {
const match = orgs.find((org) => org.id === currentSelection);
if (match) {
@ -153,12 +146,12 @@ export class ConfigHandler {
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
...selectedOrgs,
[workspaceId]: selectedOrg.id,
[workspaceId]: selectedOrg?.id,
});
this.organizations = orgs;
this.currentOrg = selectedOrg;
this.currentProfile = selectedOrg.currentProfile;
this.currentProfile = selectedOrg?.currentProfile;
await this.reloadConfig(reason, errors);
} catch (e) {
@ -179,10 +172,27 @@ export class ConfigHandler {
const isSignedIn = await this.controlPlaneClient.isSignedIn();
if (isSignedIn) {
try {
const orgDescs = await this.controlPlaneClient.listOrganizations();
// TODO use policy returned with org, not policy endpoint
const policyResponse = await this.controlPlaneClient.getPolicy();
PolicySingleton.getInstance().policy = policyResponse;
const orgDescriptions =
await this.controlPlaneClient.listOrganizations();
const orgsWithPolicy = orgDescriptions.map((d) => ({
...d,
policy: policyResponse?.policy,
}));
if (policyResponse?.policy?.allowOtherOrgs === false) {
if (orgsWithPolicy.length === 0) {
return { orgs: [] };
} else {
const firstOrg = await this.getNonPersonalHubOrg(orgsWithPolicy[0]);
return { orgs: [firstOrg] };
}
}
const orgs = await Promise.all([
this.getPersonalHubOrg(),
...orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
...orgsWithPolicy.map((org) => this.getNonPersonalHubOrg(org)),
]);
// TODO make try/catch more granular here, to catch specific org errors
return { orgs };
@ -328,7 +338,7 @@ export class ConfigHandler {
async getLocalProfiles(options: LoadAssistantFilesOptions) {
/**
* Users can define as many local assistants as they want in a `.continue/assistants` folder
* Users can define as many local agents as they want in a `.continue/agents` (or previous .continue/assistants) folder
*/
// Local customization disabled for on-premise deployments
@ -347,9 +357,14 @@ export class ConfigHandler {
const assistantFiles = await getAllDotContinueDefinitionFiles(
this.ide,
options,
ASSISTANTS,
"assistants",
);
const profiles = assistantFiles.map((assistant) => {
const agentFiles = await getAllDotContinueDefinitionFiles(
this.ide,
options,
"agents",
);
const profiles = [...assistantFiles, ...agentFiles].map((assistant) => {
return new LocalProfileLoader(
this.ide,
this.ideSettingsPromise,
@ -426,7 +441,7 @@ export class ConfigHandler {
// Org id: check id validity, save selection, switch and reload
async setSelectedOrgId(orgId: string, profileId?: string) {
if (orgId === this.currentOrg.id) {
if (orgId === this.currentOrg?.id) {
return;
}
const org = this.organizations.find((org) => org.id === orgId);
@ -454,6 +469,9 @@ export class ConfigHandler {
// Profile id: check id validity, save selection, switch and reload
async setSelectedProfileId(profileId: string) {
if (!this.currentOrg) {
throw new Error(`No org selected`);
}
if (
this.currentProfile &&
profileId === this.currentProfile.profileDescription.id
@ -490,10 +508,7 @@ export class ConfigHandler {
if (!this.currentProfile) {
return {
config: undefined,
errors: [
{ message: "Current profile not found", fatal: true },
...(injectErrors ?? []),
],
errors: injectErrors,
configLoadInterrupted: true,
};
}
@ -562,7 +577,7 @@ export class ConfigHandler {
if (!this.currentProfile) {
return {
config: undefined,
errors: [{ message: "Current profile not found", fatal: true }],
errors: undefined,
configLoadInterrupted: true,
};
}
@ -575,7 +590,7 @@ export class ConfigHandler {
if (!this.currentProfile) {
return {
config: undefined,
errors: [{ message: "Current profile not found", fatal: true }],
errors: undefined,
configLoadInterrupted: true,
};
}
@ -585,7 +600,7 @@ export class ConfigHandler {
);
if (config.errors?.length) {
logger.warn("Errors loading config: ", config.errors);
Logger.error("Errors loading config: ", config.errors);
}
return config;
}
@ -598,11 +613,15 @@ export class ConfigHandler {
if (!openProfileId) {
return;
}
const profile = this.currentOrg.profiles.find(
const profile = this.currentOrg?.profiles.find(
(p) => p.profileDescription.id === openProfileId,
);
if (!profile) {
console.error(`Profile ${profileId} not found`);
return;
}
if (profile?.profileDescription.profileType === "local") {
if (profile.profileDescription.profileType === "local") {
const configFile = element?.sourceFile ?? profile.profileDescription.uri;
await this.ide.openFile(configFile);
} else {

View file

@ -10,7 +10,7 @@ import { defaultConfig } from "./default";
describe.skip("Test the ConfigHandler and E2E config loading", () => {
test("should show only local profile", () => {
const profiles = testConfigHandler.currentOrg.profiles;
const profiles = testConfigHandler.currentOrg?.profiles;
expect(profiles?.length).toBe(1);
expect(profiles?.[0].profileDescription.id).toBe("local");

View file

@ -2,6 +2,7 @@ import {
ConfigResult,
ConfigValidationError,
FullSlug,
Policy,
} from "@continuedev/config-yaml";
import {
@ -11,6 +12,7 @@ import {
IDE,
} from "../index.js";
import { Logger } from "../util/Logger.js";
import { finalToBrowserConfig } from "./load.js";
import { IProfileLoader } from "./profile/IProfileLoader.js";
@ -30,6 +32,7 @@ export interface OrganizationDescription {
iconUrl: string;
name: string;
slug: string | undefined; // TODO: This doesn't need to be undefined, just doing while transitioning the backend
policy?: Policy;
}
export type OrgWithProfiles = OrganizationDescription & {
@ -96,6 +99,11 @@ export class ProfileLifecycleManager {
try {
result = await this.profileLoader.doLoadConfig();
} catch (e) {
// Capture config loading system failures to Sentry
Logger.error(e, {
context: "profile_config_loading",
});
const message =
e instanceof Error
? `${e.message}\n${e.stack ? e.stack : ""}`

View file

@ -0,0 +1,62 @@
import { IDE } from "..";
import { joinPathsToUri } from "../util/uri";
const DEFAULT_ASSISTANT_FILE = `# This is an example assistant configuration file
# It is used to define custom AI assistants within Continue
# Each assistant file can be accessed by selecting it from the assistant dropdown
# To learn more, see the full assistant reference: https://docs.continue.dev/reference
name: Example Assistant
version: 1.0.0
schema: v1
# Models define which AI models this assistant can use
models:
- name: my gpt-5
provider: openai
model: gpt-5
apiKey: YOUR_API_KEY_HERE
# Context providers define what information the assistant can access
context:
- provider: code
- provider: docs
- provider: diff
- provider: terminal
- provider: problems
- provider: folder
- provider: codebase
`;
export async function createNewAssistantFile(
ide: IDE,
assistantPath: string | undefined,
): Promise<void> {
const workspaceDirs = await ide.getWorkspaceDirs();
if (workspaceDirs.length === 0) {
throw new Error(
"No workspace directories found. Make sure you've opened a folder in your IDE.",
);
}
const baseDirUri = joinPathsToUri(
workspaceDirs[0],
assistantPath ?? ".continue/assistants",
);
// Find the first available filename
let counter = 0;
let assistantFileUri: string;
do {
const suffix = counter === 0 ? "" : `-${counter}`;
assistantFileUri = joinPathsToUri(
baseDirUri,
`new-assistant${suffix}.yaml`,
);
counter++;
} while (await ide.fileExists(assistantFileUri));
await ide.writeFile(assistantFileUri, DEFAULT_ASSISTANT_FILE);
await ide.openFile(assistantFileUri);
}

View file

@ -1,37 +1,8 @@
import { ConfigYaml } from "@continuedev/config-yaml";
export const defaultContextProvidersVsCode: NonNullable<
ConfigYaml["context"]
>[number][] = [
{ provider: "code" },
{ provider: "docs" },
{ provider: "diff" },
{ provider: "terminal" },
{ provider: "problems" },
{ provider: "folder" },
{ provider: "codebase" },
];
export const defaultContextProvidersJetBrains: NonNullable<
ConfigYaml["context"]
>[number][] = [
{ provider: "diff" },
{ provider: "folder" },
{ provider: "codebase" },
];
export const defaultConfig: ConfigYaml = {
name: "Local Assistant",
name: "Local Agent",
version: "1.0.0",
schema: "v1",
models: [],
context: defaultContextProvidersVsCode,
};
export const defaultConfigJetBrains: ConfigYaml = {
name: "Local Assistant",
version: "1.0.0",
schema: "v1",
models: [],
context: defaultContextProvidersJetBrains,
};

View file

@ -19,7 +19,6 @@ import {
ContinueRcJson,
CustomContextProvider,
EmbeddingsProviderDescription,
IContextProvider,
IDE,
IdeInfo,
IdeSettings,
@ -36,10 +35,6 @@ import { getLegacyBuiltInSlashCommandFromDescription } from "../commands/slash/b
import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand";
import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand";
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import FileContextProvider from "../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../context/providers/index";
import { useHub } from "../control-plane/env";
import { BaseLLM } from "../llm";
import { LLMClasses, llmFromDescription } from "../llm/llms";
@ -62,9 +57,11 @@ import {
} from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import { getToolsForIde } from "../tools";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import { getBaseToolDefinitions } from "../tools";
import { resolveRelativePathInDir } from "../util/ideUtils";
import { getWorkspaceRcConfigs } from "./json/loadRcConfigs";
import { loadConfigContextProviders } from "./loadContextProviders";
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
import {
getModelByRole,
@ -229,7 +226,7 @@ function applyRequestOptionsToModels(
export function isContextProviderWithParams(
contextProvider: CustomContextProvider | ContextProviderWithParams,
): contextProvider is ContextProviderWithParams {
return (contextProvider as ContextProviderWithParams).name !== undefined;
return "name" in contextProvider && !!contextProvider.name;
}
/** Only difference between intermediate and final configs is the `models` array */
@ -285,6 +282,7 @@ async function intermediateToFinalConfig({
...desc,
model: modelName,
title: modelName,
isFromAutoDetect: true,
},
ide.readFile.bind(ide),
getUriFromPath,
@ -322,6 +320,7 @@ async function intermediateToFinalConfig({
...desc.options,
model: modelName,
logger: llmLogger,
isFromAutoDetect: true,
},
}),
);
@ -386,50 +385,25 @@ async function intermediateToFinalConfig({
applyRequestOptionsToModels(tabAutocompleteModels, config);
// These context providers are always included, regardless of what, if anything,
// the user has configured in config.json
// Load context providers
const { providers: contextProviders, errors: contextErrors } =
loadConfigContextProviders(
config.contextProviders
?.filter((cp) => isContextProviderWithParams(cp))
.map((cp) => ({
provider: (cp as ContextProviderWithParams).name,
params: (cp as ContextProviderWithParams).params,
})),
!!config.docs?.length,
ideInfo.ideType,
);
const codebaseContextParams =
(
(config.contextProviders || [])
.filter(isContextProviderWithParams)
.find((cp) => cp.name === "codebase") as
| ContextProviderWithParams
| undefined
)?.params || {};
const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
({ description: { title } }) => title,
);
// Context providers
const contextProviders: IContextProvider[] = DEFAULT_CONTEXT_PROVIDERS;
for (const provider of config.contextProviders || []) {
if (isContextProviderWithParams(provider)) {
const cls = contextProviderClassFromName(provider.name) as any;
if (!cls) {
if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(provider.name)) {
console.warn(`Unknown context provider ${provider.name}`);
}
continue;
}
const instance: IContextProvider = new cls(provider.params);
// Handle continue-proxy
if (instance.description.title === "continue-proxy") {
(instance as ContinueProxyContextProvider).workOsAccessToken =
workOsAccessToken;
}
contextProviders.push(instance);
} else {
contextProviders.push(new CustomContextProviderClass(provider));
for (const cp of config.contextProviders ?? []) {
if (!isContextProviderWithParams(cp)) {
contextProviders.push(new CustomContextProviderClass(cp));
}
}
errors.push(...contextErrors);
// Embeddings Provider
function getEmbeddingsILLM(
@ -526,7 +500,7 @@ async function intermediateToFinalConfig({
const continueConfig: ContinueConfig = {
...config,
contextProviders,
tools: await getToolsForIde(ide),
tools: getBaseToolDefinitions(),
mcpServerStatuses: [],
slashCommands: [],
modelsByRole: {
@ -654,6 +628,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
apiKeyLocation: llm.apiKeyLocation,
envSecretLocations: llm.envSecretLocations,
sourceFile: llm.sourceFile,
isFromAutoDetect: llm.isFromAutoDetect,
};
}

View file

@ -0,0 +1,95 @@
import {
AssistantUnrolledNonNullable,
ConfigValidationError,
} from "@continuedev/config-yaml";
import { IContextProvider, IdeType } from "..";
import { contextProviderClassFromName } from "../context/providers";
import CurrentFileContextProvider from "../context/providers/CurrentFileContextProvider";
import DiffContextProvider from "../context/providers/DiffContextProvider";
import DocsContextProvider from "../context/providers/DocsContextProvider";
import FileContextProvider from "../context/providers/FileContextProvider";
import ProblemsContextProvider from "../context/providers/ProblemsContextProvider";
import RulesContextProvider from "../context/providers/RulesContextProvider";
import TerminalContextProvider from "../context/providers/TerminalContextProvider";
/*
Loads context providers based on configuration
- default providers will always be loaded, using config params if present
- other providers will be loaded if configured
NOTE the MCPContextProvider is added in doLoadConfig if any resources are present
*/
export function loadConfigContextProviders(
configContext: AssistantUnrolledNonNullable["context"],
hasDocs: boolean,
ideType: IdeType,
): {
providers: IContextProvider[];
errors: ConfigValidationError[];
} {
const providers: IContextProvider[] = [];
const errors: ConfigValidationError[] = [];
const defaultProviders: IContextProvider[] = [
new FileContextProvider({}),
new CurrentFileContextProvider({}),
new DiffContextProvider({}),
new TerminalContextProvider({}),
new ProblemsContextProvider({}),
new RulesContextProvider({}),
];
// Add from config
if (configContext) {
for (const config of configContext) {
const cls = contextProviderClassFromName(config.provider) as any;
if (
!cls &&
!defaultProviders.find((p) => p.description.title === config.provider)
) {
errors.push({
fatal: false,
message: `Unknown context provider ${config.provider}`,
});
continue;
}
providers.push(
new cls({
name: config.name,
...config.params,
}),
);
}
}
// Add from defaults if not found in config
for (const defaultProvider of defaultProviders) {
if (
!providers.find(
(p) => p.description.title === defaultProvider.description.title,
)
) {
providers.push(defaultProvider);
}
}
if (hasDocs && !providers?.some((cp) => cp.description.title === "docs")) {
providers.push(new DocsContextProvider({}));
}
// @problems and @terminal are not supported in jetbrains
const filteredProviders = providers.filter((pv) => {
if (ideType === "jetbrains") {
return (
pv.description.title !== TerminalContextProvider.description.title &&
pv.description.title !== ProblemsContextProvider.description.title
);
}
return true;
});
return {
providers: filteredProviders,
errors,
};
}

View file

@ -0,0 +1,590 @@
import { beforeEach, describe, expect, it, MockedFunction, vi } from "vitest";
import { contextProviderClassFromName } from "../context/providers";
import CurrentFileContextProvider from "../context/providers/CurrentFileContextProvider";
import DiffContextProvider from "../context/providers/DiffContextProvider";
import FileContextProvider from "../context/providers/FileContextProvider";
import ProblemsContextProvider from "../context/providers/ProblemsContextProvider";
import RulesContextProvider from "../context/providers/RulesContextProvider";
import TerminalContextProvider from "../context/providers/TerminalContextProvider";
import { loadConfigContextProviders } from "./loadContextProviders";
// Mock the contextProviderClassFromName function
vi.mock("../context/providers", () => ({
contextProviderClassFromName: vi.fn(),
}));
// Mock all provider classes
vi.mock("../context/providers/CurrentFileContextProvider", () => ({
default: vi.fn().mockImplementation((options) => ({
description: { title: "current-file" },
options,
})),
}));
vi.mock("../context/providers/DiffContextProvider", () => ({
default: vi.fn().mockImplementation((options) => ({
description: { title: "diff" },
options,
})),
}));
vi.mock("../context/providers/FileContextProvider", () => ({
default: vi.fn().mockImplementation((options) => ({
description: { title: "file" },
options,
})),
}));
vi.mock("../context/providers/ProblemsContextProvider", () => {
const MockProblemsContextProvider = vi.fn().mockImplementation((options) => ({
description: { title: "problems" },
options,
}));
(MockProblemsContextProvider as any).description = { title: "problems" };
return { default: MockProblemsContextProvider };
});
vi.mock("../context/providers/RulesContextProvider", () => ({
default: vi.fn().mockImplementation((options) => ({
description: { title: "rules" },
options,
})),
}));
vi.mock("../context/providers/TerminalContextProvider", () => {
const MockTerminalContextProvider = vi.fn().mockImplementation((options) => ({
description: { title: "terminal" },
options,
}));
(MockTerminalContextProvider as any).description = { title: "terminal" };
return { default: MockTerminalContextProvider };
});
const mockedContextProviderClassFromName =
contextProviderClassFromName as MockedFunction<
typeof contextProviderClassFromName
>;
beforeEach(() => {
vi.clearAllMocks();
});
describe("loadConfigContextProviders", () => {
describe("with empty or undefined config", () => {
it("should return only default providers when config is undefined", () => {
const result = loadConfigContextProviders(undefined, false, "vscode");
expect(result.errors).toEqual([]);
expect(result.providers).toHaveLength(6);
// Verify all default providers are included
const providerTitles = result.providers.map((p) => p.description.title);
expect(providerTitles).toEqual(
expect.arrayContaining([
"file",
"current-file",
"diff",
"terminal",
"problems",
"rules",
]),
);
});
it("should return only default providers when config is empty array", () => {
const result = loadConfigContextProviders([], false, "vscode");
expect(result.errors).toEqual([]);
expect(result.providers).toHaveLength(6);
const providerTitles = result.providers.map((p) => p.description.title);
expect(providerTitles).toEqual(
expect.arrayContaining([
"file",
"current-file",
"diff",
"terminal",
"problems",
"rules",
]),
);
});
it("should exclude problems and terminal in jetbrains", () => {
const result = loadConfigContextProviders([], false, "jetbrains");
expect(result.errors).toEqual([]);
expect(result.providers).toHaveLength(4);
const providerTitles = result.providers.map((p) => p.description.title);
expect(providerTitles).toEqual(
expect.arrayContaining(["file", "current-file", "diff", "rules"]),
);
});
});
it("should return default + docs when has docs is true", () => {
const result = loadConfigContextProviders([], true, "vscode");
expect(result.errors).toEqual([]);
expect(result.providers).toHaveLength(7);
const providerTitles = result.providers.map((p) => p.description.title);
expect(providerTitles).toEqual(
expect.arrayContaining([
"file",
"current-file",
"diff",
"terminal",
"problems",
"rules",
"docs",
]),
);
});
});
describe("with valid config", () => {
it("should load providers from config with correct parameters", () => {
const mockProvider = vi.fn().mockImplementation((options) => ({
description: { title: "custom-provider" },
options,
})) as any;
mockedContextProviderClassFromName.mockReturnValue(mockProvider);
const config = [
{
provider: "custom-provider",
name: "my-custom-provider",
params: {
apiKey: "test-key",
baseUrl: "https://api.example.com",
},
},
];
const result = loadConfigContextProviders(config, false, "vscode");
expect(result.errors).toEqual([]);
expect(mockedContextProviderClassFromName).toHaveBeenCalledWith(
"custom-provider",
);
expect(mockProvider).toHaveBeenCalledWith({
name: "my-custom-provider",
apiKey: "test-key",
baseUrl: "https://api.example.com",
});
// Should have custom provider + all defaults
expect(result.providers).toHaveLength(7);
const customProvider = result.providers.find(
(p) => p.description.title === "custom-provider",
);
expect(customProvider).toBeDefined();
expect((customProvider as any)?.options).toEqual({
name: "my-custom-provider",
apiKey: "test-key",
baseUrl: "https://api.example.com",
});
});
it("should handle multiple providers in config", () => {
const mockProvider1 = vi.fn().mockImplementation((options) => ({
description: { title: "provider-1" },
options,
})) as any;
const mockProvider2 = vi.fn().mockImplementation((options) => ({
description: { title: "provider-2" },
options,
})) as any;
mockedContextProviderClassFromName
.mockReturnValueOnce(mockProvider1)
.mockReturnValueOnce(mockProvider2);
const config = [
{
provider: "provider-1",
name: "first-provider",
params: { setting1: "value1" },
},
{
provider: "provider-2",
name: "second-provider",
params: { setting2: "value2" },
},
];
const result = loadConfigContextProviders(config, false, "vscode");
expect(result.errors).toEqual([]);
expect(result.providers).toHaveLength(8); // 2 custom + 6 defaults
expect(mockProvider1).toHaveBeenCalledWith({
name: "first-provider",
setting1: "value1",
});
expect(mockProvider2).toHaveBeenCalledWith({
name: "second-provider",
setting2: "value2",
});
});
it("should handle config with empty params", () => {
const mockProvider = vi.fn().mockImplementation((options) => ({
description: { title: "no-params-provider" },
options,
})) as any;
mockedContextProviderClassFromName.mockReturnValue(mockProvider);
const config = [
{
provider: "no-params-provider",
name: "simple-provider",
params: {},
},
];
const result = loadConfigContextProviders(config, false, "vscode");
expect(result.errors).toEqual([]);
expect(mockProvider).toHaveBeenCalledWith({
name: "simple-provider",
});
});
it("should handle config without params property", () => {
const mockProvider = vi.fn().mockImplementation((options) => ({
description: { title: "provider-without-params" },
options,
})) as any;
mockedContextProviderClassFromName.mockReturnValue(mockProvider);
const config = [
{
provider: "provider-without-params",
name: "minimal-provider",
} as any, // Cast to bypass type checking for test
];
const result = loadConfigContextProviders(config, false, "vscode");
expect(result.errors).toEqual([]);
expect(mockProvider).toHaveBeenCalledWith({
name: "minimal-provider",
});
});
});
describe("error handling", () => {
it("should add error for unknown provider", () => {
mockedContextProviderClassFromName.mockReturnValue(undefined);
const config = [
{
provider: "unknown-provider",
name: "test-provider",
params: {},
},
];
const result = loadConfigContextProviders(config, false, "vscode");
expect(result.errors).toEqual([
{
fatal: false,
message: "Unknown context provider unknown-provider",
},
]);
// Should still have default providers
expect(result.providers).toHaveLength(6);
expect(mockedContextProviderClassFromName).toHaveBeenCalledWith(
"unknown-provider",
);
});
it("should handle multiple unknown providers", () => {
mockedContextProviderClassFromName.mockReturnValue(undefined);
const config = [
{
provider: "unknown-1",
name: "test-1",
params: {},
},
{
provider: "unknown-2",
name: "test-2",
params: {},
},
];
const result = loadConfigContextProviders(config, false, "vscode");
expect(result.errors).toEqual([
{
fatal: false,
message: "Unknown context provider unknown-1",
},
{
fatal: false,
message: "Unknown context provider unknown-2",
},
]);
expect(result.providers).toHaveLength(6); // Only defaults
});
it("should handle mix of valid and invalid providers", () => {
const mockValidProvider = vi.fn().mockImplementation((options) => ({
description: { title: "valid-provider" },
options,
})) as any;
mockedContextProviderClassFromName
.mockReturnValueOnce(mockValidProvider)
.mockReturnValueOnce(undefined);
const config = [
{
provider: "valid-provider",
name: "valid",
params: { key: "value" },
},
{
provider: "invalid-provider",
name: "invalid",
params: {},
},
];
const result = loadConfigContextProviders(config, false, "vscode");
expect(result.errors).toEqual([
{
fatal: false,
message: "Unknown context provider invalid-provider",
},
]);
// Should have valid provider + defaults
expect(result.providers).toHaveLength(7);
expect(mockValidProvider).toHaveBeenCalledWith({
name: "valid",
key: "value",
});
});
});
describe("default provider merging", () => {
it("should not duplicate providers when config matches defaults", () => {
// Mock FileContextProvider to be returned by contextProviderClassFromName
mockedContextProviderClassFromName.mockReturnValue(FileContextProvider);
const config = [
{
provider: "file",
name: "custom-file-provider",
params: { maxFiles: 100 },
},
];
const result = loadConfigContextProviders(config, false, "vscode");
expect(result.errors).toEqual([]);
// Should have configured file provider + other defaults (not duplicate file)
expect(result.providers).toHaveLength(6);
const fileProviders = result.providers.filter(
(p) => p.description.title === "file",
);
expect(fileProviders).toHaveLength(1);
// The configured one should be used (with custom params)
expect(FileContextProvider).toHaveBeenCalledWith({
name: "custom-file-provider",
maxFiles: 100,
});
});
it("should add default providers not present in config", () => {
const mockCustomProvider = vi.fn().mockImplementation((options) => ({
description: { title: "custom-only" },
options,
})) as any;
mockedContextProviderClassFromName.mockReturnValue(mockCustomProvider);
const config = [
{
provider: "custom-only",
name: "custom",
params: {},
},
];
const result = loadConfigContextProviders(config, false, "vscode");
expect(result.errors).toEqual([]);
expect(result.providers).toHaveLength(7); // 1 custom + 6 defaults
// All defaults should be present
const providerTitles = result.providers.map((p) => p.description.title);
expect(providerTitles).toEqual(
expect.arrayContaining([
"custom-only",
"file",
"current-file",
"diff",
"terminal",
"problems",
"rules",
]),
);
});
it("should preserve order with configured providers first", () => {
const mockProvider = vi.fn().mockImplementation((options) => ({
description: { title: "custom-provider" },
options,
})) as any;
mockedContextProviderClassFromName.mockReturnValue(mockProvider);
const config = [
{
provider: "custom-provider",
name: "custom",
params: {},
},
];
const result = loadConfigContextProviders(config, false, "vscode");
expect(result.providers[0].description.title).toBe("custom-provider");
// Rest should be defaults in their original order
const defaultTitles = result.providers
.slice(1)
.map((p) => p.description.title);
expect(defaultTitles).toEqual([
"file",
"current-file",
"diff",
"terminal",
"problems",
"rules",
]);
});
});
describe("edge cases", () => {
it("should handle provider constructor throwing error", () => {
const mockProvider = vi.fn().mockImplementation(() => {
throw new Error("Provider construction failed");
}) as any;
mockedContextProviderClassFromName.mockReturnValue(mockProvider);
const config = [
{
provider: "failing-provider",
name: "failing",
params: {},
},
];
expect(() => loadConfigContextProviders(config, false, "vscode")).toThrow(
"Provider construction failed",
);
});
it("should handle null provider class", () => {
mockedContextProviderClassFromName.mockReturnValue(undefined);
const config = [
{
provider: "null-provider",
name: "null",
params: {},
},
];
const result = loadConfigContextProviders(config, false, "vscode");
expect(result.errors).toEqual([
{
fatal: false,
message: "Unknown context provider null-provider",
},
]);
});
it("should handle provider with same title as default but different implementation", () => {
// Mock a provider with same title as a default
const mockFileProvider = vi.fn().mockImplementation((options) => ({
description: { title: "file" }, // Same title as FileContextProvider
options,
customProperty: "custom-implementation",
})) as any;
mockedContextProviderClassFromName.mockReturnValue(mockFileProvider);
const config = [
{
provider: "custom-file",
name: "my-file-provider",
params: { customParam: "value" },
},
];
const result = loadConfigContextProviders(config, false, "vscode");
expect(result.errors).toEqual([]);
// Should not duplicate - custom implementation should be used
const fileProviders = result.providers.filter(
(p) => p.description.title === "file",
);
expect(fileProviders).toHaveLength(1);
const fileProvider = fileProviders[0] as any;
expect(fileProvider.customProperty).toBe("custom-implementation");
expect(fileProvider.options).toEqual({
name: "my-file-provider",
customParam: "value",
});
});
});
describe("provider instantiation", () => {
it("should call default provider constructors with empty options", () => {
loadConfigContextProviders([], false, "vscode");
expect(FileContextProvider).toHaveBeenCalledWith({});
expect(CurrentFileContextProvider).toHaveBeenCalledWith({});
expect(DiffContextProvider).toHaveBeenCalledWith({});
expect(TerminalContextProvider).toHaveBeenCalledWith({});
expect(ProblemsContextProvider).toHaveBeenCalledWith({});
expect(RulesContextProvider).toHaveBeenCalledWith({});
});
it("should call provider constructors exactly once per provider", () => {
loadConfigContextProviders([], false, "vscode");
expect(FileContextProvider).toHaveBeenCalledTimes(1);
expect(CurrentFileContextProvider).toHaveBeenCalledTimes(1);
expect(DiffContextProvider).toHaveBeenCalledTimes(1);
expect(TerminalContextProvider).toHaveBeenCalledTimes(1);
expect(ProblemsContextProvider).toHaveBeenCalledTimes(1);
expect(RulesContextProvider).toHaveBeenCalledTimes(1);
});
});

View file

@ -10,16 +10,16 @@ import { getGlobalFolderWithName } from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import { joinPathsToUri } from "../util/uri";
export const ASSISTANTS = "assistants";
export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`;
export function isLocalDefinitionFile(uri: string): boolean {
if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) {
return false;
}
const normalizedUri = URI.normalize(uri);
return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
return (
normalizedUri.includes(`/.continue/agents/`) ||
normalizedUri.includes(`/.continue/assistants/`)
);
}
async function getDefinitionFilesInDir(
@ -35,7 +35,11 @@ async function getDefinitionFilesInDir(
}
const overrideDefaultIgnores = ignore()
.add(DEFAULT_IGNORE_FILETYPES.filter((t) => t !== "config.yaml"))
.add(
DEFAULT_IGNORE_FILETYPES.filter(
(t) => t !== "config.yaml" && t !== "config.yml",
),
)
.add(DEFAULT_IGNORE_DIRS);
const uris = await walkDir(dir, ide, {

View file

@ -6,7 +6,7 @@ import {
getAllDotContinueDefinitionFiles,
LoadAssistantFilesOptions,
} from "./loadLocalAssistants";
describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
describe("ASSISTANTS getAllDotContinueDefinitionFiles with fileExtType option", () => {
beforeEach(() => {
setUpTestDir();
walkDirCache.invalidate();
@ -18,6 +18,8 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
[".continue/assistants/assistant2.yml", "yaml content 2"],
[".continue/assistants/assistant3.md", "markdown content 1"],
[".continue/assistants/assistant4.txt", "txt content"],
[".continue/assistants/config.yaml", "txt content"],
[".continue/assistants/config.yml", "txt content"],
]);
});
@ -38,9 +40,14 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
options,
"assistants",
);
expect(result).toHaveLength(2);
expect(result).toHaveLength(4);
expect(result.map((f) => f.path.split("/").pop())).toEqual(
expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
expect.arrayContaining([
"assistant1.yaml",
"assistant2.yml",
"config.yaml",
"config.yml",
]),
);
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
"assistant3.md",
@ -69,6 +76,12 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
"assistant2.yml",
);
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
"config.yml",
);
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
"config.yaml",
);
});
it("should return all supported files when fileExtType is not specified", async () => {
@ -83,11 +96,13 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
options,
"assistants",
);
expect(result).toHaveLength(3);
expect(result).toHaveLength(5);
expect(result.map((f) => f.path.split("/").pop())).toEqual(
expect.arrayContaining([
"assistant1.yaml",
"assistant2.yml",
"config.yml",
"config.yaml",
"assistant3.md",
]),
);
@ -124,9 +139,14 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
workspaceOnOptions,
"assistants",
);
expect(workspaceResult).toHaveLength(2);
expect(workspaceResult).toHaveLength(4);
expect(workspaceResult.map((f) => f.path.split("/").pop())).toEqual(
expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
expect.arrayContaining([
"assistant1.yaml",
"assistant2.yml",
"config.yaml",
"config.yml",
]),
);
});
@ -187,7 +207,7 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
options,
"assistants",
);
expect(result).toHaveLength(2);
expect(result).toHaveLength(4);
const yamlFile = result.find((f) => f.path.includes("assistant1.yaml"));
expect(yamlFile?.content).toBe("yaml content 1");
});
@ -212,9 +232,14 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
"assistants",
);
// Should only get lowercase extensions (current implementation)
expect(yamlResult).toHaveLength(2);
expect(yamlResult).toHaveLength(4);
expect(yamlResult.map((f) => f.path.split("/").pop())).toEqual(
expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
expect.arrayContaining([
"assistant1.yaml",
"assistant2.yml",
"config.yaml",
"config.yml",
]),
);
expect(yamlResult.map((f) => f.path.split("/").pop())).not.toContain(
"assistant5.YAML",
@ -240,3 +265,232 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
);
});
});
describe("AGENTS getAllDotContinueDefinitionFiles with fileExtType option", () => {
beforeEach(() => {
setUpTestDir();
walkDirCache.invalidate();
// Add test files to the test directory
addToTestDir([
".continue/agents/",
[".continue/agents/agent1.yaml", "yaml content 1"],
[".continue/agents/agent2.yml", "yaml content 2"],
[".continue/agents/agent3.md", "markdown content 1"],
[".continue/agents/agent4.txt", "txt content"],
]);
});
afterEach(() => {
tearDownTestDir();
walkDirCache.invalidate();
});
it("should return only YAML files when fileExtType is 'yaml'", async () => {
const options: LoadAssistantFilesOptions = {
includeGlobal: false, // Only test workspace for simplicity
includeWorkspace: true,
fileExtType: "yaml",
};
const result = await getAllDotContinueDefinitionFiles(
testIde,
options,
"agents",
);
expect(result).toHaveLength(2);
expect(result.map((f) => f.path.split("/").pop())).toEqual(
expect.arrayContaining(["agent1.yaml", "agent2.yml"]),
);
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
"agent3.md",
);
});
it("should return only Markdown files when fileExtType is 'markdown'", async () => {
const options: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: true,
fileExtType: "markdown",
};
const result = await getAllDotContinueDefinitionFiles(
testIde,
options,
"agents",
);
expect(result).toHaveLength(1);
expect(result.map((f) => f.path.split("/").pop())).toEqual(["agent3.md"]);
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
"agent1.yaml",
);
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
"agent2.yml",
);
});
it("should return all supported files when fileExtType is not specified", async () => {
const options: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: true,
// fileExtType not specified
};
const result = await getAllDotContinueDefinitionFiles(
testIde,
options,
"agents",
);
expect(result).toHaveLength(3);
expect(result.map((f) => f.path.split("/").pop())).toEqual(
expect.arrayContaining(["agent1.yaml", "agent2.yml", "agent3.md"]),
);
// Should not include .txt files
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
"agent4.txt",
);
});
it("should respect includeWorkspace option with fileExtType", async () => {
// Test with includeWorkspace: false
const workspaceOffOptions: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: false,
fileExtType: "yaml",
};
const noWorkspaceResult = await getAllDotContinueDefinitionFiles(
testIde,
workspaceOffOptions,
"agents",
);
expect(noWorkspaceResult).toHaveLength(0);
// Test with includeWorkspace: true
const workspaceOnOptions: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: true,
fileExtType: "yaml",
};
const workspaceResult = await getAllDotContinueDefinitionFiles(
testIde,
workspaceOnOptions,
"agents",
);
expect(workspaceResult).toHaveLength(2);
expect(workspaceResult.map((f) => f.path.split("/").pop())).toEqual(
expect.arrayContaining(["agent1.yaml", "agent2.yml"]),
);
});
it("should return empty array when no files match the specified extension type", async () => {
// Create a test directory with only non-matching files
tearDownTestDir();
walkDirCache.invalidate();
setUpTestDir();
addToTestDir([
".continue/agents/",
[".continue/agents/nonmatch1.txt", "txt content"],
[".continue/agents/nonmatch2.json", "json content"],
]);
const options: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: true,
fileExtType: "yaml",
};
const result = await getAllDotContinueDefinitionFiles(
testIde,
options,
"agents",
);
expect(result).toHaveLength(0);
});
it("should handle directories that don't exist", async () => {
// Create a clean test directory without the agents folder
tearDownTestDir();
setUpTestDir();
const options: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: true,
fileExtType: "yaml",
};
const result = await getAllDotContinueDefinitionFiles(
testIde,
options,
"agents",
);
expect(result).toHaveLength(0);
});
it("should return correct file content", async () => {
const options: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: true,
fileExtType: "yaml",
};
const result = await getAllDotContinueDefinitionFiles(
testIde,
options,
"agents",
);
expect(result).toHaveLength(2);
const yamlFile = result.find((f) => f.path.includes("agent1.yaml"));
expect(yamlFile?.content).toBe("yaml content 1");
});
it("should filter by file extension case sensitively", async () => {
// Add files with uppercase extensions
addToTestDir([
[".continue/agents/agent5.YAML", "uppercase yaml"],
[".continue/agents/agent6.YML", "uppercase yml"],
[".continue/agents/agent7.MD", "uppercase md"],
]);
const yamlOptions: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: true,
fileExtType: "yaml",
};
const yamlResult = await getAllDotContinueDefinitionFiles(
testIde,
yamlOptions,
"agents",
);
// Should only get lowercase extensions (current implementation)
expect(yamlResult).toHaveLength(2);
expect(yamlResult.map((f) => f.path.split("/").pop())).toEqual(
expect.arrayContaining(["agent1.yaml", "agent2.yml"]),
);
expect(yamlResult.map((f) => f.path.split("/").pop())).not.toContain(
"agent5.YAML",
);
const markdownOptions: LoadAssistantFilesOptions = {
includeGlobal: false,
includeWorkspace: true,
fileExtType: "markdown",
};
const markdownResult = await getAllDotContinueDefinitionFiles(
testIde,
markdownOptions,
"agents",
);
expect(markdownResult).toHaveLength(1);
expect(markdownResult.map((f) => f.path.split("/").pop())).toEqual([
"agent3.md",
]);
expect(markdownResult.map((f) => f.path.split("/").pop())).not.toContain(
"agent7.MD",
);
});
});

View file

@ -5,7 +5,7 @@ import {
import { IDE, RuleWithSource } from "../..";
import { walkDirs } from "../../indexing/walkDir";
import { RULES_MARKDOWN_FILENAME } from "../../llm/rules/constants";
import { getUriPathBasename } from "../../util/uri";
import { findUriInDirs, getUriPathBasename } from "../../util/uri";
export class CodebaseRulesCache {
private static instance: CodebaseRulesCache | null = null;
@ -26,7 +26,14 @@ export class CodebaseRulesCache {
}
async update(ide: IDE, uri: string) {
const content = await ide.readFile(uri);
const rule = markdownToRule(content, { uriType: "file", filePath: uri });
const { relativePathOrBasename } = findUriInDirs(
uri,
await ide.getWorkspaceDirs(),
);
const rule = markdownToRule(content, {
uriType: "file",
fileUri: relativePathOrBasename,
});
const ruleWithSource: RuleWithSource = {
...rule,
source: "colocated-markdown",
@ -68,7 +75,14 @@ export async function loadCodebaseRules(ide: IDE): Promise<{
for (const filePath of rulesMdFiles) {
try {
const content = await ide.readFile(filePath);
const rule = markdownToRule(content, { uriType: "file", filePath });
const { relativePathOrBasename } = findUriInDirs(
filePath,
await ide.getWorkspaceDirs(),
);
const rule = markdownToRule(content, {
uriType: "file",
fileUri: relativePathOrBasename,
});
rules.push({
...rule,

View file

@ -2,6 +2,7 @@ import { markdownToRule } from "@continuedev/config-yaml";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { IDE } from "../..";
import { walkDirs } from "../../indexing/walkDir";
import { findUriInDirs, getUriPathBasename } from "../../util/uri";
import { loadCodebaseRules } from "./loadCodebaseRules";
// Mock dependencies
@ -13,12 +14,20 @@ vi.mock("@continuedev/config-yaml", () => ({
markdownToRule: vi.fn(),
}));
vi.mock("../../util/uri", () => ({
findUriInDirs: vi.fn(),
getUriPathBasename: vi.fn(),
}));
describe("loadCodebaseRules", () => {
// Mock IDE with properly typed mock functions
const mockIde = {
readFile: vi.fn() as unknown as IDE["readFile"] & {
mockImplementation: Function;
},
getWorkspaceDirs: vi.fn() as unknown as IDE["getWorkspaceDirs"] & {
mockImplementation: Function;
},
} as unknown as IDE;
// Setup test files
@ -77,6 +86,19 @@ describe("loadCodebaseRules", () => {
// Mock walkDirs to return our test files
(walkDirs as any).mockResolvedValue(mockFiles);
// Mock getWorkspaceDirs to return a workspace directory
(mockIde.getWorkspaceDirs as any).mockResolvedValue(["/workspace"]);
// Mock getUriPathBasename to return just the filename
(getUriPathBasename as any).mockImplementation((path: string) => {
return path.split("/").pop() || "";
});
// Mock findUriInDirs to return relative path
(findUriInDirs as any).mockImplementation((uri: string) => {
return { relativePathOrBasename: uri };
});
// Mock readFile to return content based on path
(mockIde.readFile as any).mockImplementation((path: string) => {
return Promise.resolve(mockRuleContent[path] || "");
@ -85,7 +107,7 @@ describe("loadCodebaseRules", () => {
// Mock markdownToRule to return converted rules
(markdownToRule as any).mockImplementation(
(content: string, options: any) => {
return mockConvertedRules[options.filePath];
return mockConvertedRules[options.fileUri];
},
);
});

View file

@ -3,6 +3,7 @@ import {
markdownToRule,
} from "@continuedev/config-yaml";
import { IDE, RuleWithSource } from "../..";
import { findUriInDirs } from "../../util/uri";
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
/**
@ -29,9 +30,13 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
// Process each markdown file
for (const file of mdFiles) {
try {
const { relativePathOrBasename } = findUriInDirs(
file.path,
await ide.getWorkspaceDirs(),
);
const rule = markdownToRule(file.content, {
uriType: "file",
filePath: file.path,
fileUri: relativePathOrBasename,
});
rules.push({ ...rule, source: "rules-block", ruleFile: file.path });
} catch (e) {

View file

@ -33,7 +33,7 @@ export default class LocalProfileLoader implements IProfileLoader {
iconUrl: "",
title: overrideAssistantFile?.path
? getUriPathBasename(overrideAssistantFile.path)
: "Local Assistant",
: "Local Agent",
errors: undefined,
uri:
overrideAssistantFile?.path ??
@ -48,7 +48,7 @@ export default class LocalProfileLoader implements IProfileLoader {
);
this.description.title = parsedAssistant.name;
} catch (e) {
console.error("Failed to parse assistant file: ", e);
console.error("Failed to parse agent file: ", e);
}
}
}
@ -65,8 +65,7 @@ export default class LocalProfileLoader implements IProfileLoader {
orgScopeId: null,
packageIdentifier: {
uriType: "file",
filePath:
this.overrideAssistantFile?.path ?? getPrimaryConfigFilePath(),
fileUri: this.overrideAssistantFile?.path ?? getPrimaryConfigFilePath(),
},
});

View file

@ -109,7 +109,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`,
errors: configResult.errors,
iconUrl: iconUrl,
uri: `${controlPlaneEnv}${ownerSlug}/${packageSlug}`,
uri: `${controlPlaneEnv.APP_URL}${ownerSlug}/${packageSlug}`,
rawYaml,
};

View file

@ -20,12 +20,12 @@ import {
} from "../../";
import { stringifyMcpPrompt } from "../../commands/slash/mcpSlashCommand";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import CurrentFileContextProvider from "../../context/providers/CurrentFileContextProvider";
import ContinueProxyContextProvider from "../../context/providers/ContinueProxyContextProvider";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
import RulesContextProvider from "../../context/providers/RulesContextProvider";
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { PolicySingleton } from "../../control-plane/PolicySingleton";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
import { getConfigDependentToolDefinitions } from "../../tools";
@ -35,6 +35,7 @@ import { GlobalContext } from "../../util/GlobalContext";
import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
import { localPathOrUriToPath } from "../../util/pathToUri";
import { Telemetry } from "../../util/posthog";
import { SentryLogger } from "../../util/sentry/SentryLogger";
import { TTS } from "../../util/tts";
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
import { loadContinueConfigFromJson } from "../load";
@ -60,6 +61,11 @@ async function loadRules(ide: IDE) {
rules.unshift(...markdownRules);
errors.push(...markdownRulesErrors);
// Add colocated rules from CodebaseRulesCache
const codebaseRulesCache = CodebaseRulesCache.getInstance();
rules.unshift(...codebaseRulesCache.rules);
errors.push(...codebaseRulesCache.errors);
return { rules, errors };
}
export default async function doLoadConfig(options: {
@ -91,6 +97,7 @@ export default async function doLoadConfig(options: {
const uniqueId = await ide.getUniqueId();
const ideSettings = await ideSettingsPromise;
const workOsAccessToken = await controlPlaneClient.getAccessToken();
const isSignedIn = await controlPlaneClient.isSignedIn();
// Migrations for old config files
// Removes
@ -150,17 +157,13 @@ export default async function doLoadConfig(options: {
const { rules, errors: rulesErrors } = await loadRules(ide);
errors.push(...rulesErrors);
newConfig.rules.unshift(...rules);
newConfig.contextProviders.push(new RulesContextProvider({}));
// Add current file as context if setting is enabled
if (
newConfig.experimental?.useCurrentFileAsContext === true &&
!newConfig.contextProviders.find(
(c) =>
c.description.title === CurrentFileContextProvider.description.title,
)
) {
newConfig.contextProviders.push(new CurrentFileContextProvider({}));
const proxyContextProvider = newConfig.contextProviders?.find(
(cp) => cp.description.title === "continue-proxy",
);
if (proxyContextProvider) {
(proxyContextProvider as ContinueProxyContextProvider).workOsAccessToken =
workOsAccessToken;
}
// Show deprecation warnings for providers
@ -180,11 +183,6 @@ export default async function doLoadConfig(options: {
}
});
// Add rules from colocated rules.md files in the codebase
const codebaseRulesCache = CodebaseRulesCache.getInstance();
newConfig.rules.unshift(...codebaseRulesCache.rules);
errors.push(...codebaseRulesCache.errors);
// Rectify model selections for each role
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
@ -283,6 +281,9 @@ export default async function doLoadConfig(options: {
rules: newConfig.rules,
enableExperimentalTools:
newConfig.experimental?.enableExperimentalTools ?? false,
isSignedIn,
isRemote: await ide.isWorkspaceRemote(),
modelName: newConfig.selectedModelByRole.chat?.model,
}),
);
@ -325,8 +326,18 @@ export default async function doLoadConfig(options: {
}
});
newConfig.allowAnonymousTelemetry =
newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled());
if (newConfig.allowAnonymousTelemetry !== false) {
if ((await ide.isTelemetryEnabled()) === false) {
newConfig.allowAnonymousTelemetry = false;
}
}
if (
PolicySingleton.getInstance().policy?.policy?.allowAnonymousTelemetry ===
false
) {
newConfig.allowAnonymousTelemetry = false;
}
// Setup telemetry only after (and if) we know it is enabled
await Telemetry.setup(
@ -335,6 +346,24 @@ export default async function doLoadConfig(options: {
ideInfo,
);
// Setup Sentry logger with same telemetry settings
// TODO: Remove Continue team member check once Sentry is ready for all users
let userEmail: string | undefined;
try {
// Access the session info to get user email for Continue team member check
const sessionInfo = await (controlPlaneClient as any).sessionInfoPromise;
userEmail = sessionInfo?.account?.id;
} catch (error) {
// Ignore errors getting session info, will default to no Sentry
}
await SentryLogger.setup(
newConfig.allowAnonymousTelemetry ?? false,
await ide.getUniqueId(),
ideInfo,
userEmail,
);
// TODO: pass config to pre-load non-system TTS models
await TTS.setup();

View file

@ -32,6 +32,7 @@ export const sharedConfigSchema = z
displayRawMarkdown: z.boolean(),
showChatScrollbar: z.boolean(),
autoAcceptEditToolDiffs: z.boolean(),
continueAfterToolRejection: z.boolean(),
// `tabAutocompleteOptions` in `ContinueConfig`
useAutocompleteCache: z.boolean(),
@ -158,6 +159,11 @@ export function modifyAnyConfigWithSharedConfig<
configCopy.ui.showSessionTabs = sharedConfig.showSessionTabs;
}
if (sharedConfig.continueAfterToolRejection !== undefined) {
configCopy.ui.continueAfterToolRejection =
sharedConfig.continueAfterToolRejection;
}
configCopy.experimental = {
...configCopy.experimental,
};

View file

@ -1,31 +0,0 @@
import { ModelDescription } from "../index.d";
/**
* Determines if system message tools should be auto-enabled for the given model.
* This is used to automatically enable system message tools for certain provider/model combinations
* where we have a strong preference, taking priority over user manual settings.
*
* System message tools are an alternative to native tool calling where tool definitions and calls
* are embedded in the system message as text rather than using the provider's native tool calling API.
* This can be beneficial for providers/models that don't support native tool calling or have
* poor tool calling performance.
*
* Current auto-enable rules:
* - OpenRouter provider: true for all models except those containing "claude" (since Claude models
* generally have good native tool calling support)
* - All other providers: undefined (no auto-preference, use manual setting)
*
* @param model The model description to check
* @returns true to force enable, false to force disable, undefined for no auto-preference
*/
export function shouldAutoEnableSystemMessageTools(
model: ModelDescription,
): boolean | undefined {
// Auto-enable for OpenRouter, but exclude Claude models which have good native tool calling
if (model.provider === "openrouter") {
return !model.model.toLowerCase().includes("claude");
}
// No auto-preference for all other providers - use manual setting
return undefined;
}

View file

@ -1,85 +0,0 @@
import { describe, expect, test } from "vitest";
import { ModelDescription } from "../index.d";
import { shouldAutoEnableSystemMessageTools } from "./shouldAutoEnableSystemMessageTools";
describe("shouldAutoEnableSystemMessageTools", () => {
const createModel = (provider: string, model: string): ModelDescription => ({
title: "Test Model",
provider,
underlyingProviderName: provider,
model,
});
test("should return true for OpenRouter models that don't contain 'claude'", () => {
expect(
shouldAutoEnableSystemMessageTools(createModel("openrouter", "gpt-4o")),
).toBe(true);
expect(
shouldAutoEnableSystemMessageTools(
createModel("openrouter", "llama-3.3-70b-instruct"),
),
).toBe(true);
expect(
shouldAutoEnableSystemMessageTools(
createModel("openrouter", "qwen/qwen-2.5-72b-instruct"),
),
).toBe(true);
});
test("should return false for OpenRouter Claude models", () => {
expect(
shouldAutoEnableSystemMessageTools(
createModel("openrouter", "anthropic/claude-3-sonnet"),
),
).toBe(false);
expect(
shouldAutoEnableSystemMessageTools(
createModel("openrouter", "anthropic/claude-3.5-sonnet"),
),
).toBe(false);
expect(
shouldAutoEnableSystemMessageTools(
createModel("openrouter", "claude-3-haiku"),
),
).toBe(false);
});
test("should return undefined for all other providers", () => {
expect(
shouldAutoEnableSystemMessageTools(createModel("openai", "gpt-4o")),
).toBe(undefined);
expect(
shouldAutoEnableSystemMessageTools(
createModel("anthropic", "claude-3.5-sonnet"),
),
).toBe(undefined);
expect(
shouldAutoEnableSystemMessageTools(
createModel("groq", "llama-3.3-70b-versatile"),
),
).toBe(undefined);
expect(
shouldAutoEnableSystemMessageTools(
createModel("together", "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo"),
),
).toBe(undefined);
});
test("should be case insensitive for 'claude' detection", () => {
expect(
shouldAutoEnableSystemMessageTools(
createModel("openrouter", "CLAUDE-models"),
),
).toBe(false);
expect(
shouldAutoEnableSystemMessageTools(
createModel("openrouter", "Claude-3.5"),
),
).toBe(false);
expect(
shouldAutoEnableSystemMessageTools(
createModel("openrouter", "some-model-Claude"),
),
).toBe(false);
});
});

View file

@ -387,6 +387,7 @@ declare global {
export interface PromptLog {
modelTitle: string;
modelProvider: string;
completionOptions: CompletionOptions;
prompt: string;
completion: string;

View file

@ -10,7 +10,6 @@ import {
JSONModelDescription,
PromptTemplate,
} from "../";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages";
import { GlobalContext } from "../util/GlobalContext";
import { editConfigFile } from "../util/paths";
@ -80,12 +79,6 @@ export function addModel(
maxStopWords: model.maxStopWords,
defaultCompletionOptions: model.completionOptions,
};
if (model.systemMessage) {
desc.chatOptions = {
baseSystemMessage:
DEFAULT_CHAT_SYSTEM_MESSAGE + "\n\n" + model.systemMessage,
};
}
config.models.push(desc);
return config;
},

View file

@ -4,7 +4,7 @@ import { AssistantUnrolled } from "@continuedev/config-yaml";
export const defaultConfigYaml: AssistantUnrolled = {
models: [],
context: [],
name: "Local Assistant",
name: "Local Agent",
version: "1.0.0",
schema: "v1",
};
@ -12,7 +12,7 @@ export const defaultConfigYaml: AssistantUnrolled = {
export const defaultConfigYamlJetBrains: AssistantUnrolled = {
models: [],
context: [],
name: "Local Assistant",
name: "Local Agent",
version: "1.0.0",
schema: "v1",
};

View file

@ -23,7 +23,7 @@ export async function unrollLocalYamlBlocks(
const unrollResult = await unrollAssistantFromContent(
{
uriType: "file",
filePath: "",
fileUri: "",
},
"name: FILLER\nschema: v1\nversion: 0.0.1",
registryClient,

View file

@ -14,18 +14,8 @@ import {
} from "@continuedev/config-yaml";
import { dirname } from "node:path";
import {
ContinueConfig,
IContextProvider,
IDE,
IdeInfo,
IdeSettings,
ILLMLogger,
} from "../..";
import { ContinueConfig, IDE, IdeInfo, IdeSettings, ILLMLogger } from "../..";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import FileContextProvider from "../../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../../context/providers/index";
import { ControlPlaneClient } from "../../control-plane/client";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import { getAllPromptFiles } from "../../promptFiles/getPromptFiles";
@ -35,8 +25,9 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
import { getControlPlaneEnvSync } from "../../control-plane/env";
import { getToolsForIde } from "../../tools";
import { getBaseToolDefinitions } from "../../tools";
import { getCleanUriPath } from "../../util/uri";
import { loadConfigContextProviders } from "../loadContextProviders";
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks";
import { LocalPlatformClient } from "./LocalPlatformClient";
@ -72,7 +63,7 @@ async function loadConfigYaml(options: {
);
return localBlocks.map((b) => ({
uriType: "file" as const,
filePath: b.path,
fileUri: b.path,
}));
});
const localPackageIdentifiers: PackageIdentifier[] = (
@ -87,7 +78,7 @@ async function loadConfigYaml(options: {
const getRegistryClient = async () => {
const rootPath =
packageIdentifier.uriType === "file"
? dirname(getCleanUriPath(packageIdentifier.filePath))
? dirname(getCleanUriPath(packageIdentifier.fileUri))
: undefined;
return new RegistryClient({
accessToken: await controlPlaneClient.getAccessToken(),
@ -177,7 +168,7 @@ async function configYamlToContinueConfig(options: {
const continueConfig: ContinueConfig = {
slashCommands: [],
tools: await getToolsForIde(ide),
tools: getBaseToolDefinitions(),
mcpServerStatuses: [],
contextProviders: [],
modelsByRole: {
@ -376,42 +367,14 @@ async function configYamlToContinueConfig(options: {
});
}
// Context providers
const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
({ description: { title } }) => title,
const { providers, errors: contextErrors } = loadConfigContextProviders(
config.context,
!!config.docs?.length,
ideInfo.ideType,
);
continueConfig.contextProviders = (config.context
?.map((context) => {
const cls = contextProviderClassFromName(context.provider) as any;
if (!cls) {
if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.provider)) {
localErrors.push({
fatal: false,
message: `Unknown context provider ${context.provider}`,
});
}
return undefined;
}
const instance: IContextProvider = new cls({
name: context.name,
...context.params,
});
return instance;
})
.filter((p) => !!p) ?? []) as IContextProvider[];
continueConfig.contextProviders.push(...DEFAULT_CONTEXT_PROVIDERS);
if (
continueConfig.docs?.length &&
!continueConfig.contextProviders?.some(
(cp) => cp.description.title === "docs",
)
) {
continueConfig.contextProviders.push(new DocsContextProvider({}));
}
continueConfig.contextProviders = providers;
localErrors.push(...contextErrors);
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
@ -428,6 +391,7 @@ async function configYamlToContinueConfig(options: {
timeout: server.connectionTimeout,
})),
false,
{ ide },
);
return { config: continueConfig, errors: localErrors };

View file

@ -1,14 +1,14 @@
import { describe, it, expect } from "vitest";
import {
validateConfigYaml,
AssistantUnrolledNonNullable,
validateConfigYaml,
} from "@continuedev/config-yaml";
import { describe, expect, it } from "vitest";
describe("MCP Server cwd configuration", () => {
describe("YAML schema validation", () => {
it("should accept valid MCP server with cwd", () => {
const config: AssistantUnrolledNonNullable = {
name: "test-assistant",
name: "test-agent",
version: "1.0.0",
mcpServers: [
{
@ -28,7 +28,7 @@ describe("MCP Server cwd configuration", () => {
it("should accept MCP server without cwd", () => {
const config: AssistantUnrolledNonNullable = {
name: "test-assistant",
name: "test-agent",
version: "1.0.0",
mcpServers: [
{
@ -45,7 +45,7 @@ describe("MCP Server cwd configuration", () => {
it("should accept relative paths in cwd", () => {
const config: AssistantUnrolledNonNullable = {
name: "test-assistant",
name: "test-agent",
version: "1.0.0",
mcpServers: [
{
@ -63,7 +63,7 @@ describe("MCP Server cwd configuration", () => {
it("should accept empty string cwd", () => {
const config: AssistantUnrolledNonNullable = {
name: "test-assistant",
name: "test-agent",
version: "1.0.0",
mcpServers: [
{
@ -115,7 +115,7 @@ describe("MCP Server cwd configuration", () => {
configs.forEach(({ name, server }) => {
const config: AssistantUnrolledNonNullable = {
name: "test-assistant",
name: "test-agent",
version: "1.0.0",
mcpServers: [server],
};

View file

@ -32,12 +32,14 @@ async function modelConfigToBaseLLM({
ideSettings,
llmLogger,
config,
isFromAutoDetect,
}: {
model: ModelConfig;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
config: ContinueConfig;
isFromAutoDetect?: boolean;
}): Promise<BaseLLM | undefined> {
const cls = getModelClass(model);
@ -71,6 +73,7 @@ async function modelConfigToBaseLLM({
nextEdit: model.capabilities?.includes("next_edit"),
},
autocompleteOptions: model.autocompleteOptions,
isFromAutoDetect,
};
// Model capabilities - need to be undefined if not found
@ -173,7 +176,6 @@ async function autodetectModels({
if (modelName === AUTODETECT) {
return undefined;
}
return await modelConfigToBaseLLM({
model: {
...model,
@ -184,6 +186,7 @@ async function autodetectModels({
ideSettings,
llmLogger,
config,
isFromAutoDetect: true,
});
}),
);

View file

@ -1,12 +1,16 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import {
SSEClientTransport,
SseError,
} from "@modelcontextprotocol/sdk/client/sse.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
import {
IDE,
MCPConnectionStatus,
MCPOptions,
MCPPrompt,
@ -16,6 +20,7 @@ import {
MCPTool,
} from "../..";
import { getEnvPathFromUserShell } from "../../util/shellPath";
import { getOauthToken } from "./MCPOauth";
const DEFAULT_MCP_TIMEOUT = 20_000; // 20 seconds
@ -30,10 +35,23 @@ const WINDOWS_BATCH_COMMANDS = [
"bunx",
];
function is401Error(error: unknown) {
return (
(error instanceof SseError && error.code === 401) ||
(error instanceof Error && error.message.includes("401")) ||
(error instanceof Error && error.message.includes("Unauthorized"))
);
}
export type MCPExtras = {
ide: IDE;
};
class MCPConnection {
public client: Client;
public abortController: AbortController;
public status: MCPConnectionStatus = "not-connected";
public isProtectedResource = false;
public errors: string[] = [];
public prompts: MCPPrompt[] = [];
public tools: MCPTool[] = [];
@ -46,7 +64,10 @@ class MCPConnection {
stderr: "",
};
constructor(public options: MCPOptions) {
constructor(
public options: MCPOptions,
public extras?: MCPExtras,
) {
// Don't construct transport in constructor to avoid blocking
this.transport = {} as Transport; // Will be set in connectClient
@ -78,6 +99,7 @@ class MCPConnection {
resourceTemplates: this.resourceTemplates,
tools: this.tools,
status: this.status,
isProtectedResource: this.isProtectedResource,
};
}
@ -106,6 +128,26 @@ class MCPConnection {
this.abortController.abort();
this.abortController = new AbortController();
// currently support oauth for sse transports only
if (this.options.transport.type === "sse") {
if (!this.options.transport.requestOptions) {
this.options.transport.requestOptions = {
headers: {},
};
}
const accessToken = await getOauthToken(
this.options.transport.url,
this.extras?.ide!,
);
if (accessToken) {
this.isProtectedResource = true;
this.options.transport.requestOptions.headers = {
...this.options.transport.requestOptions.headers,
Authorization: `Bearer ${accessToken}`,
};
}
}
this.connectionPromise = Promise.race([
// If aborted by a refresh or other, cancel and don't do anything
new Promise((resolve) => {
@ -244,6 +286,10 @@ class MCPConnection {
}
}
if (is401Error(error)) {
this.isProtectedResource = true;
}
// Include stdio output if available for stdio transport
if (
this.options.transport.type === "stdio" &&

View file

@ -1,7 +1,6 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { beforeEach, describe, expect, it, vi } from "vitest";
import MCPConnection from "./MCPConnection";
import { StdioOptions } from "../../index.d.js";
// Mock the shell path utility
vi.mock("../../util/shellPath", () => ({
@ -143,6 +142,7 @@ describe("MCPConnection", () => {
expect(status).toEqual({
...options,
errors: [],
isProtectedResource: false,
prompts: [],
resources: [],
resourceTemplates: [],

View file

@ -6,7 +6,7 @@ import {
StdioOptions,
TransportOptions,
} from "../..";
import MCPConnection from "./MCPConnection";
import MCPConnection, { MCPExtras } from "./MCPConnection";
export class MCPManagerSingleton {
private static instance: MCPManagerSingleton;
@ -26,12 +26,12 @@ export class MCPManagerSingleton {
}
createConnection(id: string, options: MCPOptions): MCPConnection {
if (!this.connections.has(id)) {
if (this.connections.has(id)) {
return this.connections.get(id)!;
} else {
const connection = new MCPConnection(options);
this.connections.set(id, connection);
return connection;
} else {
return this.connections.get(id)!;
}
}
@ -48,7 +48,11 @@ export class MCPManagerSingleton {
this.connections.delete(id);
}
setConnections(servers: MCPOptions[], forceRefresh: boolean) {
setConnections(
servers: MCPOptions[],
forceRefresh: boolean,
extras?: MCPExtras,
) {
let refresh = false;
// Remove any connections that are no longer in config
@ -73,15 +77,15 @@ export class MCPManagerSingleton {
// Add any connections that are not yet in manager
servers.forEach((server) => {
if (!this.connections.has(server.id)) {
refresh = true;
this.connections.set(server.id, new MCPConnection(server));
} else {
if (this.connections.has(server.id)) {
const conn = this.connections.get(server.id);
if (conn) {
// We need to update it. Some attributes may have changed, such as name, faviconUrl, etc.
conn.options = server;
}
} else {
refresh = true;
this.connections.set(server.id, new MCPConnection(server, extras));
}
});
@ -162,6 +166,10 @@ export class MCPManagerSingleton {
}));
}
setStatus(server: MCPServerStatus, status: MCPServerStatus["status"]) {
this.connections.get(server.id)!.status = status;
}
async getPrompt(
serverName: string,
promptName: string,

View file

@ -0,0 +1,227 @@
import {
OAuthClientProvider,
auth,
} from "@modelcontextprotocol/sdk/client/auth.js";
import {
OAuthClientInformationFull,
OAuthClientInformationSchema,
OAuthTokens,
OAuthTokensSchema,
} from "@modelcontextprotocol/sdk/shared/auth.js";
import { IDE, MCPServerStatus, SSEOptions } from "../..";
import http from "http";
import url from "url";
import { GlobalContext, GlobalContextType } from "../../util/GlobalContext";
let authenticatingMCPContext = null as {
authenticatingServer: MCPServerStatus;
ide: IDE;
} | null;
const PORT = 3000;
const server = http.createServer((req, res) => {
try {
if (!req.url) {
throw new Error("no url found");
}
const parsedUrl = url.parse(req.url, true);
if (!parsedUrl.query["code"]) {
throw new Error("no query params found");
}
void handleMCPOauthCode(parsedUrl.query["code"] as string);
const html = `
<!DOCTYPE html>
<html>
<head><title>Authentication Complete</title></head>
<body>Authentication Complete. You can close this page now.</body>
</html>`;
res.writeHead(200, {
"Content-Type": "text/html",
});
res.end(html);
} catch (error) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end(`Unexpected redirect error: ${(error as Error).message}`);
}
});
type MCPOauthStorage = GlobalContextType["mcpOauthStorage"][string];
type MCPOauthStorageKey = keyof MCPOauthStorage;
class MCPConnectionOauthProvider implements OAuthClientProvider {
private globalContext: GlobalContext;
constructor(
public oauthServerUrl: string,
private ide: IDE,
) {
this.globalContext = new GlobalContext();
}
get redirectUrl() {
return `http://localhost:${PORT}`; // TODO: this has to be a hub url or should we spin up a server?
}
get clientMetadata() {
return {
redirect_uris: [this.redirectUrl],
token_endpoint_auth_method: "none",
grant_types: ["authorization_code", "refresh_token"],
response_types: ["code"],
client_name: "Continue Dev, Inc", // get this from package.json?
client_uri: "https://continue.dev", // get this from package.json?
};
}
private _getOauthStorage<K extends MCPOauthStorageKey>(key: K) {
return this.globalContext.get("mcpOauthStorage")?.[this.oauthServerUrl]?.[
key
];
}
private _updateOauthStorage<K extends MCPOauthStorageKey>(
key: K,
value: MCPOauthStorage[K],
) {
const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {};
const existingServerStorage = existingStorage[this.oauthServerUrl] ?? {};
this.globalContext.update("mcpOauthStorage", {
...existingStorage,
[this.oauthServerUrl]: {
...existingServerStorage,
[key]: value,
},
});
}
private _clearOauthStorage() {
const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {};
delete existingStorage[this.oauthServerUrl];
this.globalContext.update("mcpOauthStorage", existingStorage);
}
saveClientInformation(clientInformation: OAuthClientInformationFull) {
this._updateOauthStorage("clientInformation", clientInformation);
}
async clientInformation() {
const existingClientInformation =
this._getOauthStorage("clientInformation");
if (!existingClientInformation) {
return undefined;
}
return await OAuthClientInformationSchema.parseAsync(
existingClientInformation,
);
}
async tokens() {
const existingTokens = this._getOauthStorage("tokens");
if (!existingTokens) {
return undefined;
}
return await OAuthTokensSchema.parseAsync(existingTokens);
}
saveTokens(tokens: OAuthTokens) {
this._updateOauthStorage("tokens", tokens);
}
codeVerifier(): string | Promise<string> {
const existingCodeVerifier = this._getOauthStorage("codeVerifier");
if (!existingCodeVerifier) {
return "";
}
return existingCodeVerifier;
}
saveCodeVerifier(codeVerifier: string) {
this._updateOauthStorage("codeVerifier", codeVerifier);
}
clear() {
this._clearOauthStorage();
}
async redirectToAuthorization(authorizationUrl: URL) {
if (!server.listening) {
server.listen(PORT, () => {
console.debug(
`Server started for MCP Oauth process at http://localhost:${PORT}/`,
);
});
}
void this.ide.openUrl(authorizationUrl.toString());
}
}
export async function getOauthToken(mcpServerUrl: string, ide: IDE) {
const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
const tokens = await authProvider.tokens();
return tokens?.access_token;
}
/**
* checks if the authentication is already done for the current server
* if not, starts the authentication process by opening a webpage url
*/
export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) {
const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
authenticatingMCPContext = {
authenticatingServer: mcpServer,
ide,
};
return await auth(authProvider, {
serverUrl: mcpServerUrl,
});
}
/**
* handle the authentication code received from the oauth redirect
*/
async function handleMCPOauthCode(authorizationCode: string) {
if (!authenticatingMCPContext) {
return;
}
const { ide, authenticatingServer } = authenticatingMCPContext;
const serverUrl = (authenticatingServer.transport as SSEOptions).url;
if (!serverUrl) {
void ide.showToast("error", "No MCP server url found for authentication");
return;
}
if (!authorizationCode) {
void ide.showToast(
"error",
`No MCP authorization code found for ${serverUrl}`,
);
return;
}
server.close(() => console.debug("Server for MCP Oauth process was closed"));
const authProvider = new MCPConnectionOauthProvider(serverUrl, ide);
const authStatus = await auth(authProvider, {
serverUrl,
authorizationCode,
});
if (authStatus === "AUTHORIZED") {
const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports
await MCPManagerSingleton.getInstance().refreshConnection(
authenticatingServer.id,
);
}
authenticatingMCPContext = null;
}
export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) {
const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
authProvider.clear();
}

View file

@ -0,0 +1,181 @@
import fs from "node:fs";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { GlobalContext } from "../../util/GlobalContext";
import { getGlobalContextFilePath } from "../../util/paths";
import { getOauthToken, performAuth, removeMCPAuth } from "./MCPOauth";
// Mock the MCP SDK auth module
vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({
auth: vi.fn(),
}));
// Mock the MCPManagerSingleton to avoid circular imports
vi.mock("./MCPManagerSingleton", () => ({
MCPManagerSingleton: {
getInstance: vi.fn(() => ({
refreshConnection: vi.fn(),
})),
},
}));
describe("MCPOauth", () => {
let globalContextFilePath: string;
let mockIde: any;
let mockMcpServer: any;
beforeEach(() => {
// file is present in the core/test directory
globalContextFilePath = getGlobalContextFilePath();
if (fs.existsSync(globalContextFilePath)) {
fs.unlinkSync(globalContextFilePath);
}
mockIde = {
openUrl: vi.fn(),
showToast: vi.fn(),
};
mockMcpServer = {
id: "test-server",
transport: {
type: "sse",
url: "https://test-server.com",
},
};
vi.clearAllMocks();
});
afterEach(() => {
if (fs.existsSync(globalContextFilePath)) {
fs.unlinkSync(globalContextFilePath);
}
});
describe("getOauthToken", () => {
test("should return undefined when no tokens are stored", async () => {
const result = await getOauthToken("https://test-server.com", mockIde);
expect(result).toBeUndefined();
});
test("should return access token when tokens are stored", async () => {
const globalContext = new GlobalContext();
globalContext.update("mcpOauthStorage", {
"https://test-server.com": {
tokens: {
access_token: "test-access-token",
token_type: "Bearer",
},
},
});
const result = await getOauthToken("https://test-server.com", mockIde);
expect(result).toBe("test-access-token");
});
test("should handle different server URLs independently", async () => {
const globalContext = new GlobalContext();
globalContext.update("mcpOauthStorage", {
"https://server1.com": {
tokens: {
access_token: "token1",
token_type: "Bearer",
},
},
"https://server2.com": {
tokens: {
access_token: "token2",
token_type: "Bearer",
},
},
});
const result1 = await getOauthToken("https://server1.com", mockIde);
const result2 = await getOauthToken("https://server2.com", mockIde);
const result3 = await getOauthToken("https://server3.com", mockIde);
expect(result1).toBe("token1");
expect(result2).toBe("token2");
expect(result3).toBeUndefined();
});
});
describe("performAuth", () => {
test("should call auth with correct parameters and return auth result", async () => {
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
const mockAuth = vi.mocked(auth);
mockAuth.mockResolvedValue("AUTHORIZED");
const result = await performAuth(mockMcpServer, mockIde);
expect(mockAuth).toHaveBeenCalledWith(
expect.any(Object), // MCPConnectionOauthProvider instance
{
serverUrl: "https://test-server.com",
},
);
expect(result).toBe("AUTHORIZED");
});
});
describe("removeMCPAuth", () => {
test("should clear oauth storage for the server", () => {
const globalContext = new GlobalContext();
globalContext.update("mcpOauthStorage", {
"https://test-server.com": {
tokens: {
access_token: "test-access-token",
token_type: "Bearer",
},
clientInformation: {
client_id: "test-client-id",
redirect_uris: ["http://localhost:3000"],
},
codeVerifier: "test-code-verifier",
},
"https://other-server.com": {
tokens: {
access_token: "other-access-token",
token_type: "Bearer",
},
},
});
removeMCPAuth(mockMcpServer, mockIde);
const updatedStorage = globalContext.get("mcpOauthStorage");
expect(updatedStorage).toEqual({
"https://other-server.com": {
tokens: {
access_token: "other-access-token",
token_type: "Bearer",
},
},
});
});
test("should handle non-existent server gracefully", () => {
const globalContext = new GlobalContext();
globalContext.update("mcpOauthStorage", {
"https://other-server.com": {
tokens: {
access_token: "other-access-token",
token_type: "Bearer",
},
},
});
removeMCPAuth(mockMcpServer, mockIde);
const updatedStorage = globalContext.get("mcpOauthStorage");
expect(updatedStorage).toEqual({
"https://other-server.com": {
tokens: {
access_token: "other-access-token",
token_type: "Bearer",
},
},
});
});
});
});

View file

@ -18,6 +18,10 @@ class ClipboardContextProvider extends BaseContextProvider {
type: "submenu",
};
get deprecationMessage() {
return "The clipboard context provider is deprecated as it is not used. It will be removed in a future version.";
}
async getContextItems(
query: string,
extras: ContextProviderExtras,

View file

@ -1,68 +0,0 @@
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
} from "../../index.js";
import { BaseContextProvider } from "../index.js";
const HIGHLIGHTS_TOKEN_BUDGET = 2000;
class CodeHighlightsContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "highlights",
displayTitle: "Highlights",
description: "Code highlights from open files",
type: "normal",
renderInlineAs: "",
};
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
// const { getHighlightsThatFit } = await import(
// "llm-code-highlighter/src/index.continue.js"
// );
const ide = extras.ide;
const openFiles = await ide.getOpenFiles();
// const allFiles: { name: string; absPath: string; content: string }[] =
// await Promise.all(
// openFiles.map(async (filepath: string) => {
// return {
// name: getBasename(filepath),
// absPath: filepath,
// content: `${await ide.readFile(filepath)}`,
// };
// }),
// );
// const contextSizer = {
// fits(content: string): boolean {
// return countTokens(content, "") < HIGHLIGHTS_TOKEN_BUDGET;
// },
// };
// const repoMap = await getHighlightsThatFit(
// contextSizer,
// [],
// allFiles
// .filter((file) => file.content.length > 0)
// .map((file) => {
// return {
// relPath: file.name,
// code: file.content,
// };
// }),
// );
// return [
// {
// content: repoMap ? repoMap : "",
// name: "Code Highlights",
// description: "Code highlights from open files",
// },
// ];
return [];
}
async load(): Promise<void> {}
}
export default CodeHighlightsContextProvider;

View file

@ -1,56 +0,0 @@
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
} from "../../index.js";
import { BaseContextProvider } from "../index.js";
class CodeOutlineContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "outline",
displayTitle: "Outline",
description: "Definition lines only (from open files)",
type: "normal",
renderInlineAs: "",
};
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const ide = extras.ide;
const openFiles = await ide.getOpenFiles();
// const allFiles: { name: string; absPath: string; content: string }[] =
// await Promise.all(
// openFiles.map(async (filepath: string) => {
// return {
// name: getBasename(filepath),
// absPath: filepath,
// content: `${await ide.readFile(filepath)}`,
// };
// }),
// );
// const outlines = await getOutlines(
// allFiles
// .filter((file) => file.content.length > 0)
// .map((file) => {
// return {
// relPath: file.name,
// code: file.content,
// };
// })
// );
// return [
// {
// content: outlines ? outlines : "",
// name: "Code Outline",
// description: "Definition lines only (from open files)",
// },
// ];
return [];
}
async load(): Promise<void> {}
}
export default CodeOutlineContextProvider;

View file

@ -13,6 +13,7 @@ class CodebaseContextProvider extends BaseContextProvider {
description: "Automatically find relevant files",
type: "normal",
renderInlineAs: "",
dependsOnIndexing: true,
};
async getContextItems(

View file

@ -18,6 +18,10 @@ class DatabaseContextProvider extends BaseContextProvider {
renderInlineAs: "",
};
get deprecationMessage() {
return "The database context provider is deprecated and may be removed in a later version. Please consider using a database MCP server like postgres-mcp (https://hub.continue.dev/anthropic/postgres-mcp) instead.";
}
async getContextItems(
query: string,
extras: ContextProviderExtras,

View file

@ -3,8 +3,8 @@ import {
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
FetchFunction,
LoadSubmenuItemsArgs,
} from "../../index.js";
import { BaseContextProvider } from "../index.js";
@ -43,6 +43,10 @@ class DiscordContextProvider extends BaseContextProvider {
return `${this.baseUrl}${path}`;
}
get deprecationMessage() {
return "The Discord context provider is now deprecated and may be removed in a later version. Please consider using the Discord MCP (hub.docker.com/r/mcp/mcp-discord) instead.";
}
async fetchMessages(
channelId: string,
fetch: FetchFunction,

View file

@ -43,9 +43,13 @@ class DocsContextProvider extends BaseContextProvider {
try {
const scores = await reranker.rerank(fullInput, chunksCopy);
chunksCopy.sort(
(a, b) => scores[chunksCopy.indexOf(b)] - scores[chunksCopy.indexOf(a)],
);
if (Array.isArray(scores)) {
// reranker model has returned a valid array
chunksCopy.sort(
(a, b) =>
scores[chunksCopy.indexOf(b)] - scores[chunksCopy.indexOf(a)],
);
}
chunksCopy = chunksCopy.splice(
0,

View file

@ -6,6 +6,7 @@ import {
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../";
import { isSecurityConcern } from "../../indexing/ignore";
import { walkDirs } from "../../indexing/walkDir";
import {
getShortestUniqueRelativeUriPaths,

View file

@ -44,6 +44,10 @@ class GitCommitContextProvider extends BaseContextProvider {
type: "submenu",
};
get deprecationMessage() {
return "The git commits context provider is now deprecated and may be removed in a later version. Please consider using the Git MCP (https://hub.continue.dev/docker/mcp-git) instead.";
}
async getContextItems(
query: string,
extras: ContextProviderExtras,

View file

@ -15,6 +15,10 @@ class GitHubIssuesContextProvider extends BaseContextProvider {
type: "submenu",
};
get deprecationMessage() {
return "The GitHub issues context provider is now deprecated and will be removed in a later version. Please consider using the GitHub MCP server (https://hub.continue.dev/anthropic/github-mcp) instead.";
}
async getContextItems(
query: string,
extras: ContextProviderExtras,

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