Merge branch 'main' into per-tab-model-persistence

This commit is contained in:
ferenci84 2025-11-09 11:36:18 +01:00
commit 6bf5ee15d6
813 changed files with 49654 additions and 20108 deletions

View file

@ -0,0 +1,3 @@
{
"install": "npm i"
}

View file

@ -35,7 +35,6 @@ IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock
Instead, generate actual mock files and data for operations
Pure mocks should only be used to emulate specific network responses/error or hard-to-duplicate errors, or to prevent long-duration tests
Additional types can be imported from @core/index.d.ts
If any needed types, functions, constants, or classes are still not found, warn the user and do not generate tests.
Additional types can be imported from @core/index.d.ts. If any needed types, functions, constants, or classes are still not found, warn the user and do not generate tests.
Write the comment "// Generated by continue" at the top of the generated code/file (not the filepath)
Write the comment "// Generated by continue" at the top of the generated code/file (not the filepath)

View file

@ -0,0 +1,100 @@
# Mintlify Documentation Formatting Rules
## Component Formatting
When working with Mintlify documentation components (Card, Info, Tip, Note, Warning, etc.), follow these formatting guidelines:
### Bullet Points and Lists
1. **Always add a blank line** after the opening component tag and before the closing tag
2. **Indent content** by 2 spaces within components
3. **Use proper list formatting** with each item on its own line:
- Start lists on a new line after introductory text
- Use `-` for unordered lists
- Maintain consistent indentation
### Examples
#### ✅ Correct Formatting:
```mdx
<Card title="Example" icon="icon-name">
This is the content with proper formatting:
- First bullet point
- Second bullet point
- Third bullet point
</Card>
```
```mdx
<Info>
Important information here:
- Point one
- Point two
- Point three
</Info>
```
#### ❌ Incorrect Formatting:
```mdx
<Card title="Example" icon="icon-name">
This is wrong: - All bullets - On one line - Bad formatting
</Card>
```
### Component-Specific Rules
1. **Card Components**: Always include blank lines and proper indentation
2. **Info/Tip/Note/Warning**: Format lists as bullet points, not inline
3. **CardGroup**: Each Card within should follow the same formatting rules
4. **Code Blocks**: Within components, maintain proper indentation
### Links in Lists
When including links in bullet points:
```mdx
- [Link Text](url): Description of the link
```
### Nested Components
For nested components, maintain proper indentation levels:
```mdx
<CardGroup>
<Card title="First Card">
Content here:
- Bullet one
- Bullet two
</Card>
<Card title="Second Card">
More content:
- Another bullet
- Final bullet
</Card>
</CardGroup>
```
## Application
These rules apply to all `.mdx` files in the `docs/` directory, particularly:
- Guide documents
- Cookbook documents
- Reference documentation
- Any Mintlify-powered documentation
## Automation Note
When using Continue or other AI assistants to generate or modify documentation:
- Always format Mintlify components according to these rules
- Review generated content for proper formatting
- Apply these rules consistently across all documentation

View file

@ -0,0 +1,6 @@
---
name: Personality Rules
description: Conversational and personality guidelines
---
When the user challenges your output or asks a question, don't be overly-amiable (e.g. responding "You're right" all the time). Focus on correctness and be willing to tell the user they are wrong.

View file

@ -31,12 +31,18 @@ runs:
packages/*/node_modules
key: ${{ runner.os }}-packages-node-modules-${{ hashFiles('packages/*/package-lock.json') }}
- uses: actions/cache@v4
- uses: actions/cache@v4
if: inputs.include-root == 'true'
id: root-cache
with:
path: node_modules
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
- name: Install root dependencies
if: inputs.include-root == 'true' && steps.root-cache.outputs.cache-hit != 'true'
shell: bash
run: npm ci
- uses: actions/cache@v4
id: component-cache
with:

View file

@ -5,7 +5,7 @@
## 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`
- Team members can also trigger a review by commenting `@continue-review`
## Checklist

View file

@ -97,7 +97,7 @@ jobs:
- name: Setup Node.js
if: steps.workflow-details.outputs.has_failed_tests == 'true'
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version: "20"

View file

@ -24,7 +24,7 @@ jobs:
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version: 20
registry-url: "https://registry.npmjs.org"
@ -110,6 +110,6 @@ jobs:
# Create GitHub release
gh release create "v${{ steps.get_version.outputs.beta_version }}" \
--title "Beta Release v${{ steps.get_version.outputs.beta_version }}" \
--title "CLI 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,agent@continue.dev
allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline,agent@continue.dev,action@github.com,snyk-bot
signed-commit-message: "CLA signed in $pullRequestNo"

View file

@ -25,7 +25,7 @@ jobs:
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version: 20
cache: "npm"
@ -67,7 +67,7 @@ jobs:
uses: actions/checkout@v5
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version: ${{ matrix.node-version }}

View file

@ -104,7 +104,7 @@ jobs:
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version-file: ".nvmrc"
cache: "npm"
@ -119,12 +119,12 @@ jobs:
run: npm audit --audit-level=moderate
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
uses: github/codeql-action/init@v4
with:
languages: javascript
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
uses: github/codeql-action/analyze@v4
# Use this for any files that we want to be certain exist
# Basically creates a forcing function to discuss were anyone to want to remove them

View file

@ -1,25 +0,0 @@
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@12e933bf9d13736c5f47728c436445ef4127fd52
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: continuedev
continue-config: continuedev/review-bot

View file

@ -1,6 +1,9 @@
name: Continue General Review
on:
push:
branches:
- main
pull_request:
types: [opened, ready_for_review]
issue_comment:
@ -18,8 +21,8 @@ jobs:
timeout-minutes: 10
steps:
- name: Run Continue PR Review Action
uses: continuedev/continue/actions/general-review@12e933bf9d13736c5f47728c436445ef4127fd52
uses: continuedev/continue/actions/general-review@main
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "continuedev"
continue-config: "continuedev/review-bot"
continue-agent: "empty-agent"

View file

@ -0,0 +1,24 @@
name: Delete Stale Branches
on:
schedule:
- cron: "0 6 * * 1-5"
workflow_dispatch:
permissions:
issues: write
contents: write
jobs:
stale_branches:
runs-on: ubuntu-latest
steps:
- name: Stale Branches
uses: crs-k/stale-branches@v8.2.2
with:
repo-token: "${{ secrets.GITHUB_TOKEN }}"
days-before-stale: 59
days-before-delete: 60
pr-check: true
ignore-issue-interaction: true
branches-filter-regex: "^(?!cla-signatures$).*"

View file

@ -95,7 +95,7 @@ jobs:
needs: check_release_name
if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch'
name: Build Plugin
runs-on: macos-13
runs-on: macos-latest
permissions:
contents: write
pull-requests: write
@ -116,7 +116,7 @@ jobs:
# Validate wrapper
- name: Gradle Wrapper Validation
uses: gradle/actions/wrapper-validation@v3
uses: gradle/actions/wrapper-validation@v5
# # Set up Java environment for the next steps
- name: Setup Java
@ -127,7 +127,7 @@ jobs:
# # Setup Gradle
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v3
uses: gradle/actions/setup-gradle@v5
with:
gradle-home-cache-cleanup: true
@ -152,7 +152,7 @@ jobs:
# # Setup Node.js
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version-file: ".nvmrc"
@ -294,44 +294,44 @@ jobs:
# Store already-built plugin as an artifact for downloading
- name: Upload artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: ${{ steps.artifact.outputs.filename }}
path: ./extensions/intellij/build/distributions/content/*/*
# Upload binaries as artifacts
- name: Upload artifact (darwin-arm64)
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: continue-binary-darwin-arm64
path: ./binary/bin/darwin-arm64/
- name: Upload artifact (darwin-x64)
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: continue-binary-darwin-x64
path: ./binary/bin/darwin-x64/
- name: Upload artifact (win32-x64)
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: continue-binary-win32-x64
path: ./binary/bin/win32-x64/
- name: Upload artifact (win32-arm64)
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: continue-binary-win32-arm64
path: ./binary/bin/win32-arm64/
- name: Upload artifact (linux-arm64)
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: continue-binary-linux-arm64
path: ./binary/bin/linux-arm64/
- name: Upload artifact (linux-x64)
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: continue-binary-linux-x64
path: ./binary/bin/linux-x64/
@ -358,7 +358,7 @@ jobs:
platform: darwin
arch: x64
npm_config_arch: x64
- os: macos-13
- os: macos-latest
platform: darwin
arch: arm64
npm_config_arch: arm64
@ -370,7 +370,7 @@ jobs:
# 2. Install npm dependencies
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version-file: ".nvmrc"
@ -398,7 +398,7 @@ jobs:
# Download the binary artifact
- name: Download binary artifact
uses: actions/download-artifact@v5
uses: actions/download-artifact@v6
with:
name: continue-binary-${{ matrix.platform }}-${{ matrix.arch }}
path: ./binary/bin/${{ matrix.platform }}-${{ matrix.arch }}/
@ -420,7 +420,7 @@ jobs:
- name: Upload logs
if: ${{ always() }}
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: core-logs-${{ matrix.platform }}-${{ matrix.arch }}
path: ~/.continue/logs/core.log
@ -444,7 +444,7 @@ jobs:
# Setup Gradle
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v3
uses: gradle/actions/setup-gradle@v5
with:
gradle-home-cache-cleanup: true
@ -455,7 +455,7 @@ jobs:
# Collect Tests Result of failed tests
- name: Collect Tests Result
if: ${{ failure() }}
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: tests-result
path: ${{ github.workspace }}/extensions/intellij/build/reports/tests
@ -522,7 +522,7 @@ jobs:
# Setup Gradle
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v3
uses: gradle/actions/setup-gradle@v5
with:
gradle-home-cache-cleanup: true
@ -540,7 +540,7 @@ jobs:
# Collect Plugin Verifier Result
- name: Collect Plugin Verifier Result
if: ${{ always() }}
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: pluginVerifier-result
path: ${{ github.workspace }}/build/reports/pluginVerifier
@ -563,7 +563,7 @@ jobs:
# ./gradlew patchChangelog --release-note="$CHANGELOG"
- name: Download the plugin
uses: actions/download-artifact@v5
uses: actions/download-artifact@v6
with:
name: ${{ steps.artifact.outputs.filename }}
path: ./build/distributions/

View file

@ -101,7 +101,7 @@ jobs:
echo "✅ Successfully downloaded artifact"
- name: Republish as main branch artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: vscode-extension-build-${{ matrix.platform }}
path: ./temp-download/*

View file

@ -26,8 +26,24 @@ jobs:
echo "should_run=false" >> $GITHUB_OUTPUT
fi
check-version:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v5
with:
fetch-depth: 0 # This ensures all tags are fetched
- name: Checkout tag
run: git checkout ${GITHUB_REF#refs/tags/}
- name: Make sure version isn't odd
run: |
cd extensions/vscode
node scripts/versionCheck.js
build:
needs: check_release_name
needs: [check_release_name, check-version]
if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch'
runs-on: ${{ matrix.os }}
strategy:
@ -57,11 +73,11 @@ jobs:
platform: alpine
arch: x64
npm_config_arch: x64
- os: macos-13
- os: macos-latest
platform: darwin
arch: x64
npm_config_arch: x64
- os: macos-13
- os: macos-latest
platform: darwin
arch: arm64
npm_config_arch: arm64
@ -70,7 +86,7 @@ jobs:
with:
fetch-depth: 0
- uses: actions/setup-node@v5
- uses: actions/setup-node@v6
with:
node-version-file: ".nvmrc"
@ -83,27 +99,11 @@ jobs:
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Upload .vsix artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix
path: "extensions/vscode/*.vsix"
check-version:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v5
with:
fetch-depth: 0 # This ensures all tags are fetched
- name: Checkout tag
run: git checkout ${GITHUB_REF#refs/tags/}
- name: Make sure version isn't odd
run: |
cd extensions/vscode
node scripts/versionCheck.js
release:
permissions:
contents: write
@ -120,7 +120,7 @@ jobs:
git config --local user.name "GitHub Action"
# Download the .vsix artifacts
- uses: actions/download-artifact@v5
- uses: actions/download-artifact@v6
with:
pattern: "*-vsix"
path: vsix-artifacts
@ -156,7 +156,7 @@ jobs:
run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }}
# 1. Download the artifacts
- uses: actions/download-artifact@v5
- uses: actions/download-artifact@v6
with:
pattern: "*-vsix"
path: vsix-artifacts

View file

@ -69,7 +69,7 @@ jobs:
${{ steps.read-metrics.outputs.metrics_content }}
- name: Upload metrics report as artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: issue-metrics-report
path: ./issue_metrics.md

View file

@ -39,13 +39,13 @@ jobs:
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Upload build artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: vscode-extension-build-${{ matrix.platform }}-${{ matrix.arch }}
path: extensions/vscode/build
- name: Upload .vsix artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix
path: "extensions/vscode/*.vsix"

View file

@ -23,7 +23,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
- uses: actions/setup-node@v6
with:
node-version-file: ".nvmrc"
@ -229,7 +229,7 @@ jobs:
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
- uses: actions/setup-node@v6
with:
node-version-file: ".nvmrc"
@ -303,7 +303,7 @@ jobs:
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Upload build artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: vscode-extension-build-Linux
path: extensions/vscode/build
@ -343,31 +343,6 @@ 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@v5
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:
@ -385,7 +360,6 @@ 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

@ -57,11 +57,11 @@ jobs:
platform: alpine
arch: x64
npm_config_arch: x64
- os: macos-13
- os: macos-latest
platform: darwin
arch: x64
npm_config_arch: x64
- os: macos-13
- os: macos-latest
platform: darwin
arch: arm64
npm_config_arch: arm64
@ -70,7 +70,7 @@ jobs:
with:
fetch-depth: 0
- uses: actions/setup-node@v5
- uses: actions/setup-node@v6
with:
node-version-file: ".nvmrc"
@ -83,7 +83,7 @@ jobs:
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Upload .vsix artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v5
with:
name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix
path: "extensions/vscode/*.vsix"
@ -104,7 +104,7 @@ jobs:
git config --local user.name "GitHub Action"
# Download the .vsix artifacts
- uses: actions/download-artifact@v5
- uses: actions/download-artifact@v6
with:
pattern: "*-vsix"
path: vsix-artifacts
@ -142,7 +142,7 @@ jobs:
run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }}
# 1. Download the artifacts
- uses: actions/download-artifact@v5
- uses: actions/download-artifact@v6
with:
pattern: "*-vsix"
path: vsix-artifacts
@ -165,7 +165,7 @@ jobs:
# 4. Create PR with version bump
- name: Setup Node.js
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version-file: ".nvmrc"

View file

@ -1,11 +1,17 @@
name: Release @continuedev/llm-info
on:
push:
branches:
- main
paths:
- "packages/llm-info/**"
- ".github/workflows/release-llm-info.yml"
- ".github/workflows/reusable-release.yml"
permissions:
contents: write
issues: write
pull-requests: write
jobs:
release:
@ -16,14 +22,3 @@ jobs:
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}

View file

@ -1,302 +0,0 @@
name: Respond to @continuedev Comments
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
permissions:
contents: write
pull-requests: write
issues: write
jobs:
respond-to-comment:
# Only run on pull request comments
if: github.event_name == 'issue_comment' && github.event.issue.pull_request
runs-on: ubuntu-latest
steps:
- name: Check if comment contains @continuedev
id: check-mention
run: |
# Create a temporary file to safely handle comment body with special characters
cat > /tmp/comment.txt << 'COMMENT_EOF'
${{ github.event.comment.body }}
COMMENT_EOF
if grep -q "@continuedev" /tmp/comment.txt; then
echo "contains_mention=true" >> $GITHUB_OUTPUT
else
echo "contains_mention=false" >> $GITHUB_OUTPUT
fi
- name: Add eyes reaction to comment
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/github-script@v8
with:
script: |
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: ${{ github.event.comment.id }},
content: 'eyes'
});
- name: Checkout PR branch
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/checkout@v5
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
- name: Get PR information
if: steps.check-mention.outputs.contains_mention == 'true'
id: pr-info
uses: actions/github-script@v8
with:
script: |
const { data: pr } = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number
});
core.setOutput('head_ref', pr.head.ref);
core.setOutput('head_sha', pr.head.sha);
return pr;
- name: Checkout PR branch
if: steps.check-mention.outputs.contains_mention == 'true'
run: |
git checkout ${{ steps.pr-info.outputs.head_ref }}
- name: Setup Node.js
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/setup-node@v5
with:
node-version: "20"
- name: Install Continue CLI globally
if: steps.check-mention.outputs.contains_mention == 'true'
run: npm i -g @continuedev/cli
- name: Start remote session
if: steps.check-mention.outputs.contains_mention == 'true'
id: remote-session
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
run: |
# Create a temporary file for the prompt to handle special characters and newlines properly
cat > /tmp/prompt.txt << 'PROMPT_EOF'
Please help with the following request from @${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}:
${{ github.event.comment.body }}
Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch.
PROMPT_EOF
# Debug output
echo "PROMPT content:"
cat /tmp/prompt.txt
# Start remote session and capture JSON output
echo "Starting cn with prompt..."
SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --config continuedev/address-code-review --branch ${{ steps.pr-info.outputs.head_ref }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output
SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
echo "Failed to extract session URL from output: $SESSION_OUTPUT"
exit 1
fi
echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
echo "✅ Started remote session: $SESSION_URL"
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v8
env:
ORIGINAL_COMMENT: ${{ github.event.comment.body }}
with:
script: |
const sessionUrl = '${{ steps.remote-session.outputs.session_url }}';
const originalComment = process.env.ORIGINAL_COMMENT;
const commentBody = "I've started [a remote session](" + sessionUrl + ") to help with your request:\n> " + originalComment;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: commentBody
});
- name: Log session details
if: steps.check-mention.outputs.contains_mention == 'true'
run: |
echo "✅ Successfully started remote session for comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}"
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
echo "Original comment:"
cat /tmp/comment.txt
respond-to-review-comment:
# Only run on pull request review comments
if: github.event_name == 'pull_request_review_comment'
runs-on: ubuntu-latest
steps:
- name: Check if comment contains @continuedev
id: check-mention
run: |
# Create a temporary file to safely handle comment body with special characters
cat > /tmp/review_comment.txt << 'COMMENT_EOF'
${{ github.event.comment.body }}
COMMENT_EOF
if grep -q "@continuedev" /tmp/review_comment.txt; then
echo "contains_mention=true" >> $GITHUB_OUTPUT
else
echo "contains_mention=false" >> $GITHUB_OUTPUT
fi
- name: Add eyes reaction to comment
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/github-script@v8
with:
script: |
await github.rest.reactions.createForPullRequestReviewComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: ${{ github.event.comment.id }},
content: 'eyes'
});
- name: Checkout PR branch
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/checkout@v5
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
ref: ${{ github.event.pull_request.head.ref }}
- name: Setup Node.js
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/setup-node@v5
with:
node-version: "20"
- name: Install Continue CLI globally
if: steps.check-mention.outputs.contains_mention == 'true'
run: npm i -g @continuedev/cli
- name: Get review context
if: steps.check-mention.outputs.contains_mention == 'true'
id: review-context
uses: actions/github-script@v8
with:
script: |
let reviewContext = '';
// Check if this comment is a reply to another review comment
if (context.payload.comment.in_reply_to_id) {
try {
const { data: originalComment } = await github.rest.pulls.getReviewComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.in_reply_to_id
});
reviewContext = `**Original review comment by @${originalComment.user.login}:**
${originalComment.body}
**Reply by @${{ github.event.comment.user.login }}:**
${{ github.event.comment.body }}`;
} catch (error) {
console.log('Could not fetch original comment, using current comment only');
reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:**
${{ github.event.comment.body }}`;
}
} else {
reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:**
${{ github.event.comment.body }}`;
}
core.setOutput('context', reviewContext);
- name: Start remote session
if: steps.check-mention.outputs.contains_mention == 'true'
id: remote-session
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
run: |
# Debug: Echo the branch we're starting the session on
echo "Starting remote session on branch: ${{ github.event.pull_request.head.ref }}"
# Create a temporary file for the prompt to handle special characters and newlines properly
cat > /tmp/prompt.txt << 'PROMPT_EOF'
Please help with the following code review discussion from PR #${{ github.event.pull_request.number }}:
**File:** ${{ github.event.comment.path }}
**Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }}
${{ steps.review-context.outputs.context }}
Please analyze the specific file and line mentioned, understand the review feedback and any discussion context, implement the necessary changes, and commit them to this branch.
PROMPT_EOF
# Debug output
echo "PROMPT content:"
cat /tmp/prompt.txt
# Start remote session and capture JSON output
echo "Starting cn with prompt..."
SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --config continuedev/address-code-review --branch ${{ github.event.pull_request.head.ref }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output
SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
echo "Failed to extract session URL from output: $SESSION_OUTPUT"
exit 1
fi
echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
echo "✅ Started remote session: $SESSION_URL"
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v8
env:
ORIGINAL_COMMENT: ${{ github.event.comment.body }}
with:
script: |
const sessionUrl = '${{ steps.remote-session.outputs.session_url }}';
const originalComment = process.env.ORIGINAL_COMMENT;
const commentBody = "I've started [a remote session](" + sessionUrl + ") to help with your request:\n> " + originalComment;
const commentParams = {
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: ${{ github.event.pull_request.number }},
body: commentBody,
commit_id: '${{ github.event.pull_request.head.sha }}',
path: '${{ github.event.comment.path }}',
in_reply_to: ${{ github.event.comment.id }}
};
await github.rest.pulls.createReviewComment(commentParams);
- name: Log session details
if: steps.check-mention.outputs.contains_mention == 'true'
run: |
echo "✅ Successfully started remote session for review comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}"
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
echo "File: ${{ github.event.comment.path }}"
echo "Line: ${{ github.event.comment.line }}"
echo "Original comment:"
cat /tmp/review_comment.txt

View file

@ -59,7 +59,7 @@ jobs:
uses: ./.github/actions/setup-packages
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version-file: ".nvmrc"

View file

@ -0,0 +1,41 @@
name: Run Continue Agent
on:
workflow_call:
inputs:
prompt:
description: "The prompt to send to the Continue agent"
required: true
type: string
config:
description: "The config to use (e.g., continuedev/default-background-agent)"
required: false
type: string
default: "continuedev/default-background-agent"
branch_name:
description: "The base branch name to work from"
required: false
type: string
default: "main"
secrets:
CONTINUE_API_KEY:
required: true
jobs:
run-agent:
runs-on: ubuntu-latest
steps:
- name: Call agents endpoint
run: |
response=$(curl -f -X POST https://api.continue.dev/agents \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${{ secrets.CONTINUE_API_KEY }}" \
-d '{
"prompt": "${{ inputs.prompt }}",
"config": "${{ inputs.config }}",
"branchName": "${{ inputs.branch_name }}",
"repoUrl": "https://github.com/${{ github.repository }}"
}')
id=$(echo $response | jq -r '.id')
echo "https://hub.continue.dev/agents/$id"

View file

@ -0,0 +1,8 @@
{
"name": "cn",
"system_setup_commands": [
"npm i -g @continuedev/cli@latest",
"sudo apt update",
"sudo apt install -y ripgrep"
]
}

31
.github/workflows/snyk-agent.yaml vendored Normal file
View file

@ -0,0 +1,31 @@
name: Daily Snyk Agent
on:
schedule:
# Runs at 9:00 AM UTC every day
- cron: "0 9 * * *"
workflow_dispatch: # Allows manual triggering
jobs:
run-cn-task:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v5
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: "20"
- name: Install Continue CLI globally
run: npm install -g @continuedev/cli@latest
- name: Run Snyk Agent
run: cd extensions/cli && cn -p --agent continuedev/snyk-code-scan-agent "The current directory"
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}

View file

@ -40,7 +40,7 @@ jobs:
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version: 20
registry-url: "https://registry.npmjs.org"
@ -208,7 +208,7 @@ jobs:
# Create GitHub release
gh release create "v${{ steps.final_version.outputs.stable_version }}" \
--title "Stable Release v${{ steps.final_version.outputs.stable_version }}" \
--title "CLI Stable Release v${{ steps.final_version.outputs.stable_version }}" \
--notes "${{ steps.final_version.outputs.release_notes }}" \
--latest
@ -220,3 +220,40 @@ jobs:
# 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 }}."
- name: Publish Blueprint to Runloop
env:
RUNLOOP_API_KEY: ${{ secrets.RUNLOOP_API_KEY }}
run: |
echo "Publishing blueprint 'cn' to Runloop API for version ${{ steps.final_version.outputs.stable_version }}"
# Use blueprint configuration from template file
cp .github/workflows/runloop-blueprint-template.json blueprint.json
# Publish to Runloop API
response=$(curl -X POST "https://api.runloop.ai/v1/blueprints" \
-H "Authorization: Bearer $RUNLOOP_API_KEY" \
-H "Content-Type: application/json" \
-d @blueprint.json \
-w "%{http_code}" \
-s)
http_code=$(echo "$response" | tail -c 4)
response_body=$(echo "$response" | head -c -4)
if [[ "$http_code" == "200" ]] || [[ "$http_code" == "201" ]]; then
echo "✅ Successfully published blueprint to Runloop API"
echo "Response: $response_body"
# Extract blueprint ID if available
blueprint_id=$(echo "$response_body" | jq -r '.id // empty')
if [[ -n "$blueprint_id" ]]; then
echo "Blueprint ID: $blueprint_id"
echo "blueprint_id=$blueprint_id" >> $GITHUB_OUTPUT
fi
else
echo "❌ Failed to publish blueprint to Runloop API"
echo "HTTP Code: $http_code"
echo "Response: $response_body"
exit 1
fi

View file

@ -19,7 +19,7 @@ jobs:
distribution: "temurin"
java-version: 17
- name: Generate and submit dependency graph
uses: gradle/actions/dependency-submission@v4
uses: gradle/actions/dependency-submission@v5
with:
# The gradle project is not in the root of the repository.
build-root-directory: extensions/intellij

17
.github/workflows/tidy-up-codebase.yml vendored Normal file
View file

@ -0,0 +1,17 @@
name: Weekly CN Task
on:
schedule:
# Runs at 8/9:30 AM PST (16:30 UTC) every Monday so PR shows up at beginning of week
- cron: "30 16 * * 1"
workflow_dispatch: # Allows manual triggering
jobs:
run-cn-task:
uses: ./.github/workflows/run-continue-agent.yml
with:
prompt: "Review every Markdown documentation file and verify that descriptions, examples, or behavior outlines accurately reflect the current code. Only update documentation; do not modify code. Check the corresponding code to confirm behavior before making changes. Correct any inaccuracies or outdated information in descriptions, examples, or behavior outlines. Preserve existing Markdown formatting, style, and structure. Do not add new sections, speculative explanations, or details not present in the code. Only update statements that are clearly incorrect or misleading; do not rewrite text for style or preference. Keep edits minimal and focused, ensuring that the Markdown matches what the code actually does. If verification against the code is ambiguous, leave the documentation unchanged. Use branch name bot/cleanup-<YYMMDD>-<HHMM>"
config: continuedev/default-background-agent
branch_name: main
secrets:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}

231
.github/workflows/vscode-prerelease.yml vendored Normal file
View file

@ -0,0 +1,231 @@
name: VSCode Pre-release
on:
workflow_dispatch:
inputs:
main_commit_sha:
description: "Main branch commit SHA to create pre-release from - leave empty to use HEAD of main"
required: false
type: string
prerelease_version:
description: "New pre-release version (e.g., 1.3.15) - leave empty to auto-increment"
required: false
type: string
permissions:
contents: write
pull-requests: write
jobs:
create-prerelease:
name: Create VSCode Pre-release
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v5
with:
ref: ${{ inputs.main_commit_sha || 'main' }}
fetch-depth: 0
token: ${{ secrets.GITHUB_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: 20
- name: Determine version numbers
id: version
working-directory: extensions/vscode
run: |
# Get current version from package.json
CURRENT_VERSION=$(node -p "require('./package.json').version")
echo "Current version in package.json: $CURRENT_VERSION"
# Determine new pre-release version
if [[ -n "${{ inputs.prerelease_version }}" ]]; then
NEW_VERSION="${{ inputs.prerelease_version }}"
echo "Using manually specified new version: $NEW_VERSION"
else
# Auto-increment patch version
IFS='.' read -r major minor patch <<< "$CURRENT_VERSION"
NEW_PATCH=$((patch + 1))
NEW_VERSION="${major}.${minor}.${NEW_PATCH}"
echo "Auto-incremented version: $NEW_VERSION"
fi
TAG_NAME="v${NEW_VERSION}-vscode"
echo "previous_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT
echo "new_version=$NEW_VERSION" >> $GITHUB_OUTPUT
echo "tag_name=$TAG_NAME" >> $GITHUB_OUTPUT
echo "Summary:"
echo " Previous version: $CURRENT_VERSION"
echo " New version: $NEW_VERSION"
echo " Tag name: $TAG_NAME"
- name: Create pre-release branch
id: branch
run: |
BRANCH_NAME="prerelease/vscode-${{ steps.version.outputs.new_version }}"
echo "branch_name=$BRANCH_NAME" >> $GITHUB_OUTPUT
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git checkout -b "$BRANCH_NAME"
echo "Created branch: $BRANCH_NAME"
- name: Update package.json version
working-directory: extensions/vscode
run: |
# Update version in package.json
npm version ${{ steps.version.outputs.new_version }} --no-git-tag-version
echo "Updated package.json to version ${{ steps.version.outputs.new_version }}"
- name: Commit version bump
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git add extensions/vscode/package.json
git commit -m "chore: bump VSCode extension version to ${{ steps.version.outputs.new_version }}"
echo "Committed version bump"
- name: Push branch and create PR
id: pr
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
git push origin "${{ steps.branch.outputs.branch_name }}"
echo "Pushed branch: ${{ steps.branch.outputs.branch_name }}"
# Create pull request
PR_URL=$(gh pr create \
--base main \
--head "${{ steps.branch.outputs.branch_name }}" \
--title "chore: VSCode pre-release ${{ steps.version.outputs.new_version }}" \
--body "$(cat <<'EOF'
## VSCode Pre-release ${{ steps.version.outputs.new_version }}
This PR bumps the VSCode extension version for pre-release.
### Changes
- Version bumped from ${{ steps.version.outputs.previous_version }} to ${{ steps.version.outputs.new_version }}
- Based on commit: ${{ inputs.main_commit_sha }}
### Release Process
After merging this PR:
1. The tag \`${{ steps.version.outputs.tag_name }}\` will be created automatically
2. A GitHub pre-release will be created with auto-generated release notes
🤖 This PR was created automatically by the VSCode Pre-release workflow.
EOF
)")
echo "pr_url=$PR_URL" >> $GITHUB_OUTPUT
echo "Created PR: $PR_URL"
- name: Auto-merge PR
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
# Get PR number from URL
PR_NUMBER=$(echo "${{ steps.pr.outputs.pr_url }}" | grep -oE '[0-9]+$')
# Merge the PR
gh pr merge "$PR_NUMBER" --squash --auto
echo "PR #$PR_NUMBER set to auto-merge"
# Wait for merge to complete (with timeout)
echo "Waiting for PR to be merged..."
TIMEOUT=300 # 5 minutes
ELAPSED=0
INTERVAL=10
while [ $ELAPSED -lt $TIMEOUT ]; do
PR_STATE=$(gh pr view "$PR_NUMBER" --json state --jq '.state')
if [ "$PR_STATE" = "MERGED" ]; then
echo "PR successfully merged!"
break
fi
sleep $INTERVAL
ELAPSED=$((ELAPSED + INTERVAL))
echo "Still waiting... ($ELAPSED seconds elapsed)"
done
if [ $ELAPSED -ge $TIMEOUT ]; then
echo "Warning: Timed out waiting for PR merge. Please check manually." && exit 1
fi
- name: Checkout main branch
run: |
git fetch origin main
git checkout main
git pull origin main
- name: Create and push tag
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
git tag "${{ steps.version.outputs.tag_name }}"
git push origin "${{ steps.version.outputs.tag_name }}"
echo "Created and pushed tag: ${{ steps.version.outputs.tag_name }}"
- name: Get previous tag for release notes
id: prev_tag
run: |
# Find the previous vscode pre-release tag
PREV_TAG=$(git tag -l "v*-vscode" --sort=-version:refname | head -n 2 | tail -n 1)
if [ -z "$PREV_TAG" ]; then
echo "No previous tag found, using first commit"
PREV_TAG=$(git rev-list --max-parents=0 HEAD)
fi
echo "prev_tag=$PREV_TAG" >> $GITHUB_OUTPUT
echo "Previous tag for release notes: $PREV_TAG"
- name: Create GitHub pre-release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
# Generate release notes between previous tag and current tag
RELEASE_NOTES=$(gh api \
--method POST \
-H "Accept: application/vnd.github+json" \
/repos/${{ github.repository }}/releases/generate-notes \
-f tag_name="${{ steps.version.outputs.tag_name }}" \
-f target_commitish="main" \
-f previous_tag_name="${{ steps.prev_tag.outputs.prev_tag }}" \
--jq '.body')
# Create the pre-release
gh release create "${{ steps.version.outputs.tag_name }}" \
--title "VSCode Pre-release ${{ steps.version.outputs.new_version }}" \
--notes "$RELEASE_NOTES" \
--prerelease \
--target main
echo "Created pre-release: ${{ steps.version.outputs.tag_name }}"
- name: Summary
run: |
echo "## VSCode Pre-release Created Successfully! 🚀" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### Version Information" >> $GITHUB_STEP_SUMMARY
echo "- **Previous Version:** ${{ steps.version.outputs.previous_version }}" >> $GITHUB_STEP_SUMMARY
echo "- **New Version:** ${{ steps.version.outputs.new_version }}" >> $GITHUB_STEP_SUMMARY
echo "- **Tag:** \`${{ steps.version.outputs.tag_name }}\`" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### Links" >> $GITHUB_STEP_SUMMARY
echo "- **PR:** ${{ steps.pr.outputs.pr_url }}" >> $GITHUB_STEP_SUMMARY
echo "- **Release:** https://github.com/${{ github.repository }}/releases/tag/${{ steps.version.outputs.tag_name }}" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### Commit" >> $GITHUB_STEP_SUMMARY
echo "- **Base Commit:** \`${{ inputs.main_commit_sha }}\`" >> $GITHUB_STEP_SUMMARY

View file

@ -21,7 +21,7 @@ jobs:
gh auth login --with-token <<< "${{ github.token }}"
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v5
uses: actions/setup-node@v6
with:
node-version-file: ".nvmrc"

5
.gitignore vendored
View file

@ -172,4 +172,7 @@ extensions/.continue-debug/
.continuerules
**/.continue/assistants/
**/.continue/agents/
keys
keys
.channels_cache.json
.users_cache.json

1
.husky/pre-commit Normal file
View file

@ -0,0 +1 @@
npx lint-staged

View file

@ -4,19 +4,25 @@ binary/out
binary/tmp
core/.continue-test
docs/.docusaurus
docs/**/*.mdx
extensions/.continue-debug
extensions/vscode/continue_rc_schema.json
extensions/vscode/.vscode-test
extensions/vscode/bin
extensions/vscode/build
extensions/vscode/out
extensions/vscode/textmate-syntaxes
extensions/vscode/gui
extensions/vscode/e2e/.test-extensions
extensions/vscode/e2e/test-continue
extensions/vscode/e2e/_output
extensions/vscode/e2e/storage
extensions/vscode/e2e/vsix
extensions/vscode/models
extensions/intellij/src/main/resources
gui/dist
**/.continueignore
.continue/rules/mintlify-formatting.md
CHANGELOG.md
**/continue_tutorial.py
**/node_modules
@ -24,4 +30,5 @@ CHANGELOG.md
core/vendor
coverage
# e2e
packages/continue-sdk
packages/continue-sdk
.conductor

41
.vscode/launch.json vendored
View file

@ -136,8 +136,9 @@
"name": "Debug CLI",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/extensions/cli/src/index.ts",
"program": "${workspaceFolder}/extensions/cli/dist/cn.js",
"args": [],
"runtimeArgs": ["--enable-source-maps"],
"env": {
"NODE_ENV": "development"
// "CONTINUE_API_BASE": "http://localhost:3001/",
@ -147,14 +148,48 @@
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"skipFiles": ["<node_internals>/**"],
"runtimeArgs": ["--loader", "ts-node/esm"],
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/extensions/cli/dist/**/*.js"],
"sourceMapPathOverrides": {
"../src/*": "${workspaceFolder}/extensions/cli/src/*",
"../../core/*": "${workspaceFolder}/core/*"
},
"resolveSourceMapLocations": [
"${workspaceFolder}/**",
"!**/node_modules/**"
],
"preLaunchTask": "cli:build-and-watch-logs",
"cwd": "${workspaceFolder}/extensions/cli"
"cwd": "${workspaceFolder}/manual-testing-sandbox"
},
{
"name": "Debug CLI - AWS Bedrock",
"type": "node",
"request": "launch",
"program": "${workspaceFolder}/extensions/cli/dist/cn.js",
"args": [],
"runtimeArgs": ["--enable-source-maps"],
"env": {
"NODE_ENV": "development",
"CONTINUE_USE_BEDROCK": "1"
// "CONTINUE_API_BASE": "http://localhost:3001/",
// "WORKOS_CLIENT_ID": "client_01J0FW6XCPMJMQ3CG51RB4HBZQ",
// "HUB_URL": "http://localhost:3000"
},
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"skipFiles": ["<node_internals>/**"],
"sourceMaps": true,
"outFiles": ["${workspaceFolder}/extensions/cli/dist/**/*.js"],
"sourceMapPathOverrides": {
"../src/*": "${workspaceFolder}/extensions/cli/src/*",
"../../core/*": "${workspaceFolder}/core/*"
},
"resolveSourceMapLocations": [
"${workspaceFolder}/**",
"!**/node_modules/**"
],
"preLaunchTask": "cli:build-and-watch-logs",
"cwd": "${workspaceFolder}/manual-testing-sandbox"
},
{
"name": "Debug CLI Tests",

View file

@ -23,6 +23,7 @@
"binary/build/**": true,
"binary/out/**": true,
"binary/tmp/**": true,
"core/dist/**": true,
"core/edit/lazy/test-examples/**": true,
"core/llm/llamaTokenizer.js": true,
"core/llm/llamaTokenizer.mjs": true,

2
.vscode/tasks.json vendored
View file

@ -108,7 +108,7 @@
"label": "vscode-extension:continue-ui:build",
"type": "shell",
"command": "node",
"args": ["${workspaceFolder}/extensions/vscode/scripts/prepackage.js"],
"args": ["scripts/prepackage.js"],
"problemMatcher": ["$tsc"],
"presentation": {
"group": "build-tasks",

View file

@ -252,7 +252,7 @@ add it with the following steps:
3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array
in [core/llm/autodetect.ts](./core/llm/autodetect.ts).
4. Add a documentation page for your provider in [
`docs/docs/customize/model-providers/more`](./docs/docs/customize/model-providers/more). This should show an example
`docs/customize/model-providers/more`](./docs/customize/model-providers/more). This should show an example
of configuring your provider in `config.yaml` and explain what options are available.
### Adding Models

View file

@ -27,35 +27,29 @@
**Ship faster with Continuous AI**
**Build and run custom agents across your IDE, terminal, and CI**
**The future of coding isn't writing more code. It's delegating the boring parts, so you can build the interesting stuff**
</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)
Get started in [Mission Control](https://hub.continue.dev/agents), [CLI (Headless Mode)](https://docs.continue.dev/cli/quick-start#headless-mode), or [CLI (TUI mode)](https://docs.continue.dev/cli/quick-start#tui-mode)
## Agent
## Background Agents
[Agent](https://docs.continue.dev/features/agent/quick-start) to work on development tasks together with AI
Set workflows to run automatically on [PR opens](https://docs.continue.dev/guides/continuous-ai#pattern-2-the-pr-review-agent), [schedules](https://docs.continue.dev/guides/continuous-ai#pattern-1-the-async-triage-bot), or [any event trigger](https://docs.continue.dev/cli/quick-start#headless-mode)
![agent](docs/images/agent.gif)
![Background Agents](docs/images/background-agent.gif)
## Chat
## CLI Agents
[Chat](https://docs.continue.dev/features/chat/quick-start) to ask general questions and clarify code sections
Watch workflows execute in real-time and approve decisions step-by-step from your [terminal](https://docs.continue.dev/cli/quick-start#tui-mode)
![chat](docs/images/chat.gif)
![CLI Agents](docs/images/cli-agent.gif)
## Edit
## IDE Agents
[Edit](https://docs.continue.dev/features/edit/quick-start) to modify a code section without leaving your current file
Trigger workflows from [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)—let agents handle the refactoring while you keep coding
![edit](docs/images/edit.gif)
## Autocomplete
[Autocomplete](https://docs.continue.dev/features/autocomplete/quick-start) to receive inline code suggestions as you type
![autocomplete](docs/images/autocomplete.gif)
![IDE Agents](docs/images/agent.gif)
</div>

View file

@ -4,64 +4,19 @@ GitHub Actions that provide automated code reviews for pull requests using Conti
## Available Actions
This repository provides two GitHub Actions for different review styles:
This repository provides a GitHub Action for automated PR reviews:
### 1. General Review Action
### 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`
- **Path:** `continuedev/continue/actions/general-review@main`
- **Trigger:** `@continue-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
### Setting up General Review
```yaml
name: PR General Review
@ -81,34 +36,7 @@ jobs:
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>
- uses: continuedev/continue/actions/general-review@main
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "your-org-name"
@ -117,7 +45,7 @@ jobs:
## Inputs
Both actions accept the same inputs:
The action accepts the following inputs:
| Input | Description | Required |
| ------------------ | -------------------------------------- | -------- |
@ -155,7 +83,7 @@ The workflow requires these permissions:
## Triggering Reviews
Both actions can be triggered in two ways:
The action can be triggered in two ways:
### Automatic Triggers
@ -166,12 +94,9 @@ Both actions can be triggered in two ways:
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
- `@continue-review` - Triggers a review
## Review Outputs
### General Review Output
## Review Output
The general review provides a structured comment that includes:
@ -180,46 +105,24 @@ The general review provides a structured comment that includes:
- **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:
We recommend using the main branch:
- `@<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
- `@main` - Uses the latest code from the main branch
Example:
```yaml
uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe
uses: continuedev/continue/actions/general-review@main
```
## Troubleshooting
@ -236,12 +139,6 @@ uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1
- 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:

View file

@ -1,434 +0,0 @@
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.30
- 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
# Validate API key
if [ -z "$CONTINUE_API_KEY" ]; then
echo "Warning: CONTINUE_API_KEY environment variable is not set"
# Create fallback review and continue
cat > inline_review.json << 'EOF'
{
"review_summary": "AI review skipped: CONTINUE_API_KEY not configured.",
"comments": []
}
EOF
echo "SKIP_CLI=true" >> $GITHUB_ENV
else
echo "SKIP_CLI=false" >> $GITHUB_ENV
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 ====="
# Test Continue CLI availability
if [ "$SKIP_CLI" != "true" ]; then
echo "Testing Continue CLI..."
if ! cn --version; then
echo "Warning: Continue CLI not found or not working"
cat > inline_review.json << 'EOF'
{
"review_summary": "AI review skipped: Continue CLI installation failed.",
"comments": []
}
EOF
echo "SKIP_CLI=true" >> $GITHUB_ENV
else
echo "Continue CLI version: $(cn --version)"
fi
fi
# Run the CLI and capture JSON output with error handling
if [ "$SKIP_CLI" != "true" ]; then
echo "Executing Continue CLI with config: ${{ inputs.continue-org }}/${{ inputs.continue-config }}"
# Write prompt to temp file for better handling
PROMPT_FILE="/tmp/continue-prompt-$.txt"
cp inline_review_prompt.txt "$PROMPT_FILE"
# Use timeout to prevent hanging (240 seconds = 4 minutes)
if ! timeout 240 cn --config "${{ inputs.continue-org }}/${{ inputs.continue-config }}" -p "@$PROMPT_FILE" --allow Bash --format json > inline_review_raw.json 2>cli_error.log; then
echo "Warning: Continue CLI command failed"
echo "CLI error log:"
cat cli_error.log
# Create fallback review
cat > inline_review.json << 'EOF'
{
"review_summary": "AI review failed due to service initialization issues. Please check the Continue API key and configuration.",
"comments": []
}
EOF
echo "Created fallback review due to CLI failure"
else
# 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 "Warning: Invalid JSON output from Continue CLI, using fallback"
cat > inline_review.json << 'EOF'
{
"review_summary": "AI review completed but failed to parse output correctly.",
"comments": []
}
EOF
else
# Use the JSON output directly
cp inline_review_raw.json inline_review.json
echo "Review output:"
cat inline_review.json
fi
fi
fi
- 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

@ -1,96 +0,0 @@
#!/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

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

@ -1,19 +0,0 @@
{
"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

@ -9,8 +9,8 @@ inputs:
continue-org:
description: "Organization for Continue config"
required: true
continue-config:
description: 'Config path to use (e.g., "myorg/review-bot")'
continue-agent:
description: 'Agent path to use (e.g., "myorg/review-bot")'
required: true
runs:
@ -20,44 +20,89 @@ runs:
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"
id: auth-check
uses: actions/github-script@v7
with:
script: |
let shouldRun = false;
let skipReason = '';
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
if (context.eventName === 'pull_request') {
// Check if PR is a draft
if (context.payload.pull_request.draft) {
skipReason = 'PR is a draft';
} else {
// Check if user has write permission (includes admin, maintain, write)
const prAuthor = context.payload.pull_request.user.login;
try {
const { data: permission } = await github.rest.repos.getCollaboratorPermissionLevel({
owner: context.repo.owner,
repo: context.repo.repo,
username: prAuthor
});
const allowedPermissions = ['admin', 'maintain', 'write'];
if (allowedPermissions.includes(permission.permission)) {
shouldRun = true;
console.log(`PR author @${prAuthor} has ${permission.permission} permission`);
} else {
skipReason = `PR author @${prAuthor} does not have write permission (has: ${permission.permission})`;
}
} catch (error) {
// If API call fails, fall back to checking author_association
const association = context.payload.pull_request.author_association;
const allowedAssociations = ['OWNER', 'MEMBER', 'COLLABORATOR'];
if (allowedAssociations.includes(association)) {
shouldRun = true;
console.log(`PR author @${prAuthor} association: ${association}`);
} else {
skipReason = `PR author @${prAuthor} is not a team member (association: ${association})`;
}
}
}
} else if (context.eventName === 'issue_comment') {
// Check if it's a PR comment with the trigger phrase
const hasTrigger = context.payload.comment.body.includes('@continue-review');
if (context.payload.issue.pull_request && hasTrigger) {
const commenter = context.payload.comment.user.login;
try {
const { data: permission } = await github.rest.repos.getCollaboratorPermissionLevel({
owner: context.repo.owner,
repo: context.repo.repo,
username: commenter
});
const allowedPermissions = ['admin', 'maintain', 'write'];
if (allowedPermissions.includes(permission.permission)) {
shouldRun = true;
console.log(`Commenter @${commenter} has ${permission.permission} permission`);
} else {
skipReason = `Commenter @${commenter} does not have write permission (has: ${permission.permission})`;
}
} catch (error) {
// If API call fails, fall back to checking author_association
const association = context.payload.comment.author_association;
const allowedAssociations = ['OWNER', 'MEMBER', 'COLLABORATOR'];
if (allowedAssociations.includes(association)) {
shouldRun = true;
console.log(`Commenter @${commenter} association: ${association}`);
} else {
skipReason = `Commenter @${commenter} is not a team member (association: ${association})`;
}
}
} else {
skipReason = 'Comment does not contain @continue-review trigger, or is not on a PR';
}
} else {
skipReason = `Unsupported event type: ${context.eventName}`;
}
echo "SHOULD_RUN=$SHOULD_RUN" >> $GITHUB_ENV
if (skipReason) {
core.notice(`Skipping review - ${skipReason}`);
}
core.exportVariable('SHOULD_RUN', shouldRun.toString());
return shouldRun;
- name: Setup Node.js
if: env.SHOULD_RUN == 'true'
@ -68,13 +113,138 @@ runs:
- name: Install Continue CLI
if: env.SHOULD_RUN == 'true'
shell: bash
run: npm install -g @continuedev/cli@1.4.30
run: npm install -g @continuedev/cli@latest
- name: Setup Action Scripts
if: env.SHOULD_RUN == 'true'
shell: bash
run: |
# Create directory for scripts
mkdir -p .continue-action-scripts
# Check if we're running in the Continue repo itself (scripts exist locally)
if [ -f "actions/general-review/scripts/buildPrompt.js" ] && [ -f "actions/general-review/scripts/writeMarkdown.js" ]; then
echo "Running in Continue repo - using local scripts from current checkout"
cp actions/general-review/scripts/buildPrompt.js .continue-action-scripts/buildPrompt.js
cp actions/general-review/scripts/writeMarkdown.js .continue-action-scripts/writeMarkdown.js
else
echo "Running in external repo - downloading scripts from Continue repo"
# Download scripts from Continue repo
echo "Downloading buildPrompt.js..."
curl -sSL https://raw.githubusercontent.com/continuedev/continue/main/actions/general-review/scripts/buildPrompt.js \
-o .continue-action-scripts/buildPrompt.js
echo "Downloading writeMarkdown.js..."
curl -sSL https://raw.githubusercontent.com/continuedev/continue/main/actions/general-review/scripts/writeMarkdown.js \
-o .continue-action-scripts/writeMarkdown.js
fi
# Verify scripts exist
if [ ! -f .continue-action-scripts/buildPrompt.js ]; then
echo "Error: buildPrompt.js not found"
exit 1
fi
if [ ! -f .continue-action-scripts/writeMarkdown.js ]; then
echo "Error: writeMarkdown.js not found"
exit 1
fi
echo "Scripts ready:"
ls -lh .continue-action-scripts/
- name: Post Initial Comment
if: env.SHOULD_RUN == 'true'
id: initial-comment
uses: actions/github-script@v7
with:
script: |
const marker = '<!-- continue-agent-review -->';
// 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;
}
// Check for existing comment
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
per_page: 100
});
// Find existing Continue review comment
const existingComment = comments
.filter(c => c.body && c.body.includes(marker))
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0];
// Get workflow run URL
const workflowRunUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
// Create initial "review in progress" message
let initialMessage = `${marker}\n**🔄 Review In Progress**\n\n`;
if (context.eventName === 'issue_comment') {
initialMessage = `${marker}\n**🔄 Review In Progress**\n\n*Triggered by @${context.payload.comment.user.login}'s request*\n\n`;
}
initialMessage += `Continue AI is analyzing the code changes...\n\n`;
initialMessage += `📊 **Review Scope:**\n`;
initialMessage += `- Repository: ${context.repo.owner}/${context.repo.repo}\n`;
initialMessage += `- PR #${prNumber}\n\n`;
initialMessage += `⏱️ This typically takes 1-2 minutes.\n\n`;
initialMessage += `[View live progress →](${workflowRunUrl})\n\n`;
initialMessage += `---\n<!-- ${new Date().toISOString()} | Powered by Continue (https://continue.dev) -->`;
if (existingComment) {
// Check if comment is less than 1 hour old
const commentAge = Date.now() - new Date(existingComment.created_at).getTime();
const oneHour = 60 * 60 * 1000;
if (commentAge < oneHour) {
// Update existing comment if less than 1 hour old
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: existingComment.id,
body: initialMessage
});
console.log(`Updated existing comment ${existingComment.id} to show review in progress`);
core.setOutput('comment_id', existingComment.id);
} else {
// Create new comment if older than 1 hour (preserve history)
const { data: comment } = await github.rest.issues.createComment({
issue_number: prNumber,
owner: context.repo.owner,
repo: context.repo.repo,
body: initialMessage
});
console.log(`Created new comment ${comment.id} showing review in progress`);
core.setOutput('comment_id', comment.id);
}
} else {
// Create new comment
const { data: comment } = await github.rest.issues.createComment({
issue_number: prNumber,
owner: context.repo.owner,
repo: context.repo.repo,
body: initialMessage
});
console.log(`Created new comment ${comment.id} on PR #${prNumber}`);
core.setOutput('comment_id', comment.id);
}
- name: Build PR Review Prompt
if: env.SHOULD_RUN == 'true'
shell: bash
env:
GH_TOKEN: ${{ github.token }}
GITHUB_TOKEN: ${{ github.token }}
run: |
# Get PR number based on event type
if [ "${{ github.event_name }}" = "pull_request" ]; then
@ -84,64 +254,11 @@ runs:
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
# Gather PR context and build prompt without heredocs
gh pr diff "$PR_NUMBER" > pr_diff.txt
gh pr view "$PR_NUMBER" --json title,author,body,files > pr_data.json
node .continue-action-scripts/buildPrompt.js "$PR_NUMBER"
rm -f pr_data.json
- name: Run Continue CLI Review
if: env.SHOULD_RUN == 'true'
@ -149,11 +266,13 @@ runs:
env:
CONTINUE_API_KEY: ${{ inputs.continue-api-key }}
CONTINUE_ORG: ${{ inputs.continue-org }}
CONTINUE_CONFIG: ${{ inputs.continue-config }}
CONTINUE_AGENT: ${{ inputs.continue-agent }}
GITHUB_TOKEN: ${{ github.token }}
run: |
echo "Running Continue CLI with prompt:"
echo "=================================="
cat review_prompt.txt
head -n 100 review_prompt.txt
echo "... [truncated] ..."
echo "=================================="
echo ""
@ -161,15 +280,7 @@ runs:
if [ -z "$CONTINUE_API_KEY" ]; then
echo "Warning: CONTINUE_API_KEY environment variable is not set"
# Create fallback review and continue
cat > code_review.md << 'EOF'
## Code Review Summary
⚠️ AI review skipped: CONTINUE_API_KEY not configured.
### Configuration Required
- Please set the CONTINUE_API_KEY secret in repository settings
- Verify that the organization and config path are valid
EOF
node .continue-action-scripts/writeMarkdown.js code_review.md missing_api_key
echo "SKIP_CLI=true" >> $GITHUB_ENV
else
echo "SKIP_CLI=false" >> $GITHUB_ENV
@ -181,7 +292,7 @@ runs:
exit 1
fi
if [[ ! "$CONTINUE_CONFIG" =~ ^[a-zA-Z0-9_/-]+$ ]]; then
if [[ ! "$CONTINUE_AGENT" =~ ^[a-zA-Z0-9_/-]+$ ]]; then
echo "Error: Invalid config path. Must contain only alphanumeric characters, hyphens, underscores, and forward slashes."
exit 1
fi
@ -189,51 +300,67 @@ runs:
# Test Continue CLI availability
if [ "$SKIP_CLI" != "true" ]; then
echo "Testing Continue CLI..."
if ! cn --version; then
if ! which cn > /dev/null 2>&1; then
echo "Warning: Continue CLI not found or not working"
cat > code_review.md << 'EOF'
## Code Review Summary
⚠️ AI review skipped: Continue CLI installation failed.
### Troubleshooting
- Check that npm installation succeeded
- Verify @continuedev/cli package is available
EOF
node .continue-action-scripts/writeMarkdown.js code_review.md cli_install_failed
echo "SKIP_CLI=true" >> $GITHUB_ENV
else
echo "Continue CLI version: $(cn --version)"
echo "Continue CLI found at: $(which cn)"
echo "Continue CLI version: $(cn --version 2>/dev/null || echo 'version check failed')"
fi
fi
# Run the CLI with validated config and error handling
if [ "$SKIP_CLI" != "true" ]; then
echo "Executing Continue CLI with config: $CONTINUE_ORG/$CONTINUE_CONFIG"
echo "Executing Continue CLI with config: $CONTINUE_ORG/$CONTINUE_AGENT"
# Write prompt to temp file for better handling
PROMPT_FILE="/tmp/continue-prompt-$.txt"
# Write prompt to temp file for headless mode
PROMPT_FILE="/tmp/continue-review-$RANDOM.txt"
cp review_prompt.txt "$PROMPT_FILE"
echo "Prompt file: $PROMPT_FILE"
echo "Prompt length: $(wc -c < "$PROMPT_FILE") characters"
# Use timeout to prevent hanging (240 seconds = 4 minutes)
if ! timeout 240 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -p "@$PROMPT_FILE" --allow Bash > code_review.md 2>cli_error.log; then
echo "Error: Continue CLI command failed"
echo "CLI error log:"
cat cli_error.log
# Use timeout to prevent hanging (360 seconds = 6 minutes)
echo "Executing command: cn --agent $CONTINUE_ORG/$CONTINUE_AGENT -p @$PROMPT_FILE --allow Bash"
# Create fallback review
cat > code_review.md << 'EOF'
## Code Review Summary
⚠️ AI review failed due to service initialization issues. Please check the Continue API key and configuration.
### Troubleshooting
- Verify the CONTINUE_API_KEY secret is set correctly
- Check that the organization and config path are valid
- Ensure the Continue service is accessible
EOF
if timeout 360 cn --agent "$CONTINUE_ORG/$CONTINUE_AGENT" -p "@$PROMPT_FILE" --allow Bash > code_review_raw.md 2>cli_error.log; then
echo "Continue CLI completed successfully"
echo "Raw output length: $(wc -c < code_review_raw.md) characters"
# Clean up ANSI codes if any
sed 's/\x1b\[[0-9;]*m//g' code_review_raw.md > code_review.md
echo "Cleaned output length: $(wc -c < code_review.md) characters"
echo "First 500 chars of output:"
head -c 500 code_review.md
echo ""
# Check if output is empty
if [ ! -s code_review.md ]; then
echo "Warning: Continue CLI returned empty output"
node .continue-action-scripts/writeMarkdown.js code_review.md empty_output
fi
else
echo "Error: Continue CLI command failed with exit code $?"
echo "CLI error log:"
cat cli_error.log
# Check for specific error patterns
if grep -q "not found\|ENOENT" cli_error.log 2>/dev/null; then
node .continue-action-scripts/writeMarkdown.js code_review.md cli_not_found
elif grep -q "config\|assistant" cli_error.log 2>/dev/null; then
node .continue-action-scripts/writeMarkdown.js code_review.md config_error
elif grep -q "api\|auth" cli_error.log 2>/dev/null; then
node .continue-action-scripts/writeMarkdown.js code_review.md auth_error
else
node .continue-action-scripts/writeMarkdown.js code_review.md generic_failure
fi
fi
# Clean up temp file
rm -f "$PROMPT_FILE"
else
echo "Review generated successfully"
fi
echo "Review generation successfully completed"
fi
- name: Upload Review Results
@ -247,7 +374,7 @@ runs:
pr_diff.txt
retention-days: 30
- name: Comment PR with Review
- name: Update Comment with Review
if: env.SHOULD_RUN == 'true' && always()
uses: actions/github-script@v7
with:
@ -256,13 +383,15 @@ runs:
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.';
// Build direct link to workflow logs
const workflowRunUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
reviewContent = `⚠️ AI review completed but no review output was generated.\n\n**Likely cause:** Expired CONTINUE_API_KEY or missing continuedev/review-bot assistant\n\n[📋 View workflow logs](${workflowRunUrl}) for details.`;
}
// Get PR number based on event type
let prNumber;
if (context.eventName === 'pull_request') {
@ -277,17 +406,115 @@ runs:
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`*';
// Add footer with timestamp and branding
const timestamp = new Date().toISOString();
reviewContent += `\n\n---\n<!-- ${timestamp} | Powered by Continue (https://continue.dev) -->`;
// 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}`);
// Look for existing review comment to update (sticky comment)
const marker = '<!-- continue-agent-review -->';
// Try to get comment_id from the initial comment step
const initialCommentId = '${{ steps.initial-comment.outputs.comment_id }}';
if (initialCommentId && initialCommentId !== '') {
// We have the comment ID from the initial step, use it directly
reviewContent = `${marker}\n**✅ Review Complete**\n\n${reviewContent}`;
try {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: parseInt(initialCommentId),
body: reviewContent
});
console.log(`Updated comment ${initialCommentId} with review results`);
} catch (updateError) {
console.log(`Failed to update comment ${initialCommentId}, will search for it instead:`, updateError.message);
// Fallback: search for the comment
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
per_page: 100
});
// Find existing Continue review comment
const existingComment = comments
.filter(c => c.body && c.body.includes(marker))
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0];
if (existingComment) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: existingComment.id,
body: reviewContent
});
console.log(`Updated existing comment ${existingComment.id} via search`);
} else {
// Create new comment as last resort
await github.rest.issues.createComment({
issue_number: prNumber,
owner: context.repo.owner,
repo: context.repo.repo,
body: reviewContent
});
console.log(`Created new comment on PR #${prNumber} as fallback`);
}
}
} else {
// No initial comment ID, search for existing comment
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: prNumber,
per_page: 100
});
// Find existing Continue review comment
const existingComment = comments
.filter(c => c.body && c.body.includes(marker))
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0];
// Add marker and review status
reviewContent = `${marker}\n**✅ Review Complete**\n\n${reviewContent}`;
if (existingComment) {
// Check if comment is less than 1 hour old
const commentAge = Date.now() - new Date(existingComment.created_at).getTime();
const oneHour = 60 * 60 * 1000;
if (commentAge < oneHour) {
// Update existing comment if less than 1 hour old
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: existingComment.id,
body: reviewContent
});
console.log(`Updated existing comment ${existingComment.id} (${Math.round(commentAge / 1000 / 60)} minutes old)`);
} else {
// Create new comment if older than 1 hour (preserve history)
await github.rest.issues.createComment({
issue_number: prNumber,
owner: context.repo.owner,
repo: context.repo.repo,
body: reviewContent
});
console.log(`Created new comment (existing comment was ${Math.round(commentAge / 1000 / 60)} minutes old)`);
}
} else {
// Create new comment
await github.rest.issues.createComment({
issue_number: prNumber,
owner: context.repo.owner,
repo: context.repo.repo,
body: reviewContent
});
console.log(`Created new comment on PR #${prNumber}`);
}
}
} catch (error) {
console.log('Failed to post comment:', error.message);
console.log('Error details:', error);

View file

@ -0,0 +1,94 @@
const fs = require("fs");
const path = require("path");
function main() {
const prNumber = process.argv[2];
if (!prNumber) {
console.error(
"buildPrompt.js requires the PR number as the first argument",
);
process.exit(1);
}
const prDataPath = path.resolve(process.cwd(), "pr_data.json");
const prDiffPath = path.resolve(process.cwd(), "pr_diff.txt");
const outputPath = path.resolve(process.cwd(), "review_prompt.txt");
if (!fs.existsSync(prDataPath)) {
console.error(`Missing PR metadata file: ${prDataPath}`);
process.exit(1);
}
if (!fs.existsSync(prDiffPath)) {
console.error(`Missing PR diff file: ${prDiffPath}`);
process.exit(1);
}
const repo = process.env.GITHUB_REPOSITORY || "unknown-repo";
let prData;
try {
prData = JSON.parse(fs.readFileSync(prDataPath, "utf8"));
} catch (error) {
console.error("Failed to parse PR metadata JSON:", error);
process.exit(1);
}
const filesChanged = Array.isArray(prData.files) ? prData.files.length : 0;
const authorLogin = prData.author?.login || "unknown-author";
const title = prData.title || "Untitled";
const prBody =
prData.body && prData.body.trim()
? prData.body.trim()
: "No description provided";
const diff = fs.readFileSync(prDiffPath, "utf8");
const promptSections = [
"You are reviewing a pull request. Please provide helpful, context-aware feedback.",
"",
"CONTEXT:",
`- Repository: ${repo}`,
`- PR #${prNumber}: ${title}`,
`- Files Changed: ${filesChanged}`,
`- Author: ${authorLogin}`,
"",
"REVIEW APPROACH:",
"1. First, understand what this PR is trying to accomplish",
"2. Check if similar patterns exist elsewhere in the codebase",
"3. Focus on actual issues that affect functionality",
"4. Be constructive and suggest solutions when possible",
"",
"FOCUS ON:",
"- Bugs that will cause failures or incorrect behavior",
"- Security vulnerabilities (exposed secrets, injection risks)",
"- Breaking changes that affect other parts of the system",
"- Performance issues with real impact (memory leaks, O(n²) algorithms)",
"- Missing tests for new features or bug fixes",
"- Missing documentation for APIs or complex logic",
"",
"SKIP COMMENTING ON:",
"- Style and formatting (handled by linters)",
"- Alternative approaches unless current is broken",
"- Minor naming unless genuinely confusing",
"- Trivial documentation for self-explanatory code",
"",
"Be specific with line numbers and explain why something is an issue.",
"",
`PR Description: ${prBody}`,
"",
"Code Changes:",
diff.trimEnd(),
"",
"Your Review:",
"Please provide constructive feedback on the code changes.",
"Focus on issues that matter for functionality, security, and maintainability.",
"If the code looks good overall, acknowledge that while noting any minor suggestions.",
];
const prompt = `${promptSections.join("\n")}\n`;
fs.writeFileSync(outputPath, prompt, "utf8");
console.log(`Wrote review prompt to ${outputPath}`);
}
main();

View file

@ -0,0 +1,68 @@
const fs = require("fs");
const path = require("path");
const messages = {
missing_api_key: `## Code Review Summary
⚠️ AI review skipped: CONTINUE_API_KEY not configured.
### Configuration Required
- Please set the CONTINUE_API_KEY secret in repository settings
- Verify that the organization and config path are valid
`,
cli_install_failed: `## Code Review Summary
⚠️ AI review skipped: Continue CLI installation failed.
### Troubleshooting
- Check that npm installation succeeded
- Verify @continuedev/cli package is available
`,
empty_output: `## Code Review Summary
⚠️ Continue CLI returned an empty response. Please check the configuration.
`,
cli_not_found: `## Code Review Summary
⚠️ Continue CLI is not properly installed. Please ensure @continuedev/cli is installed globally.
`,
config_error: `## Code Review Summary
⚠️ Continue configuration error. Please verify that the assistant exists in Continue Hub.
`,
auth_error: `## Code Review Summary
⚠️ Continue API authentication failed. Please check your CONTINUE_API_KEY.
`,
generic_failure: `## Code Review Summary
⚠️ AI review failed. Please check the Continue API key and configuration.
### Troubleshooting
- Verify the CONTINUE_API_KEY secret is set correctly
- Check that the organization and config path are valid
- Ensure the Continue service is accessible
`,
};
function main() {
const [outputPath, messageKey] = process.argv.slice(2);
if (!outputPath || !messageKey) {
console.error("Usage: node writeMarkdown.js <outputPath> <messageKey>");
process.exit(1);
}
const message = messages[messageKey];
if (!message) {
console.error(`Unknown message key: ${messageKey}`);
process.exit(1);
}
const absolutePath = path.resolve(process.cwd(), outputPath);
fs.writeFileSync(absolutePath, message, "utf8");
console.log(`Wrote ${messageKey} message to ${absolutePath}`);
}
main();

View file

@ -48,6 +48,7 @@
"version": "1.1.0",
"license": "Apache-2.0",
"dependencies": {
"@anthropic-ai/sdk": "^0.62.0",
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
"@aws-sdk/credential-providers": "^3.778.0",
@ -114,6 +115,7 @@
"system-ca": "^1.0.3",
"tar": "^7.4.3",
"tree-sitter-wasms": "^0.1.11",
"untildify": "^6.0.0",
"uuid": "^9.0.1",
"vectordb": "^0.4.20",
"web-tree-sitter": "^0.21.0",
@ -6674,9 +6676,9 @@
}
},
"node_modules/tar-fs": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz",
"integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==",
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",
"integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==",
"dev": true,
"license": "MIT",
"dependencies": {

View file

@ -11,7 +11,7 @@ const { TARGET_TO_LANCEDB } = require("../utils/targets");
const fs = require("fs");
const {
downloadSqlite,
} = require("../../extensions/vscode/scripts/download-copy-sqlite-esbuild");
} = require("../../extensions/vscode/scripts/download-copy-sqlite");
const { fork } = require("child_process");
async function downloadNodeSqlite(target, targetDir) {

View file

@ -268,6 +268,8 @@ export class CompletionProvider {
gitRepo: await this.ide.getRepoName(helper.filepath),
uniqueId: await this.ide.getUniqueId(),
timestamp: new Date().toISOString(),
profileType:
this.configHandler.currentProfile?.profileDescription.profileType,
...helper.options,
};

View file

@ -1,8 +1,7 @@
import * as fs from "fs/promises";
import path from "path";
import { pathToFileURL } from "url";
import Parser from "web-tree-sitter";
import { IDE, Position } from "../../..";
import { FileType, IDE, Position } from "../../../";
import { localPathOrUriToPath } from "../../../util/pathToUri";
import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter";
import {
@ -353,10 +352,7 @@ export class StaticContextService {
if (foundContents.has(tdLocation.filepath)) {
content = foundContents.get(tdLocation.filepath)!;
} else {
content = await fs.readFile(
localPathOrUriToPath(tdLocation.filepath),
"utf8",
);
content = await this.ide.readFile(tdLocation.filepath);
foundContents.set(tdLocation.filepath, content);
}
@ -854,24 +850,19 @@ export class StaticContextService {
return skipDirs.includes(dirName) || dirName.startsWith(".");
};
async function scanRecursively(currentPath: string): Promise<void> {
const scanRecursively = async (currentPath: string): Promise<void> => {
try {
const entries = await fs.readdir(currentPath, {
withFileTypes: true,
});
const currentUri = pathToFileURL(currentPath).toString();
const entries = await this.ide.listDir(currentUri);
for (const [name, fileType] of entries) {
const fullPath = localPathOrUriToPath(path.join(currentPath, name));
for (const entry of entries) {
const fullPath = localPathOrUriToPath(
path.join(currentPath, entry.name),
);
if (entry.isDirectory()) {
// Skip common directories that typically don't contain source files
if (!shouldSkipDirectory(entry.name)) {
if (fileType === (2 as FileType.Directory)) {
if (!shouldSkipDirectory(name)) {
await scanRecursively(fullPath);
}
} else if (entry.isFile()) {
const extension = path.extname(entry.name).toLowerCase();
} else if (fileType === (1 as FileType.File)) {
const extension = path.extname(name).toLowerCase();
if (tsExtensions.includes(extension)) {
tsFiles.push(fullPath);
}
@ -880,7 +871,7 @@ export class StaticContextService {
} catch (error) {
console.error(`Error reading directory ${currentPath}:`, error);
}
}
};
await scanRecursively(dirPath);
return tsFiles;

View file

@ -0,0 +1,118 @@
import { postprocessCompletion } from "./index";
describe("postprocessCompletion - removeBackticks", () => {
const mockLLM = { model: "test-model" } as any;
it("should remove first line starting with ``` and last line that is ```", () => {
const completion =
"```typescript\nfunction hello() {\n return 'world';\n}\n```";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe("function hello() {\n return 'world';\n}");
});
it("should remove only first line if it starts with ```", () => {
const completion = "```javascript\nconst x = 5;\nconsole.log(x);";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe("const x = 5;\nconsole.log(x);");
});
it("should remove only last line if it is ```", () => {
const completion = "const y = 10;\nconsole.log(y);\n```";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe("const y = 10;\nconsole.log(y);");
});
it("should not modify completion without backticks", () => {
const completion = "function test() {\n return true;\n}";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe("function test() {\n return true;\n}");
});
it("should handle completion with backticks in the middle", () => {
const completion = "const str = `template ${literal}`;\nconsole.log(str);";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe(
"const str = `template ${literal}`;\nconsole.log(str);",
);
});
it("should handle first line with leading whitespace before ```", () => {
const completion = " ```python\ndef hello():\n pass\n```";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe("def hello():\n pass");
});
it("should handle last line with whitespace around ```", () => {
const completion = "```\ncode here\n ``` ";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe("code here");
});
it("should handle single line completion", () => {
const completion = "const x = 5;";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe("const x = 5;");
});
it("should handle empty completion", () => {
const completion = "";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBeUndefined();
});
it("should not remove ``` if it's not on its own line at the end", () => {
const completion = "```typescript\nconst x = 5; // end```";
const result = postprocessCompletion({
completion,
llm: mockLLM,
prefix: "",
suffix: "",
});
expect(result).toBe("const x = 5; // end```");
});
});

View file

@ -52,6 +52,43 @@ function isBlank(completion: string): boolean {
return completion.trim().length === 0;
}
/**
* Removes markdown code block delimiters from completion.
* Removes the first line if it starts with backticks (with optional language name).
* Removes the last line if it contains only backticks.
*/
function removeBackticks(completion: string): string {
const lines = completion.split("\n");
if (lines.length === 0) {
return completion;
}
let startIdx = 0;
let endIdx = lines.length;
// Remove first line if it starts with backticks (``` or ```language)
const firstLineTrimmed = lines[0].trim();
if (firstLineTrimmed.startsWith("```")) {
startIdx = 1;
}
// Remove last line if it contains only backticks (one or more)
if (lines.length > startIdx) {
const lastLineTrimmed = lines[lines.length - 1].trim();
if (lastLineTrimmed.length > 0 && /^`+$/.test(lastLineTrimmed)) {
endIdx = lines.length - 1;
}
}
// If we removed lines, return the modified completion
if (startIdx > 0 || endIdx < lines.length) {
return lines.slice(startIdx, endIdx).join("\n");
}
return completion;
}
export function postprocessCompletion({
completion,
llm,
@ -113,7 +150,7 @@ export function postprocessCompletion({
completion = completion.replace(/^\n+|\n+$/g, "");
}
if (llm.model.includes("mercury") || llm.model.includes("granite")) {
if (llm.model.includes("granite")) {
// Granite tends to repeat the start of the line in the completion output
let prefixEnd = prefix.split("\n").pop();
if (prefixEnd) {
@ -156,5 +193,8 @@ export function postprocessCompletion({
completion = completion.slice(1);
}
// Remove markdown code block delimiters
completion = removeBackticks(completion);
return completion;
}

View file

@ -71,6 +71,21 @@ const qwenCoderFimTemplate: AutocompleteTemplate = {
},
};
// https://www.ibm.com/granite/docs/models/granite#fim
const granite4FimTemplate: AutocompleteTemplate = {
template:
"<|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>",
completionOptions: {
stop: [
"<|end_of_text|>",
"<|fim_prefix|>",
"<|fim_middle|>",
"<|fim_suffix|>",
"<|fim_pad|>",
],
},
};
const seedCoderFimTemplate: AutocompleteTemplate = {
template:
"<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
@ -177,7 +192,7 @@ const mercuryMultifileFimTemplate: AutocompleteTemplate = {
suffix,
];
}
return [`<|fim_prefix|>${prefix}`, suffix];
return [`${prefix}`, suffix];
}
const relativePaths = getShortestUniqueRelativeUriPaths(
@ -442,6 +457,10 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
return qwenCoderFimTemplate;
}
if (lowerCaseModel.includes("granite") && lowerCaseModel.includes("4")) {
return granite4FimTemplate;
}
if (lowerCaseModel.includes("seed") && lowerCaseModel.includes("coder")) {
return seedCoderFimTemplate;
}

View file

@ -119,6 +119,7 @@ export class AutocompleteLoggingService {
time: restOfOutcome.time,
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
numLines: restOfOutcome.numLines,
profileType: restOfOutcome.profileType,
};
outcome.enabledStaticContextualization

View file

@ -43,4 +43,5 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions {
uniqueId: string;
timestamp: string;
enabledStaticContextualization?: boolean;
profileType?: "local" | "platform" | "control-plane";
}

View file

@ -1,99 +1,17 @@
import fs from "fs";
import { homedir } from "node:os";
import { fileURLToPath, pathToFileURL } from "node:url";
import { fileURLToPath } from "node:url";
import path from "path";
import { languageForFilepath } from "../../../autocomplete/constants/AutocompleteLanguageInfo.js";
import { SlashCommand } from "../../../index.js";
import { renderChatMessage } from "../../../util/messageContent.js";
import { getContinueGlobalPath } from "../../../util/paths.js";
// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
function getOffsetDatetime(date: Date): Date {
const offset = date.getTimezoneOffset();
const offsetHours = Math.floor(offset / 60);
const offsetMinutes = offset % 60;
date.setHours(date.getHours() - offsetHours);
date.setMinutes(date.getMinutes() - offsetMinutes);
return date;
}
function asBasicISOString(date: Date): string {
const isoString = date.toISOString();
return isoString.replace(/[-:]|(\.\d+Z)/g, "");
}
function reformatCodeBlocks(msgText: string): string {
const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g;
msgText = msgText.replace(
codeBlockFenceRegex,
(match, metadata, filename, extension) => {
const lang = languageForFilepath(filename);
return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`;
},
);
// Appease the markdown linter
return msgText.replace(/```\n```/g, "```\n\n```");
}
import { shareSession } from "../../../util/historyUtils.js";
const ShareSlashCommand: SlashCommand = {
name: "share",
description: "Export the current chat session to markdown",
run: async function* ({ ide, history, params }) {
const now = new Date();
let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${now.toLocaleString()}`;
// As currently implemented, the /share command is by definition the last
// message in the chat history, this will omit it
for (const msg of history.slice(0, history.length - 1)) {
let msgText = msg.content;
msgText = renderChatMessage(msg);
if (msg.role === "user" && msgText.search("```") > -1) {
msgText = reformatCodeBlocks(msgText);
}
// format messages as blockquotes
msgText = msgText.replace(/^/gm, "> ");
content += `\n\n#### ${
msg.role === "user" ? "_User_" : "_Assistant_"
}\n\n${msgText}`;
}
let outputDir: string = params?.outputDir ?? getContinueGlobalPath();
if (outputDir.startsWith("~")) {
outputDir = outputDir.replace(/^~/, homedir);
} else if (
outputDir.startsWith("./") ||
outputDir.startsWith(".\\") ||
outputDir === "."
) {
const workspaceDirs = await ide.getWorkspaceDirs();
// Although the most common situation is to have one directory open in a
// workspace it's also possible to have just a file open without an
// associated directory or to use multi-root workspaces in which multiple
// folders are included. We default to using the first item in the list, if
// it exists.
const workspaceDirectory = workspaceDirs?.[0] || "";
outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory));
}
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
const dtString = asBasicISOString(getOffsetDatetime(now));
const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming?
const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^
await ide.writeFile(fileUrl, content);
await ide.openFile(fileUrl);
const fileUrl = await shareSession(ide, history, params?.outputDir);
const filePath = fileURLToPath(fileUrl);
// output path is the parent directory of the filePath
const outPath = path.dirname(filePath);
yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`;
},
};

View file

@ -11,6 +11,6 @@ export function convertCustomCommandToSlashCommand(
description: customCommand.description ?? "",
prompt: customCommand.prompt,
source: "json-custom-command",
promptFile: customCommand.sourceFile, // TODO refactor promptFile to align with sourceFile
sourceFile: customCommand.sourceFile,
};
}

View file

@ -9,6 +9,6 @@ export function convertPromptBlockToSlashCommand(
description: prompt.description ?? "",
prompt: prompt.prompt,
source: "yaml-prompt-block",
promptFile: prompt.sourceFile, // Align with the sourceFile property
sourceFile: prompt.sourceFile,
};
}

View file

@ -15,7 +15,7 @@ export function slashCommandFromPromptFile(
description,
prompt,
source: version === 1 ? "prompt-file-v1" : "prompt-file-v2",
promptFile: path,
sourceFile: path,
overrideSystemMessage: systemMessage,
};
}

View file

@ -10,6 +10,7 @@ export function convertRuleBlockToSlashCommand(
description: rule.description ?? "",
prompt: rule.rule,
source: "invokable-rule",
promptFile: rule.ruleFile,
sourceFile: rule.sourceFile,
slug: rule.slug,
};
}

View file

@ -9,7 +9,7 @@ describe("convertRuleBlockToSlashCommand", () => {
rule: "Review this code for best practices",
description: "Performs a code review",
source: "rules-block",
ruleFile: "/path/to/rules.yaml",
sourceFile: "file:///path/to/rules.yaml",
invokable: true,
};
@ -20,7 +20,7 @@ describe("convertRuleBlockToSlashCommand", () => {
description: "Performs a code review",
prompt: "Review this code for best practices",
source: "invokable-rule",
promptFile: "/path/to/rules.yaml",
sourceFile: "file:///path/to/rules.yaml",
});
});

View file

@ -537,12 +537,25 @@ export class ConfigHandler {
// Track config loading telemetry
const endTime = performance.now();
const duration = endTime - startTime;
void Telemetry.capture("config_reload", {
const isSignedIn = await this.controlPlaneClient.isSignedIn();
const profileDescription = this.currentProfile.profileDescription;
const telemetryData: Record<string, any> = {
duration,
reason,
totalConfigLoads: this.totalConfigReloads,
configLoadInterrupted,
});
profileType: profileDescription.profileType,
isPersonalOrg: this.currentOrg?.id === this.PERSONAL_ORG_DESC.id,
errorCount: errors.length,
isSignedIn,
};
void Telemetry.capture("config_reload", telemetryData);
if (errors.length) {
Logger.error("Errors loading config: ", errors);
}
return {
config,
@ -594,10 +607,6 @@ export class ConfigHandler {
const config = await this.currentProfile.loadConfig(
this.additionalContextProviders,
);
if (config.errors?.length) {
Logger.error("Errors loading config: ", config.errors);
}
return config;
}

View file

@ -1,17 +1,14 @@
import { IDE } from "..";
import { joinPathsToUri } from "../util/uri";
const DEFAULT_ASSISTANT_FILE = `# This is an example agent configuration file
# It is used to define custom AI agents within Continue
# Each agent file can be accessed by selecting it from the agent dropdown
const DEFAULT_ASSISTANT_FILE = `# This is an example configuration file
# To learn more, see the full config.yaml reference: https://docs.continue.dev/reference
name: Example Agent
name: Example Config
version: 1.0.0
schema: v1
# Models define which AI models this agent can use
# Define which models can be used
# https://docs.continue.dev/customization/models
models:
- name: my gpt-5
@ -23,7 +20,7 @@ models:
with:
ANTHROPIC_API_KEY: \${{ secrets.ANTHROPIC_API_KEY }}
# MCP Servers the agent can use
# MCP Servers that Continue can access
# https://docs.continue.dev/customization/mcp-tools
mcpServers:
- uses: anthropic/memory-mcp
@ -50,7 +47,7 @@ export async function createNewAssistantFile(
let assistantFileUri: string;
do {
const suffix = counter === 0 ? "" : `-${counter}`;
assistantFileUri = joinPathsToUri(baseDirUri, `new-agent${suffix}.yaml`);
assistantFileUri = joinPathsToUri(baseDirUri, `new-config${suffix}.yaml`);
counter++;
} while (await ide.fileExists(assistantFileUri));

View file

@ -1,7 +1,7 @@
import { ConfigYaml } from "@continuedev/config-yaml";
export const defaultConfig: ConfigYaml = {
name: "Local Agent",
name: "Local Config",
version: "1.0.0",
schema: "v1",
models: [],

View file

@ -16,7 +16,7 @@ export async function getWorkspaceContinueRuleDotFiles(ide: IDE) {
const content = await ide.readFile(dotFile);
rules.push({
rule: content,
ruleFile: dotFile,
sourceFile: dotFile,
source: ".continuerules",
});
}

View file

@ -6,10 +6,10 @@ import path from "path";
import {
ConfigResult,
ConfigValidationError,
mergeConfigYamlRequestOptions,
ModelRole,
} from "@continuedev/config-yaml";
import * as JSONC from "comment-json";
import * as tar from "tar";
import {
BrowserSerializedContinueConfig,
@ -25,6 +25,7 @@ import {
IdeType,
ILLM,
ILLMLogger,
InternalMcpOptions,
LLMOptions,
ModelDescription,
RerankerDescription,
@ -57,9 +58,10 @@ import {
} from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import { PolicySingleton } from "../control-plane/PolicySingleton";
import { loadJsonMcpConfigs } from "../context/mcp/json/loadJsonMcpConfigs";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import { getBaseToolDefinitions } from "../tools";
import { PolicySingleton } from "../control-plane/PolicySingleton";
import { getBaseToolDefinitions, serializeTool } from "../tools";
import { resolveRelativePathInDir } from "../util/ideUtils";
import { getWorkspaceRcConfigs } from "./json/loadRcConfigs";
import { loadConfigContextProviders } from "./loadContextProviders";
@ -550,17 +552,27 @@ async function intermediateToFinalConfig({
if (orgPolicy?.policy?.allowMcpServers === false) {
await mcpManager.shutdown();
} else {
mcpManager.setConnections(
(config.experimental?.modelContextProtocolServers ?? []).map(
(server, index) => ({
id: `continue-mcp-server-${index + 1}`,
name: `MCP Server`,
...server,
requestOptions: config.requestOptions,
}),
const mcpOptions: InternalMcpOptions[] = (
config.experimental?.modelContextProtocolServers ?? []
).map((server, index) => ({
id: `continue-mcp-server-${index + 1}`,
name: `MCP Server`,
requestOptions: mergeConfigYamlRequestOptions(
server.transport.type !== "stdio"
? server.transport.requestOptions
: undefined,
config.requestOptions,
),
false,
...server.transport,
}));
const { errors: jsonMcpErrors, mcpServers } = await loadJsonMcpConfigs(
ide,
true,
config.requestOptions,
);
errors.push(...jsonMcpErrors);
mcpOptions.push(...mcpServers);
mcpManager.setConnections(mcpOptions, false);
}
// Handle experimental modelRole config values for apply and edit
@ -659,7 +671,7 @@ async function finalToBrowserConfig(
experimental: final.experimental,
rules: final.rules,
docs: final.docs,
tools: final.tools,
tools: final.tools.map(serializeTool),
mcpServerStatuses: final.mcpServerStatuses,
tabAutocompleteOptions: final.tabAutocompleteOptions,
usePlatform: await useHub(ide.getIdeSettings()),
@ -683,102 +695,43 @@ function escapeSpacesInPath(p: string): string {
return p.replace(/ /g, "\\ ");
}
async function handleEsbuildInstallation(ide: IDE, ideType: IdeType) {
// JetBrains is currently the only IDE that we've reached the plugin size limit and
// therefore need to install esbuild manually to reduce the size
if (ideType !== "jetbrains") {
return;
}
const globalContext = new GlobalContext();
if (globalContext.get("hasDismissedConfigTsNoticeJetBrains")) {
return;
}
const esbuildPath = getEsbuildBinaryPath();
if (fs.existsSync(esbuildPath)) {
return;
}
console.debug("No esbuild binary detected");
const shouldInstall = await promptEsbuildInstallation(ide);
if (shouldInstall) {
await downloadAndInstallEsbuild(ide);
}
}
async function promptEsbuildInstallation(ide: IDE): Promise<boolean> {
const installMsg = "Install esbuild";
const dismissMsg = "Dismiss";
const res = await ide.showToast(
"warning",
"You're using a custom 'config.ts' file, which requires 'esbuild' to be installed. Would you like to install it now?",
dismissMsg,
installMsg,
);
if (res === dismissMsg) {
const globalContext = new GlobalContext();
globalContext.update("hasDismissedConfigTsNoticeJetBrains", true);
return false;
}
return res === installMsg;
}
/**
* The download logic is adapted from here: https://esbuild.github.io/getting-started/#download-a-build
*/
async function downloadAndInstallEsbuild(ide: IDE) {
const esbuildPath = getEsbuildBinaryPath();
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "esbuild-"));
async function handleEsbuildInstallation(
ide: IDE,
_ideType: IdeType,
): Promise<boolean> {
// Only check when config.ts is going to be used; never auto-install.
const installCmd = "npm i esbuild@x.x.x --prefix ~/.continue";
// Try to detect a user-installed esbuild (normal resolution)
try {
const target = `${os.platform()}-${os.arch()}`;
const version = "0.19.11";
const url = `https://registry.npmjs.org/@esbuild/${target}/-/${target}-${version}.tgz`;
const tgzPath = path.join(tempDir, `esbuild-${version}.tgz`);
console.debug(`Downloading esbuild from: ${url}`);
execSync(`curl -fo "${tgzPath}" "${url}"`);
console.debug(`Extracting tgz file to: ${tempDir}`);
await tar.x({
file: tgzPath,
cwd: tempDir,
strip: 2, // Remove the top two levels of directories
});
// Ensure the destination directory exists
const destDir = path.dirname(esbuildPath);
if (!fs.existsSync(destDir)) {
fs.mkdirSync(destDir, { recursive: true });
await import("esbuild");
return true; // available
} catch {
// Try resolving from ~/.continue/node_modules as a courtesy
try {
const userEsbuild = path.join(
os.homedir(),
".continue",
"node_modules",
"esbuild",
);
const candidate = require.resolve("esbuild", { paths: [userEsbuild] });
// eslint-disable-next-line @typescript-eslint/no-var-requires
require(candidate);
return true; // available via ~/.continue
} catch {
// Not available → show friendly instructions and opt out of building
await ide.showToast(
"error",
[
"config.ts has been deprecated and esbuild is no longer automatically installed by Continue.",
"To use config.ts, install esbuild manually:",
"",
` ${installCmd}`,
].join("\n"),
);
return false;
}
// Move the file
const extractedBinaryPath = path.join(tempDir, "esbuild");
fs.renameSync(extractedBinaryPath, esbuildPath);
// Ensure the binary is executable (not needed on Windows)
if (os.platform() !== "win32") {
fs.chmodSync(esbuildPath, 0o755);
}
// Clean up
fs.unlinkSync(tgzPath);
fs.rmSync(tempDir, { recursive: true });
await ide.showToast(
"info",
`'esbuild' successfully installed to ${esbuildPath}`,
);
} catch (error) {
console.error("Error downloading or saving esbuild binary:", error);
throw error;
}
}
@ -853,8 +806,15 @@ async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) {
return;
}
await handleEsbuildInstallation(ide, ideType);
await tryBuildConfigTs();
// Only bother with esbuild if config.ts is actually customized
if (currentContent.trim() !== DEFAULT_CONFIG_TS_CONTENTS.trim()) {
const ok = await handleEsbuildInstallation(ide, ideType);
if (!ok) {
// esbuild not available → we already showed a friendly message; skip building
return;
}
await tryBuildConfigTs();
}
return readConfigJs();
}

View file

@ -1,3 +1,4 @@
import { BLOCK_TYPES } from "@continuedev/config-yaml";
import ignore from "ignore";
import * as URI from "uri-js";
import { IDE } from "..";
@ -6,12 +7,31 @@ import {
DEFAULT_IGNORE_FILETYPES,
} from "../indexing/ignore";
import { walkDir } from "../indexing/walkDir";
import { RULES_MARKDOWN_FILENAME } from "../llm/rules/constants";
import { getGlobalFolderWithName } from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import { joinPathsToUri } from "../util/uri";
import { getUriPathBasename, joinPathsToUri } from "../util/uri";
import { SYSTEM_PROMPT_DOT_FILE } from "./getWorkspaceContinueRuleDotFiles";
import { SUPPORTED_AGENT_FILES } from "./markdown";
export function isContinueConfigRelatedUri(uri: string): boolean {
return (
uri.endsWith(".continuerc.json") ||
uri.endsWith(".prompt") ||
!!SUPPORTED_AGENT_FILES.find((file) => uri.endsWith(`/${file}`)) ||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
(uri.includes(".continue") &&
(uri.endsWith(".yaml") ||
uri.endsWith(".yml") ||
uri.endsWith(".json"))) ||
[...BLOCK_TYPES, "agents", "assistants"].some((blockType) =>
uri.includes(`.continue/${blockType}`),
)
);
}
export function isLocalDefinitionFile(uri: string): boolean {
if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) {
export function isContinueAgentConfigFile(uri: string): boolean {
const isYaml = uri.endsWith(".yaml") || uri.endsWith(".yml");
if (!isYaml) {
return false;
}
@ -22,6 +42,10 @@ export function isLocalDefinitionFile(uri: string): boolean {
);
}
export function isColocatedRulesFile(uri: string): boolean {
return getUriPathBasename(uri) === RULES_MARKDOWN_FILENAME;
}
async function getDefinitionFilesInDir(
ide: IDE,
dir: string,

View file

@ -26,20 +26,30 @@ export class CodebaseRulesCache {
}
async update(ide: IDE, uri: string) {
const content = await ide.readFile(uri);
const { relativePathOrBasename } = findUriInDirs(
const workspaceDirs = await ide.getWorkspaceDirs();
const { relativePathOrBasename, foundInDir } = findUriInDirs(
uri,
await ide.getWorkspaceDirs(),
workspaceDirs,
);
if (!foundInDir) {
console.warn(
`Failed to load codebase rule ${uri}: URI not found in workspace`,
);
}
const rule = markdownToRule(
content,
{
uriType: "file",
fileUri: uri,
},
relativePathOrBasename,
);
const rule = markdownToRule(content, {
uriType: "file",
fileUri: relativePathOrBasename,
});
const ruleWithSource: RuleWithSource = {
...rule,
source: "colocated-markdown",
ruleFile: uri,
sourceFile: uri,
};
const matchIdx = this.rules.findIndex((r) => r.ruleFile === uri);
const matchIdx = this.rules.findIndex((r) => r.sourceFile === uri);
if (matchIdx === -1) {
this.rules.push(ruleWithSource);
} else {
@ -47,7 +57,7 @@ export class CodebaseRulesCache {
}
}
remove(uri: string) {
this.rules = this.rules.filter((r) => r.ruleFile !== uri);
this.rules = this.rules.filter((r) => r.sourceFile !== uri);
}
}
@ -75,20 +85,32 @@ export async function loadCodebaseRules(ide: IDE): Promise<{
for (const filePath of rulesMdFiles) {
try {
const content = await ide.readFile(filePath);
const { relativePathOrBasename } = findUriInDirs(
const { relativePathOrBasename, foundInDir, uri } = findUriInDirs(
filePath,
await ide.getWorkspaceDirs(),
);
const rule = markdownToRule(content, {
uriType: "file",
fileUri: relativePathOrBasename,
});
if (foundInDir) {
const lastSlashIndex = relativePathOrBasename.lastIndexOf("/");
const parentDir = relativePathOrBasename.substring(0, lastSlashIndex);
const rule = markdownToRule(
content,
{
uriType: "file",
fileUri: uri,
},
parentDir,
);
rules.push({
...rule,
source: "colocated-markdown",
ruleFile: filePath,
});
rules.push({
...rule,
source: "colocated-markdown",
sourceFile: filePath,
});
} else {
console.warn(
`Failed to load codebase rule ${uri}: URI not found in workspace dirs`,
);
}
} catch (e) {
errors.push({
fatal: false,

View file

@ -2,7 +2,6 @@ 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
@ -14,14 +13,10 @@ 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 = {
fileExists: vi.fn().mockImplementation(() => true),
readFile: vi.fn() as unknown as IDE["readFile"] & {
mockImplementation: Function;
},
@ -30,52 +25,45 @@ describe("loadCodebaseRules", () => {
},
} as unknown as IDE;
// Setup test files
const mockFiles = [
"src/rules.md",
"src/redux/rules.md",
"src/components/rules.md",
"src/utils/helper.ts", // Non-rules file
".continue/rules.md", // This should also be loaded
];
// Mock rule content
const mockRuleContent: Record<string, string> = {
"src/rules.md": "# General Rules\nFollow coding standards",
"src/redux/rules.md":
"file:///workspace/src/rules.md":
"# General Rules\nFollow coding standards",
"file:///workspace/src/redux/rules.md":
'---\nglobs: "**/*.{ts,tsx}"\n---\n# Redux Rules\nUse Redux Toolkit',
"src/components/rules.md":
"file:///workspace/src/components/rules.md":
'---\nglobs: ["**/*.tsx", "**/*.jsx"]\n---\n# Component Rules\nUse functional components',
".continue/rules.md": "# Global Rules\nFollow project guidelines",
"file:///workspace/.continue/rules.md":
"# Global Rules\nFollow project guidelines",
};
// Mock converted rules
const mockConvertedRules: Record<string, any> = {
"src/rules.md": {
"file:///workspace/src/rules.md": {
name: "General Rules",
rule: "Follow coding standards",
source: "colocated-markdown",
ruleFile: "src/rules.md",
sourceFile: "file:///workspace/src/rules.md",
},
"src/redux/rules.md": {
"file:///workspace/src/redux/rules.md": {
name: "Redux Rules",
rule: "Use Redux Toolkit",
globs: "**/*.{ts,tsx}",
source: "colocated-markdown",
ruleFile: "src/redux/rules.md",
sourceFile: "file:///workspace/src/redux/rules.md",
},
"src/components/rules.md": {
"file:///workspace/src/components/rules.md": {
name: "Component Rules",
rule: "Use functional components",
globs: ["**/*.tsx", "**/*.jsx"],
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
sourceFile: "file:///workspace/src/components/rules.md",
},
".continue/rules.md": {
"file:///workspace/.continue/rules.md": {
name: "Global Rules",
rule: "Follow project guidelines",
source: "colocated-markdown",
ruleFile: ".continue/rules.md",
sourceFile: "file:///workspace/.continue/rules.md",
},
};
@ -84,20 +72,13 @@ describe("loadCodebaseRules", () => {
vi.resetAllMocks();
// Mock walkDirs to return our test files
(walkDirs as any).mockResolvedValue(mockFiles);
(walkDirs as any).mockResolvedValue([
...Object.keys(mockRuleContent),
"file:///workspace/src/utils/helper.ts", // Non-rules file
]);
// 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 };
});
(mockIde.getWorkspaceDirs as any).mockResolvedValue(["file:///workspace"]);
// Mock readFile to return content based on path
(mockIde.readFile as any).mockImplementation((path: string) => {
@ -123,20 +104,36 @@ describe("loadCodebaseRules", () => {
// Should read all rules.md files
expect(mockIde.readFile).toHaveBeenCalledTimes(4);
expect(mockIde.readFile).toHaveBeenCalledWith("src/rules.md");
expect(mockIde.readFile).toHaveBeenCalledWith("src/redux/rules.md");
expect(mockIde.readFile).toHaveBeenCalledWith("src/components/rules.md");
expect(mockIde.readFile).toHaveBeenCalledWith(".continue/rules.md");
expect(mockIde.readFile).toHaveBeenCalledWith(
"file:///workspace/src/rules.md",
);
expect(mockIde.readFile).toHaveBeenCalledWith(
"file:///workspace/src/redux/rules.md",
);
expect(mockIde.readFile).toHaveBeenCalledWith(
"file:///workspace/src/components/rules.md",
);
expect(mockIde.readFile).toHaveBeenCalledWith(
"file:///workspace/.continue/rules.md",
);
// Should convert all rules
expect(markdownToRule).toHaveBeenCalledTimes(4);
// Should return all rules
expect(rules).toHaveLength(4);
expect(rules).toContainEqual(mockConvertedRules["src/rules.md"]);
expect(rules).toContainEqual(mockConvertedRules["src/redux/rules.md"]);
expect(rules).toContainEqual(mockConvertedRules["src/components/rules.md"]);
expect(rules).toContainEqual(mockConvertedRules[".continue/rules.md"]);
expect(rules).toContainEqual(
mockConvertedRules["file:///workspace/src/rules.md"],
);
expect(rules).toContainEqual(
mockConvertedRules["file:///workspace/src/redux/rules.md"],
);
expect(rules).toContainEqual(
mockConvertedRules["file:///workspace/src/components/rules.md"],
);
expect(rules).toContainEqual(
mockConvertedRules["file:///workspace/.continue/rules.md"],
);
// Should not have errors
expect(errors).toHaveLength(0);
@ -145,7 +142,7 @@ describe("loadCodebaseRules", () => {
it("should handle errors when reading a rule file", async () => {
// Setup mock to throw for a specific file
(mockIde.readFile as any).mockImplementation((path: string) => {
if (path === "src/redux/rules.md") {
if (path === "file:///workspace/src/redux/rules.md") {
return Promise.reject(new Error("Failed to read file"));
}
return Promise.resolve(mockRuleContent[path] || "");
@ -155,14 +152,20 @@ describe("loadCodebaseRules", () => {
// Should still return other rules
expect(rules).toHaveLength(3);
expect(rules).toContainEqual(mockConvertedRules["src/rules.md"]);
expect(rules).toContainEqual(mockConvertedRules["src/components/rules.md"]);
expect(rules).toContainEqual(mockConvertedRules[".continue/rules.md"]);
expect(rules).toContainEqual(
mockConvertedRules["file:///workspace/src/rules.md"],
);
expect(rules).toContainEqual(
mockConvertedRules["file:///workspace/src/components/rules.md"],
);
expect(rules).toContainEqual(
mockConvertedRules["file:///workspace/.continue/rules.md"],
);
// Should have one error
expect(errors).toHaveLength(1);
expect(errors[0].message).toContain(
"Failed to parse colocated rule file src/redux/rules.md",
"Failed to parse colocated rule file file:///workspace/src/redux/rules.md: Failed to read file",
);
});

View file

@ -3,11 +3,14 @@ import {
markdownToRule,
} from "@continuedev/config-yaml";
import { IDE, RuleWithSource } from "../..";
import { findUriInDirs } from "../../util/uri";
import { PROMPTS_DIR_NAME, RULES_DIR_NAME } from "../../promptFiles";
import { joinPathsToUri } from "../../util/uri";
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
export const SUPPORTED_AGENT_FILES = ["AGENTS.md", "AGENT.md", "CLAUDE.md"];
/**
* Loads rules from markdown files in the .continue/rules directory
* Loads rules from markdown files in the .continue/rules and .continue/prompts directories
* and agent files (AGENTS.md, AGENT.md, CLAUDE.md) at workspace root
*/
export async function loadMarkdownRules(ide: IDE): Promise<{
rules: RuleWithSource[];
@ -16,41 +19,86 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
const errors: ConfigValidationError[] = [];
const rules: RuleWithSource[] = [];
try {
// Get all .md files from .continue/rules
const markdownFiles = await getAllDotContinueDefinitionFiles(
ide,
{ includeGlobal: true, includeWorkspace: true, fileExtType: "markdown" },
"rules",
);
// First, try to load agent files from workspace root
const workspaceDirs = await ide.getWorkspaceDirs();
// Filter to just .md files
const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md"));
// Process each markdown file
for (const file of mdFiles) {
for (const workspaceDir of workspaceDirs) {
let agentFileFound = false;
for (const fileName of SUPPORTED_AGENT_FILES) {
try {
const { relativePathOrBasename } = findUriInDirs(
file.path,
await ide.getWorkspaceDirs(),
);
const rule = markdownToRule(file.content, {
uriType: "file",
fileUri: relativePathOrBasename,
});
rules.push({ ...rule, source: "rules-block", ruleFile: file.path });
const agentFileUri = joinPathsToUri(workspaceDir, fileName);
const exists = await ide.fileExists(agentFileUri);
if (exists) {
const agentContent = await ide.readFile(agentFileUri);
const rule = markdownToRule(agentContent, {
uriType: "file",
fileUri: agentFileUri,
});
rules.push({
...rule,
source: "agentFile",
sourceFile: agentFileUri,
alwaysApply: true,
});
agentFileFound = true;
}
break; // Use the first found agent file in this workspace
} catch (e) {
errors.push({
fatal: false,
message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`,
});
// File doesn't exist or can't be read, continue to next file
}
}
} catch (e) {
errors.push({
fatal: false,
message: `Error loading markdown rule files: ${e instanceof Error ? e.message : e}`,
});
if (agentFileFound) {
break; // Use agent file from first workspace that has one
}
}
// Load markdown files from both .continue/rules and .continue/prompts
const dirsToCheck = [RULES_DIR_NAME, PROMPTS_DIR_NAME];
for (const dirName of dirsToCheck) {
try {
const markdownFiles = await getAllDotContinueDefinitionFiles(
ide,
{
includeGlobal: true,
includeWorkspace: true,
fileExtType: "markdown",
},
dirName,
);
// Filter to just .md files
const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md"));
// Process each markdown file
for (const file of mdFiles) {
try {
const rule = markdownToRule(file.content, {
uriType: "file",
fileUri: file.path,
});
if (!rule.invokable) {
rules.push({
...rule,
source: "rules-block",
sourceFile: file.path,
});
}
} catch (e) {
errors.push({
fatal: false,
message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`,
});
}
}
} catch (e) {
errors.push({
fatal: false,
message: `Error loading markdown rule files from ${dirName}: ${e instanceof Error ? e.message : e}`,
});
}
}
return { rules, errors };

View file

@ -17,7 +17,7 @@ describe("Rule Colocation Application", () => {
name: "Root Rule",
rule: "Follow project standards",
source: "colocated-markdown",
ruleFile: ".continue/rules.md",
sourceFile: ".continue/rules.md",
},
// Nested directory rule without globs - should only apply to files in that directory
@ -25,7 +25,7 @@ describe("Rule Colocation Application", () => {
name: "React Components Rule",
rule: "Use functional components with hooks",
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
sourceFile: "src/components/rules.md",
// No explicit globs - should implicitly only apply to files in that directory
},
@ -35,7 +35,7 @@ describe("Rule Colocation Application", () => {
rule: "Use Redux Toolkit for state management",
globs: "src/redux/**/*.{ts,tsx}",
source: "colocated-markdown",
ruleFile: "src/redux/rules.md",
sourceFile: "src/redux/rules.md",
},
// Directory rule with specific file extension glob
@ -44,7 +44,7 @@ describe("Rule Colocation Application", () => {
rule: "Use TypeScript with React components",
globs: "**/*.tsx", // Only apply to .tsx files
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
sourceFile: "src/components/rules.md",
},
// Rule for a specific subdirectory with its own glob
@ -53,7 +53,7 @@ describe("Rule Colocation Application", () => {
rule: "Follow API utility conventions",
globs: "**/*.ts", // Only TypeScript files in this directory
source: "colocated-markdown",
ruleFile: "src/utils/api/rules.md",
sourceFile: "src/utils/api/rules.md",
},
];
@ -184,7 +184,7 @@ describe("Rule Colocation Application", () => {
name: "Implied Components Rule",
rule: "Use React component best practices",
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
sourceFile: "src/components/rules.md",
// No explicit globs - should infer from directory
};
@ -234,7 +234,7 @@ describe("Rule Colocation Application", () => {
rule: "Use TypeScript with React components",
globs: "**/*.tsx", // Only apply to .tsx files
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
sourceFile: "src/components/rules.md",
};
// Test with TSX component file - should apply
@ -281,7 +281,7 @@ describe("Rule Colocation Application", () => {
rule: "Follow API utility conventions",
globs: "**/*.ts", // Only TypeScript files in this directory
source: "colocated-markdown",
ruleFile: "src/utils/api/rules.md",
sourceFile: "src/utils/api/rules.md",
};
// Test with file in the API utils directory - should apply
@ -314,9 +314,9 @@ describe("Rule Colocation Application", () => {
// it should automatically create an implicit glob pattern for that directory.
function createRuleWithAutomaticGlobInference(
ruleFilePath: string,
sourceFilePath: string,
): RuleWithSource {
const directory = path.dirname(ruleFilePath);
const directory = path.dirname(sourceFilePath);
// The expected behavior would be to create an implicit glob like this:
const expectedGlob = `${directory}/**/*`;
@ -324,7 +324,7 @@ describe("Rule Colocation Application", () => {
name: `Inferred Rule for ${directory}`,
rule: `Follow standards for ${directory}`,
source: "colocated-markdown",
ruleFile: ruleFilePath,
sourceFile: sourceFilePath,
// In a fixed implementation, these globs would be automatically inferred
// globs: expectedGlob,
};

View file

@ -4,6 +4,15 @@ import {
} from "@continuedev/config-yaml";
import { joinPathsToUri } from "../../util/uri";
function createRelativeRuleFilePathParts(ruleName: string): string[] {
const safeRuleName = sanitizeRuleName(ruleName);
return [".continue", "rules", `${safeRuleName}.${RULE_FILE_EXTENSION}`];
}
export function createRelativeRuleFilePath(ruleName: string): string {
return createRelativeRuleFilePathParts(ruleName).join("/");
}
/**
* Creates the file path for a rule in the workspace .continue/rules directory
*/
@ -11,11 +20,8 @@ export function createRuleFilePath(
workspaceDir: string,
ruleName: string,
): string {
const safeRuleName = sanitizeRuleName(ruleName);
return joinPathsToUri(
workspaceDir,
".continue",
"rules",
`${safeRuleName}.${RULE_FILE_EXTENSION}`,
...createRelativeRuleFilePathParts(ruleName),
);
}

View file

@ -173,13 +173,6 @@ export function migrateJsonSharedConfig(filepath: string, ide: IDE): void {
effected = true;
}
const { autoAcceptEditToolDiffs, ...withoutAutoApply } = migratedUI;
if (autoAcceptEditToolDiffs !== undefined) {
shareConfigUpdates.autoAcceptEditToolDiffs = autoAcceptEditToolDiffs;
migratedUI = withoutAutoApply;
effected = true;
}
const { showChatScrollbar, ...withoutShowChatScrollbar } = migratedUI;
if (showChatScrollbar !== undefined) {
shareConfigUpdates.showChatScrollbar = showChatScrollbar;

View file

@ -32,7 +32,7 @@ export default class LocalProfileLoader implements IProfileLoader {
iconUrl: "",
title: overrideAssistantFile?.path
? getUriPathBasename(overrideAssistantFile.path)
: "Local Agent",
: "Local Config",
errors: undefined,
uri:
overrideAssistantFile?.path ??
@ -47,7 +47,7 @@ export default class LocalProfileLoader implements IProfileLoader {
);
this.description.title = parsedAssistant.name;
} catch (e) {
console.error("Failed to parse agent file: ", e);
console.error("Failed to parse config file: ", e);
}
}
}

View file

@ -18,6 +18,7 @@ import {
Tool,
} from "../../";
import { stringifyMcpPrompt } from "../../commands/slash/mcpSlashCommand";
import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import ContinueProxyContextProvider from "../../context/providers/ContinueProxyContextProvider";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
@ -27,6 +28,7 @@ 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 { initSlashCommand } from "../../promptFiles/initPrompt";
import { getConfigDependentToolDefinitions } from "../../tools";
import { encodeMCPToolUri } from "../../tools/callTool";
import { getMCPToolName } from "../../tools/mcpToolName";
@ -155,6 +157,23 @@ export default async function doLoadConfig(options: {
errors.push(...rulesErrors);
newConfig.rules.unshift(...rules);
// Convert invokable rules to slash commands
for (const rule of newConfig.rules) {
if (rule.invokable) {
try {
const slashCommand = convertRuleBlockToSlashCommand(rule);
(newConfig.slashCommands ??= []).push(slashCommand);
} catch (e) {
errors.push({
message: `Error converting invokable rule ${rule.name} to slash command: ${e instanceof Error ? e.message : e}`,
fatal: false,
});
}
}
}
newConfig.slashCommands.push(initSlashCommand);
const proxyContextProvider = newConfig.contextProviders?.find(
(cp) => cp.description.title === "continue-proxy",
);
@ -194,6 +213,13 @@ export default async function doLoadConfig(options: {
newConfig.mcpServerStatuses = serializableStatuses;
for (const server of mcpServerStatuses) {
server.errors.forEach((error) => {
// MCP errors will also show as config loading errors
errors.push({
fatal: false,
message: error,
});
});
if (server.status === "connected") {
const serverTools: Tool[] = server.tools.map((tool) => ({
displayTitle: server.name + " " + tool.name,

View file

@ -31,7 +31,6 @@ export const sharedConfigSchema = z
codeWrap: z.boolean(),
displayRawMarkdown: z.boolean(),
showChatScrollbar: z.boolean(),
autoAcceptEditToolDiffs: z.boolean(),
continueAfterToolRejection: z.boolean(),
// `tabAutocompleteOptions` in `ContinueConfig`
@ -140,10 +139,6 @@ export function modifyAnyConfigWithSharedConfig<
if (sharedConfig.showChatScrollbar !== undefined) {
configCopy.ui.showChatScrollbar = sharedConfig.showChatScrollbar;
}
if (sharedConfig.autoAcceptEditToolDiffs !== undefined) {
configCopy.ui.autoAcceptEditToolDiffs =
sharedConfig.autoAcceptEditToolDiffs;
}
if (sharedConfig.allowAnonymousTelemetry !== undefined) {
configCopy.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry;

View file

@ -78,8 +78,9 @@ declare global {
export interface ILLM extends LLMOptions {
get providerName(): string;
uniqueId: string;
lastRequestId?: string;
model: string;
title?: string;
@ -280,11 +281,6 @@ declare global {
replacement: string;
}
export interface ContinueError {
title: string;
message: string;
}
export interface CompletionOptions extends BaseCompletionOptions {
model: string;
}
@ -692,6 +688,8 @@ declare global {
openUrl(url: string): Promise<void>;
getExternalUri?(uri: string): Promise<string>;
runCommand(command: string): Promise<void>;
saveFile(filepath: string): Promise<void>;

View file

@ -1,12 +1,12 @@
import { decodeSecretLocation, SecretType } from "@continuedev/config-yaml";
import { BrowserSerializedContinueConfig } from "..";
import { BrowserSerializedContinueConfig, ModelDescription } from "..";
/**
* Helper function to determine if the config uses a free trial API key
* Helper function to determine if the config uses an API key that relies on Continue credits (free trial or models add-on)
* @param config The serialized config object
* @returns true if the config is using any free trial models
*/
export function usesFreeTrialApiKey(
export function usesCreditsBasedApiKey(
config: BrowserSerializedContinueConfig | null,
): boolean {
if (!config) {
@ -19,12 +19,7 @@ export function usesFreeTrialApiKey(
// Check if any of the chat models use free-trial provider
try {
const hasFreeTrial = allModels?.some(
(model) =>
model.apiKeyLocation &&
decodeSecretLocation(model.apiKeyLocation).secretType ===
SecretType.FreeTrial,
);
const hasFreeTrial = allModels?.some(modelUsesCreditsBasedApiKey);
return hasFreeTrial;
} catch (e) {
@ -33,3 +28,13 @@ export function usesFreeTrialApiKey(
return false;
}
const modelUsesCreditsBasedApiKey = (model: ModelDescription) => {
if (!model.apiKeyLocation) {
return false;
}
const secretType = decodeSecretLocation(model.apiKeyLocation).secretType;
return secretType === SecretType.FreeTrial;
};

View file

@ -15,13 +15,13 @@ vi.mock("@continuedev/config-yaml", () => ({
}));
describe("usesFreeTrialApiKey", () => {
let usesFreeTrialApiKey: typeof import("./usesFreeTrialApiKey").usesFreeTrialApiKey;
let usesFreeTrialApiKey: typeof import("./usesFreeTrialApiKey").usesCreditsBasedApiKey;
let SecretType: typeof import("@continuedev/config-yaml").SecretType;
beforeEach(async () => {
mockDecodeSecretLocation.mockReset();
usesFreeTrialApiKey = (await import("./usesFreeTrialApiKey"))
.usesFreeTrialApiKey;
.usesCreditsBasedApiKey;
SecretType = (await import("@continuedev/config-yaml")).SecretType;
});

View file

@ -2,10 +2,12 @@ import {
BlockType,
ConfigYaml,
createRuleMarkdown,
createPromptMarkdown,
RULE_FILE_EXTENSION,
} from "@continuedev/config-yaml";
import * as YAML from "yaml";
import { IDE } from "../..";
import { getContinueGlobalPath } from "../../util/paths";
import { joinPathsToUri } from "../../util/uri";
const BLOCK_TYPE_CONFIG: Record<
@ -83,7 +85,10 @@ function getContentsForNewBlock(blockType: BlockType): ConfigYaml {
}
function getFileExtension(blockType: BlockType): string {
return blockType === "rules" ? RULE_FILE_EXTENSION : "yaml";
if (blockType === "rules" || blockType === "prompts") {
return "md";
}
return "yaml";
}
export function getFileContent(blockType: BlockType): string {
@ -91,6 +96,15 @@ export function getFileContent(blockType: BlockType): string {
return createRuleMarkdown("New Rule", "Your rule content", {
description: "A description of your rule",
});
} else if (blockType === "prompts") {
return createPromptMarkdown(
"New prompt",
"Please write a thorough suite of unit tests for this code, making sure to cover all relevant edge cases",
{
description: "New prompt",
invokable: true,
},
);
} else {
return YAML.stringify(getContentsForNewBlock(blockType));
}
@ -101,8 +115,13 @@ export async function findAvailableFilename(
blockType: BlockType,
fileExists: (uri: string) => Promise<boolean>,
extension?: string,
isGlobal?: boolean,
): Promise<string> {
const baseFilename = `new-${BLOCK_TYPE_CONFIG[blockType]?.filename}`;
// Differentiate filename based on whether its a global rule or a workspace rule
const baseFilename =
blockType === "rules" && isGlobal
? "global-rule"
: `new-${BLOCK_TYPE_CONFIG[blockType]?.filename}`;
const fileExtension = extension ?? getFileExtension(blockType);
let counter = 0;
let fileUri: string;
@ -143,3 +162,28 @@ export async function createNewWorkspaceBlockFile(
await ide.writeFile(fileUri, fileContent);
await ide.openFile(fileUri);
}
export async function createNewGlobalRuleFile(ide: IDE): Promise<void> {
try {
const globalDir = getContinueGlobalPath();
// Create the rules subdirectory within the global directory
const rulesDir = joinPathsToUri(globalDir, "rules");
const fileUri = await findAvailableFilename(
rulesDir,
"rules",
ide.fileExists.bind(ide),
undefined,
true, // isGlobal = true for global rules
);
const fileContent = getFileContent("rules");
await ide.writeFile(fileUri, fileContent);
await ide.openFile(fileUri);
} catch (error) {
throw error;
}
}

View file

@ -18,7 +18,7 @@ describe("getFileContent", () => {
expect(result).toContain("provider: anthropic");
});
test("generates correct YAML for different block types", () => {
test("generates correct content for different block types", () => {
const contextResult = getFileContent("context");
expect(contextResult).toContain("name: New context");
expect(contextResult).toContain("context:");
@ -31,8 +31,10 @@ describe("getFileContent", () => {
const promptsResult = getFileContent("prompts");
expect(promptsResult).toContain("name: New prompt");
expect(promptsResult).toContain("prompts:");
expect(promptsResult).toContain("description: New prompt");
expect(promptsResult).toContain("invokable: true");
expect(promptsResult).toContain("thorough suite of unit tests");
expect(promptsResult).toContain("---"); // Should be markdown with frontmatter
const mcpResult = getFileContent("mcpServers");
expect(mcpResult).toContain("name: New MCP server");
@ -96,7 +98,7 @@ describe("findAvailableFilename", () => {
{ blockType: "context", expected: "/test/new-context.yaml" },
{ blockType: "rules", expected: `/test/new-rule.${RULE_FILE_EXTENSION}` },
{ blockType: "docs", expected: "/test/new-doc.yaml" },
{ blockType: "prompts", expected: "/test/new-prompt.yaml" },
{ blockType: "prompts", expected: "/test/new-prompt.md" },
{ blockType: "mcpServers", expected: "/test/new-mcp-server.yaml" },
];
@ -148,8 +150,8 @@ describe("findAvailableFilename", () => {
const existingFiles = new Set(
Array.from({ length: 100 }, (_, i) =>
i === 0
? "/workspace/.continue/prompts/new-prompt.yaml"
: `/workspace/.continue/prompts/new-prompt-${i}.yaml`,
? "/workspace/.continue/prompts/new-prompt.md"
: `/workspace/.continue/prompts/new-prompt-${i}.md`,
),
);
@ -163,6 +165,6 @@ describe("findAvailableFilename", () => {
mockFileExists,
);
expect(result).toBe("/workspace/.continue/prompts/new-prompt-100.yaml");
expect(result).toBe("/workspace/.continue/prompts/new-prompt-100.md");
});
});

View file

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

View file

@ -15,7 +15,14 @@ import {
} from "@continuedev/config-yaml";
import { dirname } from "node:path";
import { ContinueConfig, IDE, IdeInfo, IdeSettings, ILLMLogger } from "../..";
import {
ContinueConfig,
IDE,
IdeInfo,
IdeSettings,
ILLMLogger,
InternalMcpOptions,
} from "../..";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import { ControlPlaneClient } from "../../control-plane/client";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
@ -25,7 +32,7 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand";
import { loadJsonMcpConfigs } from "../../context/mcp/json/loadJsonMcpConfigs";
import { getControlPlaneEnvSync } from "../../control-plane/env";
import { PolicySingleton } from "../../control-plane/PolicySingleton";
import { getBaseToolDefinitions } from "../../tools";
@ -35,7 +42,10 @@ import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks";
import { LocalPlatformClient } from "./LocalPlatformClient";
import { llmsFromModelConfig } from "./models";
import { convertYamlRuleToContinueRule } from "./yamlToContinueConfig";
import {
convertYamlMcpConfigToInternalMcpOptions,
convertYamlRuleToContinueRule,
} from "./yamlToContinueConfig";
async function loadConfigYaml(options: {
overrideConfigYaml: AssistantUnrolled | undefined;
@ -209,19 +219,6 @@ export async function configYamlToContinueConfig(options: {
for (const rule of config.rules ?? []) {
const convertedRule = convertYamlRuleToContinueRule(rule);
continueConfig.rules.push(convertedRule);
// Convert invokable rules to slash commands
if (convertedRule.invokable) {
try {
const slashCommand = convertRuleBlockToSlashCommand(convertedRule);
continueConfig.slashCommands?.push(slashCommand);
} catch (e) {
localErrors.push({
message: `Error converting invokable rule ${convertedRule.name} to slash command: ${e instanceof Error ? e.message : e}`,
fatal: false,
});
}
}
}
continueConfig.data = config.data?.map((d) => ({
@ -241,17 +238,19 @@ export async function configYamlToContinueConfig(options: {
}));
config.mcpServers?.forEach((mcpServer) => {
const mcpArgVariables =
mcpServer.args?.filter((arg) => TEMPLATE_VAR_REGEX.test(arg)) ?? [];
if ("args" in mcpServer) {
const mcpArgVariables =
mcpServer.args?.filter((arg) => TEMPLATE_VAR_REGEX.test(arg)) ?? [];
if (mcpArgVariables.length === 0) {
return;
if (mcpArgVariables.length === 0) {
return;
}
localErrors.push({
fatal: false,
message: `MCP server "${mcpServer.name}" has unsubstituted variables in args: ${mcpArgVariables.join(", ")}. Please refer to https://docs.continue.dev/hub/secrets/secret-types for managing hub secrets.`,
});
}
localErrors.push({
fatal: false,
message: `MCP server "${mcpServer.name}" has unsubstituted variables in args: ${mcpArgVariables.join(", ")}. Please refer to https://docs.continue.dev/hub/secrets/secret-types for managing hub secrets.`,
});
});
// Prompt files -
@ -395,25 +394,18 @@ export async function configYamlToContinueConfig(options: {
if (orgPolicy?.policy?.allowMcpServers === false) {
await mcpManager.shutdown();
} else {
mcpManager.setConnections(
(config.mcpServers ?? []).map((server) => ({
id: server.name,
name: server.name,
sourceFile: server.sourceFile,
transport: {
type: "stdio",
args: [],
requestOptions: mergeConfigYamlRequestOptions(
server.requestOptions,
config.requestOptions,
),
...(server as any), // TODO: fix the types on mcpServers in config-yaml
},
timeout: server.connectionTimeout,
})),
false,
{ ide },
const mcpOptions: InternalMcpOptions[] = (config.mcpServers ?? []).map(
(server) =>
convertYamlMcpConfigToInternalMcpOptions(server, config.requestOptions),
);
const { errors: jsonMcpErrors, mcpServers } = await loadJsonMcpConfigs(
ide,
true,
config.requestOptions,
);
localErrors.push(...jsonMcpErrors);
mcpOptions.push(...mcpServers);
mcpManager.setConnections(mcpOptions, false, { ide });
}
return { config: continueConfig, errors: localErrors };

View file

@ -52,7 +52,7 @@ describe("llmsFromModelConfig requestOptions merging", () => {
requestOptions: {
timeout: 30000,
headers: {
"User-Agent": "Continue/1.0.0",
"user-agent": "Continue/1.0.0",
},
proxy: "global-proxy",
},
@ -112,7 +112,7 @@ describe("llmsFromModelConfig requestOptions merging", () => {
expect(llm.requestOptions).toEqual({
timeout: 60000, // model-specific takes precedence
headers: {
"User-Agent": "Continue/1.0.0", // from global request options
"user-agent": "Continue/1.0.0", // from global request options
Authorization: "Bearer token123", // from model
},
proxy: "model-proxy", // model-specific takes precedence
@ -236,7 +236,7 @@ describe("llmsFromModelConfig requestOptions merging", () => {
expect(llm.requestOptions).toEqual({
timeout: 120000, // model-specific takes precedence
headers: {
"User-Agent": "Continue/1.0.0", // from global request options
"user-agent": "Continue/1.0.0", // from global request options
"X-Custom": "autodetect", // from model
},
proxy: "global-proxy", // from global request options
@ -302,7 +302,7 @@ describe("llmsFromModelConfig requestOptions merging", () => {
expect(llm.requestOptions).toEqual({
timeout: 90000,
headers: {
"User-Agent": "Continue/1.0.0",
"user-agent": "Continue/1.0.0",
},
proxy: "global-proxy",
});
@ -345,7 +345,7 @@ describe("llmsFromModelConfig requestOptions merging", () => {
const llm = result[0];
expect(llm.requestOptions?.headers).toEqual({
"User-Agent": "Continue/1.0.0", // from global request options
"user-agent": "Continue/1.0.0", // from global request options
"Cache-Control": "no-cache", // from global request options
Authorization: "Bearer model-token", // from model
Accept: "application/json", // from model (overrides config)

View file

@ -1,5 +1,16 @@
import { MCPServer, Rule } from "@continuedev/config-yaml";
import { ExperimentalMCPOptions, RuleWithSource } from "../..";
import {
MCPServer,
mergeConfigYamlRequestOptions,
RequestOptions,
Rule,
} from "@continuedev/config-yaml";
import {
InternalMcpOptions,
InternalSseMcpOptions,
InternalStdioMcpOptions,
InternalStreamableHttpMcpOptions,
RuleWithSource,
} from "../..";
export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
if (typeof rule === "string") {
@ -14,24 +25,51 @@ export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
globs: rule.globs,
name: rule.name,
description: rule.description,
ruleFile: rule.sourceFile,
sourceFile: rule.sourceFile,
alwaysApply: rule.alwaysApply,
invokable: rule.invokable ?? false,
};
}
}
export function convertYamlMcpToContinueMcp(
server: MCPServer,
): ExperimentalMCPOptions {
return {
transport: {
type: "stdio",
command: server.command,
args: server.args ?? [],
env: server.env,
cwd: server.cwd,
} as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
timeout: server.connectionTimeout,
export function convertYamlMcpConfigToInternalMcpOptions(
config: MCPServer,
globalRequestOptions?: RequestOptions,
): InternalMcpOptions {
const { connectionTimeout, faviconUrl, name, sourceFile } = config;
const shared = {
id: name,
name,
faviconUrl: faviconUrl,
timeout: connectionTimeout,
sourceFile,
};
// Stdio
if ("command" in config) {
const { args, command, cwd, env, type } = config;
const stdioOptions: InternalStdioMcpOptions = {
...shared,
type,
command,
args,
cwd,
env,
};
return stdioOptions;
}
// HTTP/SSE
const { type, url, apiKey, requestOptions } = config;
const httpSseConfig:
| InternalStreamableHttpMcpOptions
| InternalSseMcpOptions = {
...shared,
type,
url,
apiKey,
requestOptions: mergeConfigYamlRequestOptions(
requestOptions,
globalRequestOptions,
),
};
return httpSseConfig;
}

View file

@ -1,4 +1,7 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { fileURLToPath } from "url";
import {
SSEClientTransport,
SseError,
@ -6,18 +9,22 @@ import {
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 { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { Agent as HttpsAgent } from "https";
import {
IDE,
InternalMcpOptions,
InternalSseMcpOptions,
InternalStdioMcpOptions,
InternalStreamableHttpMcpOptions,
InternalWebsocketMcpOptions,
MCPConnectionStatus,
MCPOptions,
MCPPrompt,
MCPResource,
MCPResourceTemplate,
MCPServerStatus,
MCPTool,
} from "../..";
import { resolveRelativePathInDir } from "../../util/ideUtils";
import { getEnvPathFromUserShell } from "../../util/shellPath";
import { getOauthToken } from "./MCPOauth";
@ -34,6 +41,8 @@ const WINDOWS_BATCH_COMMANDS = [
"bunx",
];
const COMMONS_ENV_VARS = ["HOME", "USER", "USERPROFILE", "LOGNAME", "USERNAME"];
function is401Error(error: unknown) {
return (
(error instanceof SseError && error.code === 401) ||
@ -65,7 +74,7 @@ class MCPConnection {
};
constructor(
public options: MCPOptions,
public options: InternalMcpOptions,
public extras?: MCPExtras,
) {
// Don't construct transport in constructor to avoid blocking
@ -84,10 +93,11 @@ class MCPConnection {
this.abortController = new AbortController();
}
async disconnect() {
async disconnect(disable = false) {
this.abortController.abort();
await this.client.close();
await this.transport.close();
this.status = disable ? "disabled" : "not-connected";
}
getStatus(): MCPServerStatus {
@ -105,6 +115,9 @@ class MCPConnection {
}
async connectClient(forceRefresh: boolean, externalSignal: AbortSignal) {
if (this.status === "disabled") {
return;
}
if (!forceRefresh) {
// Already connected
if (this.status === "connected") {
@ -131,20 +144,20 @@ class MCPConnection {
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 = {
if (this.options.type === "sse") {
if (!this.options.requestOptions) {
this.options.requestOptions = {
headers: {},
};
}
const accessToken = await getOauthToken(
this.options.transport.url,
this.options.url,
this.extras?.ide!,
);
if (accessToken) {
this.isProtectedResource = true;
this.options.transport.requestOptions.headers = {
...this.options.transport.requestOptions.headers,
this.options.requestOptions.headers = {
...this.options.requestOptions.headers,
Authorization: `Bearer ${accessToken}`,
};
}
@ -177,22 +190,71 @@ class MCPConnection {
});
}),
(async () => {
this.transport = await this.constructTransportAsync(this.options);
try {
await this.client.connect(this.transport);
} catch (error) {
// Allow the case where for whatever reason is already connected
if (
error instanceof Error &&
error.message.startsWith(
"StdioClientTransport already started",
)
) {
await this.client.close();
await this.client.connect(this.transport);
if ("command" in this.options) {
// STDIO: no need to check type, just if command is present
const transport = await this.constructStdioTransport(
this.options,
);
try {
await this.client.connect(transport, {});
this.transport = transport;
} catch (error) {
// Allow the case where for whatever reason is already connected
if (
error instanceof Error &&
error.message.startsWith(
"StdioClientTransport already started",
)
) {
await this.client.close();
await this.client.connect(transport);
this.transport = transport;
} else {
throw error;
}
}
} else {
// SSE/HTTP: if type isn't explicit: try http and fall back to sse
if (this.options.type === "sse") {
const transport = this.constructSseTransport(this.options);
await this.client.connect(transport, {});
this.transport = transport;
} else if (this.options.type === "streamable-http") {
const transport = this.constructHttpTransport(this.options);
await this.client.connect(transport, {});
this.transport = transport;
} else if (this.options.type === "websocket") {
const transport = this.constructWebsocketTransport(
this.options,
);
await this.client.connect(transport, {});
this.transport = transport;
} else if (this.options.type) {
throw new Error(
`Unsupported transport type: ${this.options.type}`,
);
} else {
throw error;
try {
const transport = this.constructHttpTransport({
...this.options,
type: "streamable-http",
});
await this.client.connect(transport, {});
this.transport = transport;
} catch (e) {
try {
const transport = this.constructSseTransport({
...this.options,
type: "sse",
});
await this.client.connect(transport, {});
this.transport = transport;
} catch (e) {
throw new Error(
`MCP config with URL and no type specified failed both SSE and HTTP connection: ${e instanceof Error ? e.message : String(e)}`,
);
}
}
}
}
@ -201,7 +263,6 @@ class MCPConnection {
// this.client.setNotificationHandler(, notification => {
// console.log(notification)
// })
const capabilities = this.client.getServerCapabilities();
// Resources <—> Context Provider
@ -304,7 +365,7 @@ class MCPConnection {
// Include stdio output if available for stdio transport
if (
this.options.transport.type === "stdio" &&
this.options.type === "stdio" &&
(this.stdioOutput.stdout || this.stdioOutput.stderr)
) {
errorMessage += "\n\nProcess output:";
@ -355,98 +416,158 @@ class MCPConnection {
};
}
private async constructTransportAsync(
options: MCPOptions,
): Promise<Transport> {
switch (options.transport.type) {
case "stdio":
const env: Record<string, string> = options.transport.env
? { ...options.transport.env }
: {};
if (process.env.PATH !== undefined) {
// Set the initial PATH from process.env
env.PATH = process.env.PATH;
// For non-Windows platforms, try to get the PATH from user shell
if (process.platform !== "win32") {
try {
const shellEnvPath = await getEnvPathFromUserShell();
if (shellEnvPath && shellEnvPath !== process.env.PATH) {
env.PATH = shellEnvPath;
}
} catch (err) {
console.error("Error getting PATH:", err);
}
}
}
// Resolve the command and args for the current platform
const { command, args } = this.resolveCommandForPlatform(
options.transport.command,
options.transport.args || [],
);
const transport = new StdioClientTransport({
command,
args,
env,
cwd: options.transport.cwd,
stderr: "pipe",
});
// Capture stdio output for better error reporting
transport.stderr?.on("data", (data: Buffer) => {
this.stdioOutput.stderr += data.toString();
});
return transport;
case "websocket":
return new WebSocketClientTransport(new URL(options.transport.url));
case "sse":
const sseAgent =
options.transport.requestOptions?.verifySsl === false
? new HttpsAgent({ rejectUnauthorized: false })
: undefined;
return new SSEClientTransport(new URL(options.transport.url), {
eventSourceInit: {
fetch: (input, init) =>
fetch(input, {
...init,
headers: {
...init?.headers,
...(options.transport.requestOptions?.headers as
| Record<string, string>
| undefined),
},
...(sseAgent && { agent: sseAgent }),
}),
},
requestInit: {
headers: options.transport.requestOptions?.headers,
...(sseAgent && { agent: sseAgent }),
},
});
case "streamable-http":
const { url, requestOptions } = options.transport;
const streamableAgent =
requestOptions?.verifySsl === false
? new HttpsAgent({ rejectUnauthorized: false })
: undefined;
return new StreamableHTTPClientTransport(new URL(url), {
requestInit: {
headers: requestOptions?.headers,
...(streamableAgent && { agent: streamableAgent }),
},
});
default:
throw new Error(
`Unsupported transport type: ${(options.transport as any).type}`,
);
/**
* Resolves the current working directory of the current workspace.
* @param cwd The cwd parameter provided by user.
* @returns Current working directory (user-provided cwd or workspace root).
*/
private async resolveCwd(cwd?: string) {
if (!cwd) {
return this.resolveWorkspaceCwd(undefined);
}
if (cwd.startsWith("file://")) {
return fileURLToPath(cwd);
}
// Return cwd if cwd is an absolute path.
if (cwd.charAt(0) === "/") {
return cwd;
}
return this.resolveWorkspaceCwd(cwd);
}
private async resolveWorkspaceCwd(cwd: string | undefined) {
const IDE = this.extras?.ide;
if (IDE) {
const target = cwd ?? ".";
const resolved = await resolveRelativePathInDir(target, IDE);
if (resolved) {
if (resolved.startsWith("file://")) {
return fileURLToPath(resolved);
}
return resolved;
}
return resolved;
}
return cwd;
}
private constructWebsocketTransport(
options: InternalWebsocketMcpOptions,
): WebSocketClientTransport {
return new WebSocketClientTransport(new URL(options.url));
}
private constructSseTransport(
options: InternalSseMcpOptions,
): SSEClientTransport {
const sseAgent =
options.requestOptions?.verifySsl === false
? new HttpsAgent({ rejectUnauthorized: false })
: undefined;
// Merge apiKey into headers if provided
const headers = {
...options.requestOptions?.headers,
...(options.apiKey && { Authorization: `Bearer ${options.apiKey}` }),
};
return new SSEClientTransport(new URL(options.url), {
eventSourceInit: {
fetch: (input, init) =>
fetch(input, {
...init,
headers: {
...init?.headers,
...headers,
},
...(sseAgent && { agent: sseAgent }),
}),
},
requestInit: {
headers,
...(sseAgent && { agent: sseAgent }),
},
});
}
private constructHttpTransport(
options: InternalStreamableHttpMcpOptions,
): StreamableHTTPClientTransport {
const { url, requestOptions } = options;
const streamableAgent =
requestOptions?.verifySsl === false
? new HttpsAgent({ rejectUnauthorized: false })
: undefined;
// Merge apiKey into headers if provided
const headers = {
...requestOptions?.headers,
...(options.apiKey && { Authorization: `Bearer ${options.apiKey}` }),
};
return new StreamableHTTPClientTransport(new URL(url), {
requestInit: {
headers,
...(streamableAgent && { agent: streamableAgent }),
},
});
}
private async constructStdioTransport(
options: InternalStdioMcpOptions,
): Promise<StdioClientTransport> {
const commonEnvVars: Record<string, string> = Object.fromEntries(
COMMONS_ENV_VARS.filter((key) => process.env[key] !== undefined).map(
(key) => [key, process.env[key] as string],
),
);
const env = {
...commonEnvVars,
...(options.env ?? {}),
};
if (process.env.PATH !== undefined) {
// Set the initial PATH from process.env
env.PATH = process.env.PATH;
// For non-Windows platforms, try to get the PATH from user shell
if (process.platform !== "win32") {
try {
const shellEnvPath = await getEnvPathFromUserShell();
if (shellEnvPath && shellEnvPath !== process.env.PATH) {
env.PATH = shellEnvPath;
}
} catch (err) {
console.error("Error getting PATH:", err);
}
}
}
const { command, args } = this.resolveCommandForPlatform(
options.command,
options.args || [],
);
const cwd = await this.resolveCwd(options.cwd);
const transport = new StdioClientTransport({
command,
args,
env,
cwd,
stderr: "pipe",
});
// Capture stdio output for better error reporting
transport.stderr?.on("data", (data: Buffer) => {
this.stdioOutput.stderr += data.toString();
});
return transport;
}
}

View file

@ -1,5 +1,11 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
InternalSseMcpOptions,
InternalStdioMcpOptions,
InternalWebsocketMcpOptions,
} from "../..";
import * as ideUtils from "../../util/ideUtils";
import MCPConnection from "./MCPConnection";
// Mock the shell path utility
@ -16,15 +22,13 @@ describe("MCPConnection", () => {
describe("constructor", () => {
it("should create instance with stdio transport", () => {
const options = {
const options: InternalStdioMcpOptions = {
name: "test-mcp",
id: "test-id",
transport: {
type: "stdio" as const,
command: "test-cmd",
args: ["--test"],
env: { TEST: "true" },
},
type: "stdio",
command: "test-cmd",
args: ["--test"],
env: { TEST: "true" },
};
const conn = new MCPConnection(options);
@ -33,34 +37,30 @@ describe("MCPConnection", () => {
});
it("should create instance with stdio transport including cwd", () => {
const options = {
const options: InternalStdioMcpOptions = {
name: "test-mcp",
id: "test-id",
transport: {
type: "stdio" as const,
command: "test-cmd",
args: ["--test"],
env: { TEST: "true" },
cwd: "/path/to/working/directory",
},
type: "stdio",
command: "test-cmd",
args: ["--test"],
env: { TEST: "true" },
cwd: "/path/to/working/directory",
};
const conn = new MCPConnection(options);
expect(conn).toBeInstanceOf(MCPConnection);
expect(conn.status).toBe("not-connected");
if (conn.options.transport.type === "stdio") {
expect(conn.options.transport.cwd).toBe("/path/to/working/directory");
if (conn.options.type === "stdio") {
expect(conn.options.cwd).toBe("/path/to/working/directory");
}
});
it("should create instance with websocket transport", () => {
const options = {
const options: InternalWebsocketMcpOptions = {
name: "test-mcp",
id: "test-id",
transport: {
type: "websocket" as const,
url: "ws://test.com",
},
type: "websocket",
url: "ws://test.com",
};
const conn = new MCPConnection(options);
@ -69,13 +69,11 @@ describe("MCPConnection", () => {
});
it("should create instance with SSE transport", () => {
const options = {
const options: InternalSseMcpOptions = {
name: "test-mcp",
id: "test-id",
transport: {
type: "sse" as const,
url: "http://test.com/events",
},
type: "sse",
url: "http://test.com/events",
};
const conn = new MCPConnection(options);
@ -84,17 +82,15 @@ describe("MCPConnection", () => {
});
it("should create instance with SSE transport and custom headers", () => {
const options = {
const options: InternalSseMcpOptions = {
name: "test-mcp",
id: "test-id",
transport: {
type: "sse" as const,
url: "http://test.com/events",
requestOptions: {
headers: {
Authorization: "Bearer token123",
"X-Custom-Header": "custom-value",
},
type: "sse",
url: "http://test.com/events",
requestOptions: {
headers: {
Authorization: "Bearer token123",
"X-Custom-Header": "custom-value",
},
},
};
@ -108,9 +104,8 @@ describe("MCPConnection", () => {
const options = {
name: "test-mcp",
id: "test-id",
transport: {
type: "invalid",
} as any,
type: "invalid" as any,
url: "",
};
const conn = new MCPConnection(options);
@ -126,14 +121,12 @@ describe("MCPConnection", () => {
describe("getStatus", () => {
it("should return current status", () => {
const options = {
const options: InternalStdioMcpOptions = {
name: "test-mcp",
id: "test-id",
transport: {
type: "stdio" as const,
command: "test",
args: [],
},
type: "stdio",
command: "test",
args: [],
};
const conn = new MCPConnection(options);
@ -153,15 +146,44 @@ describe("MCPConnection", () => {
});
});
describe("connectClient", () => {
const options = {
describe("resolveCwd", () => {
const baseOptions = {
name: "test-mcp",
id: "test-id",
transport: {
type: "stdio" as const,
command: "test-cmd",
args: [],
},
type: "stdio" as const,
command: "test-cmd",
args: [],
};
it("should return absolute cwd unchanged", async () => {
const conn = new MCPConnection(baseOptions);
await expect((conn as any).resolveCwd("/tmp/project")).resolves.toBe(
"/tmp/project",
);
});
it("should resolve relative cwd using IDE workspace", async () => {
const ide = {} as any;
const mockResolve = vi
.spyOn(ideUtils, "resolveRelativePathInDir")
.mockResolvedValue("file:///workspace/src");
const conn = new MCPConnection(baseOptions, { ide });
await expect((conn as any).resolveCwd("src")).resolves.toBe(
"/workspace/src",
);
expect(mockResolve).toHaveBeenCalledWith("src", ide);
});
});
describe("connectClient", () => {
const options: InternalStdioMcpOptions = {
name: "test-mcp",
id: "test-id",
type: "stdio",
command: "test-cmd",
args: [],
};
it("should connect successfully", async () => {
@ -282,17 +304,15 @@ describe("MCPConnection", () => {
vi.restoreAllMocks();
// Use a command that will definitely fail and produce stderr output
const failingOptions = {
const failingOptions: InternalStdioMcpOptions = {
name: "failing-mcp",
id: "failing-id",
transport: {
type: "stdio" as const,
command: "node",
args: [
"-e",
"console.error('Custom error message from stderr'); process.exit(1);",
],
},
type: "stdio",
command: "node",
args: [
"-e",
"console.error('Custom error message from stderr'); process.exit(1);",
],
timeout: 5000, // Give enough time for the command to run and fail
};
@ -315,11 +335,9 @@ describe("MCPConnection", () => {
const conn = new MCPConnection({
id: "filesystem",
name: "Filesystem",
transport: {
type: "stdio" as const,
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "."],
},
type: "stdio",
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "."],
});
try {

View file

@ -1,11 +1,6 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import {
MCPOptions,
MCPServerStatus,
StdioOptions,
TransportOptions,
} from "../..";
import { InternalMcpOptions, MCPServerStatus } from "../..";
import MCPConnection, { MCPExtras } from "./MCPConnection";
export class MCPManagerSingleton {
@ -25,7 +20,23 @@ export class MCPManagerSingleton {
return MCPManagerSingleton.instance;
}
createConnection(id: string, options: MCPOptions): MCPConnection {
async setEnabled(serverId: string, enabled: boolean) {
const conn = this.connections.get(serverId);
if (conn) {
if (enabled) {
conn.status = "not-connected";
await this.refreshConnection(serverId);
} else {
try {
await conn.disconnect(true);
} catch (e) {
console.error(`Error disconnecting from MCP server ${serverId}`, e);
}
}
}
}
createConnection(id: string, options: InternalMcpOptions): MCPConnection {
if (this.connections.has(id)) {
return this.connections.get(id)!;
} else {
@ -39,15 +50,6 @@ export class MCPManagerSingleton {
return this.connections.get(id);
}
async removeConnection(id: string) {
const connection = this.connections.get(id);
if (connection) {
await connection.client.close();
}
this.connections.delete(id);
}
async shutdown() {
if (this.connections.size > 0) {
await Promise.allSettled(
@ -64,7 +66,7 @@ export class MCPManagerSingleton {
}
setConnections(
servers: MCPOptions[],
servers: InternalMcpOptions[],
forceRefresh: boolean,
extras?: MCPExtras,
) {
@ -76,11 +78,7 @@ export class MCPManagerSingleton {
!servers.find(
// Refresh the connection if TransportOptions changed
(s) =>
s.id === id &&
this.compareTransportOptions(
connection.options.transport,
s.transport,
),
s.id === id && this.compareTransportOptions(connection.options, s),
)
) {
refresh = true;
@ -111,33 +109,35 @@ export class MCPManagerSingleton {
}
private compareTransportOptions(
a: TransportOptions,
b: TransportOptions,
a: InternalMcpOptions,
b: InternalMcpOptions,
): boolean {
if (a.type !== b.type) {
return false;
}
if (a.type === "stdio" && b.type === "stdio") {
if ("command" in a && "command" in b) {
return (
a.command === b.command &&
JSON.stringify(a.args) === JSON.stringify(b.args) &&
this.compareEnv(a, b)
this.compareEnv(a.env, b.env)
);
} else if (a.type !== "stdio" && b.type !== "stdio") {
} else if ("url" in a && "url" in b) {
return a.url === b.url;
}
return false;
}
private compareEnv(a: StdioOptions, b: StdioOptions): boolean {
const aEnv = a.env ?? {};
const bEnv = b.env ?? {};
const aKeys = Object.keys(aEnv);
const bKeys = Object.keys(bEnv);
private compareEnv(
aEnv: Record<string, string> | undefined,
bEnv: Record<string, string> | undefined,
): boolean {
const a = aEnv ?? {};
const b = bEnv ?? {};
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
return (
aKeys.length === bKeys.length &&
aKeys.every((key) => aEnv[key] === bEnv[key])
aKeys.length === bKeys.length && aKeys.every((key) => a[key] === b[key])
);
}
@ -181,8 +181,8 @@ export class MCPManagerSingleton {
}));
}
setStatus(server: MCPServerStatus, status: MCPServerStatus["status"]) {
this.connections.get(server.id)!.status = status;
setStatus(serverId: string, status: MCPServerStatus["status"]) {
this.connections.get(serverId)!.status = status;
}
async getPrompt(

View file

@ -1,11 +1,11 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { MCPOptions } from "../..";
import { InternalMcpOptions } from "../..";
import MCPConnection from "./MCPConnection";
import { MCPManagerSingleton } from "./MCPManagerSingleton";
// Create test versions with stubbed behavior
class TestMCPConnection extends MCPConnection {
constructor(options: MCPOptions) {
constructor(options: InternalMcpOptions) {
super(options);
// Override with test implementations
@ -28,14 +28,12 @@ class TestMCPConnection extends MCPConnection {
describe("MCPManagerSingleton", () => {
let manager: MCPManagerSingleton;
const testOptions: MCPOptions = {
const testOptions: InternalMcpOptions = {
name: "test-mcp",
id: "test-id",
transport: {
type: "stdio",
command: "test-command",
args: [],
},
type: "stdio",
command: "test-command",
args: [],
};
beforeEach(() => {
@ -53,7 +51,7 @@ describe("MCPManagerSingleton", () => {
// Override createConnection to use our TestMCPConnection
manager.createConnection = function (
id: string,
options: MCPOptions,
options: InternalMcpOptions,
): MCPConnection {
if (this.connections.has(id)) {
return this.connections.get(id)!;
@ -96,28 +94,6 @@ describe("MCPManagerSingleton", () => {
});
});
describe("removeConnection", () => {
it("should remove connection and close client", async () => {
// Create a spy on the close method
const connection = manager.createConnection(
"test-id",
testOptions,
) as TestMCPConnection;
const closeSpy = vi.spyOn(connection.client, "close");
await manager.removeConnection("test-id");
expect(closeSpy).toHaveBeenCalled();
expect(manager.getConnection("test-id")).toBeUndefined();
});
it("should handle non-existent connection", async () => {
await expect(
manager.removeConnection("non-existent"),
).resolves.toBeUndefined();
});
});
describe("setConnections", () => {
it("should add new connections", () => {
const servers = [testOptions];

View file

@ -8,69 +8,123 @@ import {
OAuthTokens,
OAuthTokensSchema,
} from "@modelcontextprotocol/sdk/shared/auth.js";
import { IDE, MCPServerStatus, SSEOptions } from "../..";
import { IDE } from "../..";
import http from "http";
import url from "url";
import { v4 as uuidv4 } from "uuid";
import { GlobalContext, GlobalContextType } from "../../util/GlobalContext";
let authenticatingMCPContext = null as {
authenticatingServer: MCPServerStatus;
// Use a Map to support concurrent authentications for different servers
interface MCPOauthContext {
serverId: string;
ide: IDE;
} | null;
state?: string;
}
const authenticatingContexts = new Map<string, MCPOauthContext>();
// Map state parameters to server URLs for OAuth callback matching
const stateToServerUrl = new Map<string, string>();
const PORT = 3000;
const server = http.createServer((req, res) => {
try {
if (!req.url) {
throw new Error("no url found");
}
let serverInstance: http.Server | null = null;
const parsedUrl = url.parse(req.url, true);
if (!parsedUrl.query["code"]) {
throw new Error("no query params found");
}
const createServerForOAuth = () =>
http.createServer((req, res) => {
try {
if (!req.url) {
throw new Error("no url found");
}
void handleMCPOauthCode(parsedUrl.query["code"] as string);
const parsedUrl = url.parse(req.url, true);
if (!parsedUrl.query["code"]) {
throw new Error("no query params found");
}
const html = `
const code = parsedUrl.query["code"] as string;
const state = parsedUrl.query["state"] as string | undefined;
void handleMCPOauthCode(code, state);
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}`);
}
});
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;
private _redirectUrl: string;
private _redirectUrlInitialized: Promise<void>;
constructor(
public oauthServerUrl: string,
private ide: IDE,
) {
this.globalContext = new GlobalContext();
// Set default redirect URL immediately for synchronous access
this._redirectUrl = `http://localhost:${PORT}`;
// Initialize actual redirect URL asynchronously
this._redirectUrlInitialized = this._initializeRedirectUrl();
}
private async _initializeRedirectUrl(): Promise<void> {
try {
// If IDE supports getExternalUri (VS Code extension), use it for dynamic redirect URI
if (this.ide.getExternalUri) {
const localUri = `http://localhost:${PORT}`;
const externalUri = await this.ide.getExternalUri(localUri);
this._redirectUrl = externalUri;
}
// Otherwise keep the default localhost URL
} catch (error) {
console.error("Failed to initialize redirect URL:", error);
// Keep default URL on error
}
}
get redirectUrl() {
return `http://localhost:${PORT}`; // TODO: this has to be a hub url or should we spin up a server?
// Always return a valid URL, even if initialization is pending
return this._redirectUrl;
}
getRedirectUrlWithState(state: string): string {
// Add state parameter to redirect URL
const urlObj = new URL(this._redirectUrl);
urlObj.searchParams.set("state", state);
return urlObj.toString();
}
async ensureRedirectUrl(): Promise<string> {
// Wait for initialization to complete before returning
await this._redirectUrlInitialized;
return this._redirectUrl;
}
get clientMetadata() {
// Generate state parameter if needed
const state = authenticatingContexts.get(this.oauthServerUrl)?.state;
const redirectUri = state
? this.getRedirectUrlWithState(state)
: this.redirectUrl;
return {
redirect_uris: [this.redirectUrl],
redirect_uris: [redirectUri],
token_endpoint_auth_method: "none",
grant_types: ["authorization_code", "refresh_token"],
response_types: ["code"],
@ -151,14 +205,28 @@ class MCPConnectionOauthProvider implements OAuthClientProvider {
}
async redirectToAuthorization(authorizationUrl: URL) {
if (!server.listening) {
server.listen(PORT, () => {
console.debug(
`Server started for MCP Oauth process at http://localhost:${PORT}/`,
);
});
// Ensure redirect URL is initialized before proceeding
await this.ensureRedirectUrl();
// Only create and start local server if using localhost redirect
// For web-based VS Code, the redirect will be handled by VS Code's built-in mechanism
if (!this.ide.getExternalUri || this._redirectUrl.includes("localhost")) {
if (!serverInstance) {
serverInstance = createServerForOAuth();
}
if (!serverInstance.listening) {
await new Promise<void>((resolve, reject) => {
serverInstance!.listen(PORT, () => {
console.debug(
`Server started for MCP Oauth process at http://localhost:${PORT}/`,
);
resolve();
});
serverInstance!.on("error", reject);
});
}
}
void this.ide.openUrl(authorizationUrl.toString());
await this.ide.openUrl(authorizationUrl.toString());
}
}
@ -172,56 +240,110 @@ export async function getOauthToken(mcpServerUrl: string, ide: IDE) {
* 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,
export async function performAuth(serverId: string, url: string, ide: IDE) {
const authProvider = new MCPConnectionOauthProvider(url, ide);
// Ensure redirect URL is ready before starting auth
await authProvider.ensureRedirectUrl();
// Generate a unique state parameter for this auth flow
const state = uuidv4();
// Store context for this specific server with state
authenticatingContexts.set(url, {
serverId,
ide,
};
return await auth(authProvider, {
serverUrl: mcpServerUrl,
state,
});
// Map state to server URL for callback matching
stateToServerUrl.set(state, url);
try {
return await auth(authProvider, {
serverUrl: url,
});
} catch (error) {
// Clean up on error
authenticatingContexts.delete(url);
stateToServerUrl.delete(state);
throw error;
}
}
/**
* 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;
async function handleMCPOauthCode(authorizationCode: string, state?: string) {
let serverUrl: string | undefined;
let context: MCPOauthContext | undefined;
if (!serverUrl) {
void ide.showToast("error", "No MCP server url found for authentication");
if (state) {
// Use state parameter to find the correct server
serverUrl = stateToServerUrl.get(state);
if (serverUrl) {
context = authenticatingContexts.get(serverUrl);
}
} else {
// Fallback: if no state or single context, use the first one
const contexts = Array.from(authenticatingContexts.entries());
if (contexts.length === 1) {
[serverUrl, context] = contexts[0];
}
}
if (!context || !serverUrl) {
console.error("No matching authenticating context found for state:", state);
return;
}
if (!authorizationCode) {
void ide.showToast(
"error",
`No MCP authorization code found for ${serverUrl}`,
);
return;
const { ide, serverId } = context;
try {
if (!serverUrl) {
throw new Error("No MCP server url found for authentication");
}
if (!authorizationCode) {
throw new Error(`No MCP authorization code found for ${serverUrl}`);
}
// Close the server before processing auth
if (serverInstance) {
await new Promise<void>((resolve) => {
serverInstance!.close(() => {
console.debug("Server for MCP Oauth process was closed");
serverInstance = null;
resolve();
});
});
}
const authProvider = new MCPConnectionOauthProvider(serverUrl, ide);
await authProvider.ensureRedirectUrl();
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(serverId);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error("OAuth authorization failed:", errorMessage);
if (context?.ide) {
await context.ide.showToast("error", `OAuth failed: ${errorMessage}`);
}
} finally {
// Always clean up the context and state mapping
authenticatingContexts.delete(serverUrl);
if (state) {
stateToServerUrl.delete(state);
}
}
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);
export function removeMCPAuth(url: string, ide: IDE) {
const authProvider = new MCPConnectionOauthProvider(url, ide);
authProvider.clear();
}

View file

@ -21,7 +21,8 @@ vi.mock("./MCPManagerSingleton", () => ({
describe("MCPOauth", () => {
let globalContextFilePath: string;
let mockIde: any;
let mockMcpServer: any;
let mockMcpServerId: string;
let mockMcpServerUrl: string;
beforeEach(() => {
// file is present in the core/test directory
@ -33,15 +34,11 @@ describe("MCPOauth", () => {
mockIde = {
openUrl: vi.fn(),
showToast: vi.fn(),
getExternalUri: vi.fn((uri) => Promise.resolve(uri)),
};
mockMcpServer = {
id: "test-server",
transport: {
type: "sse",
url: "https://test-server.com",
},
};
mockMcpServerId = "test-server";
mockMcpServerUrl = "https://test-server.com";
vi.clearAllMocks();
});
@ -106,7 +103,11 @@ describe("MCPOauth", () => {
const mockAuth = vi.mocked(auth);
mockAuth.mockResolvedValue("AUTHORIZED");
const result = await performAuth(mockMcpServer, mockIde);
const result = await performAuth(
mockMcpServerId,
mockMcpServerUrl,
mockIde,
);
expect(mockAuth).toHaveBeenCalledWith(
expect.any(Object), // MCPConnectionOauthProvider instance
@ -141,7 +142,7 @@ describe("MCPOauth", () => {
},
});
removeMCPAuth(mockMcpServer, mockIde);
removeMCPAuth(mockMcpServerUrl, mockIde);
const updatedStorage = globalContext.get("mcpOauthStorage");
expect(updatedStorage).toEqual({
@ -165,7 +166,7 @@ describe("MCPOauth", () => {
},
});
removeMCPAuth(mockMcpServer, mockIde);
removeMCPAuth(mockMcpServerUrl, mockIde);
const updatedStorage = globalContext.get("mcpOauthStorage");
expect(updatedStorage).toEqual({
@ -178,4 +179,122 @@ describe("MCPOauth", () => {
});
});
});
describe("redirect URL handling", () => {
test("should use getExternalUri when available for VS Code", async () => {
const vscodeIde = {
...mockIde,
getExternalUri: vi.fn((uri) =>
Promise.resolve("https://vscode.dev/redirect"),
),
};
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
const mockAuth = vi.mocked(auth);
mockAuth.mockResolvedValue("AUTHORIZED");
await performAuth(mockMcpServerId, mockMcpServerUrl, vscodeIde);
expect(vscodeIde.getExternalUri).toHaveBeenCalledWith(
"http://localhost:3000",
);
});
test("should fallback to localhost when getExternalUri is not available", async () => {
const ideWithoutExternalUri = {
openUrl: vi.fn(() => Promise.resolve()),
showToast: vi.fn(() => Promise.resolve()),
};
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
const mockAuth = vi.mocked(auth);
mockAuth.mockResolvedValue("AUTHORIZED");
await performAuth(
mockMcpServerId,
mockMcpServerUrl,
ideWithoutExternalUri as any,
);
// Should still work without getExternalUri
expect(mockAuth).toHaveBeenCalled();
});
test("should handle getExternalUri errors gracefully", async () => {
const errorIde = {
...mockIde,
getExternalUri: vi.fn(() => Promise.reject(new Error("Network error"))),
};
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
const mockAuth = vi.mocked(auth);
mockAuth.mockResolvedValue("AUTHORIZED");
// Should not throw, should fallback to localhost
await performAuth(mockMcpServerId, mockMcpServerUrl, errorIde);
expect(mockAuth).toHaveBeenCalled();
});
});
describe("concurrent authentication", () => {
test("should handle multiple concurrent auth flows", async () => {
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
const mockAuth = vi.mocked(auth);
mockAuth.mockResolvedValue("AUTHORIZED");
// Start two auth flows concurrently
const [result1, result2] = await Promise.all([
performAuth("server-1-id", "https://server1.com", mockIde),
performAuth("server-2-id", "https://server2.com", mockIde),
]);
expect(result1).toBe("AUTHORIZED");
expect(result2).toBe("AUTHORIZED");
expect(mockAuth).toHaveBeenCalledTimes(2);
});
});
describe("error handling", () => {
test("should clean up context on auth failure", async () => {
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
const mockAuth = vi.mocked(auth);
// First successful call to set up the context
mockAuth.mockResolvedValueOnce("AUTHORIZED");
await performAuth(mockMcpServerId, mockMcpServerUrl, mockIde);
// Reset mock for the failure test
mockAuth.mockRejectedValueOnce(new Error("Auth failed"));
// Second call that should fail and clean up
await expect(
performAuth(mockMcpServerId, mockMcpServerUrl, mockIde),
).rejects.toThrow("Auth failed");
// Verify auth was called twice
expect(mockAuth).toHaveBeenCalledTimes(2);
// The context cleanup happens internally in performAuth's catch block
// We can verify it indirectly by checking that a subsequent auth call works
mockAuth.mockResolvedValueOnce("AUTHORIZED");
const result = await performAuth(
mockMcpServerId,
mockMcpServerUrl,
mockIde,
);
expect(result).toBe("AUTHORIZED");
});
test("should handle missing server URL", async () => {
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
const mockAuth = vi.mocked(auth);
mockAuth.mockResolvedValue("AUTHORIZED");
await performAuth("invalid-id", "", mockIde);
// Should still attempt auth with empty URL
expect(mockAuth).toHaveBeenCalled();
});
});
});

View file

@ -0,0 +1,205 @@
import {
claudeCodeLikeConfigFileSchema,
claudeDesktopLikeConfigFileSchema,
ConfigValidationError,
convertJsonMcpConfigToYamlMcpConfig,
McpJsonConfig,
mcpServersJsonSchema,
RequestOptions,
} from "@continuedev/config-yaml";
import * as JSONC from "comment-json";
import ignore from "ignore";
import { IDE, InternalMcpOptions } from "../../..";
import { convertYamlMcpConfigToInternalMcpOptions } from "../../../config/yaml/yamlToContinueConfig";
import {
DEFAULT_IGNORE_DIRS,
DEFAULT_IGNORE_FILETYPES,
} from "../../../indexing/ignore";
import { walkDir } from "../../../indexing/walkDir";
import { deduplicateArray } from "../../../util";
import { getGlobalFolderWithName } from "../../../util/paths";
import { localPathToUri } from "../../../util/pathToUri";
import { getUriPathBasename, joinPathsToUri } from "../../../util/uri";
/**
* Loads MCP configs from JSON files in ~/.continue/mcpServers and workspace .continue/mcpServers
*/
export async function loadJsonMcpConfigs(
ide: IDE,
includeGlobal: boolean,
globalRequestOptions: RequestOptions | undefined = undefined,
): Promise<{
mcpServers: InternalMcpOptions[];
errors: ConfigValidationError[];
}> {
const errors: ConfigValidationError[] = [];
// Get dirs
const workspaceDirs = await ide.getWorkspaceDirs();
const mcpDirs = workspaceDirs.map((dir) =>
joinPathsToUri(dir, ".continue", "mcpServers"),
);
if (includeGlobal) {
mcpDirs.push(localPathToUri(getGlobalFolderWithName("mcpServers")));
}
// Get json files and their contents
const overrideDefaultIgnores = ignore()
.add(
DEFAULT_IGNORE_FILETYPES.filter(
(val) => !["config.json", "settings.json"].includes(val),
),
)
.add(DEFAULT_IGNORE_DIRS);
const jsonFiles: { uri: string; content: string }[] = [];
await Promise.all(
mcpDirs.map(async (dir) => {
const exists = await ide.fileExists(dir);
if (!exists) {
return;
}
try {
const uris = await walkDir(dir, ide, {
overrideDefaultIgnores,
source: "get mcp json files",
});
const jsonUris = uris.filter((uri) => uri.endsWith(".json"));
await Promise.all(
jsonUris.map(async (uri) => {
try {
const content = await ide.readFile(uri);
jsonFiles.push({ uri, content });
} catch (e) {
errors.push({
fatal: false,
message: `Failed to read MCP server JSON file at ${uri}: ${e instanceof Error ? e.message : String(e)}`,
});
}
}),
);
} catch (e) {
errors.push({
fatal: false,
message: `Failed to check for MCP JSON files in ${dir}: ${e instanceof Error ? e.message : String(e)}`,
});
}
}),
);
const validJsonConfigs: {
name: string;
mcpJson: McpJsonConfig;
uri: string;
}[] = [];
for (const { content, uri } of jsonFiles) {
try {
const json = JSONC.parse(content);
// Try parsing as a file with mcpServers and multiple servers (claude code/desktop-esque format)
const claudeCodeFileParsed =
claudeCodeLikeConfigFileSchema.safeParse(json);
if (claudeCodeFileParsed.success) {
if (claudeCodeFileParsed.data.mcpServers) {
validJsonConfigs.push(
...Object.entries(claudeCodeFileParsed.data.mcpServers).map(
([name, mcpJson]) => ({
name,
mcpJson,
uri,
}),
),
);
}
const projectServers = Object.values(
claudeCodeFileParsed.data.projects,
).map((v) => v.mcpServers);
for (const mcpServers of projectServers) {
if (mcpServers) {
validJsonConfigs.push(
...Object.entries(mcpServers).map(([name, mcpJson]) => ({
name,
mcpJson,
uri,
})),
);
}
}
} else {
const claudeDesktopFileParsed =
claudeDesktopLikeConfigFileSchema.safeParse(json);
if (claudeDesktopFileParsed.success) {
validJsonConfigs.push(
...Object.entries(claudeDesktopFileParsed.data.mcpServers).map(
([name, mcpJson]) => ({
name,
mcpJson,
uri,
}),
),
);
} else {
// Try parsing as single JSON file
const singleConfigParsed = mcpServersJsonSchema.safeParse(json);
if (singleConfigParsed.success) {
validJsonConfigs.push({
mcpJson: singleConfigParsed.data,
name: getUriPathBasename(uri).replace(".json", ""),
uri,
});
} else {
errors.push({
fatal: false,
message: `MCP JSON file at ${uri} doesn't match a supported MCP JSON configuration format`,
});
}
}
}
} catch (e) {
errors.push({
fatal: false,
message: `Error parsing MCP JSON file at ${uri}: ${e instanceof Error ? e.message : String(e)}`,
});
}
}
// De-duplicate
const deduplicatedJsonConfigs = deduplicateArray(
validJsonConfigs,
(a, b) => a.name === b.name,
);
// Two levels of conversion for now.
const yamlConfigs = deduplicatedJsonConfigs.map((c) => {
const { warnings, yamlConfig } = convertJsonMcpConfigToYamlMcpConfig(
c.name,
c.mcpJson,
);
return {
warnings,
yamlConfig: {
...yamlConfig,
sourceFile: c.uri,
},
};
});
const mcpServers = yamlConfigs.map((c) => {
errors.push(
...c.warnings.map((warning) => ({
fatal: false,
message: warning,
uri: c.yamlConfig.sourceFile,
})),
);
return convertYamlMcpConfigToInternalMcpOptions(
c.yamlConfig,
globalRequestOptions,
);
});
// Parse and convert files
return {
mcpServers,
errors,
};
}

View file

@ -0,0 +1,206 @@
/**
* Tests for HttpContextProvider - specifically testing the fix for v1.0.19
* where missing or null uri fields in server responses caused TypeErrors.
*
* The fix uses conditional access (item.uri &&) to safely handle null/undefined uri fields.
*/
import { ContextProviderExtras } from "../../index.js";
import HttpContextProvider from "./HttpContextProvider.js";
describe("HttpContextProvider", () => {
let provider: HttpContextProvider;
let mockExtras: ContextProviderExtras;
beforeEach(() => {
provider = new HttpContextProvider({
title: "Test HTTP Provider",
url: "http://localhost:3000/context",
});
mockExtras = {
fullInput: "test input",
fetch: jest.fn(),
ide: {
getCurrentFile: jest.fn().mockResolvedValue({ path: "/test/file.ts" }),
getWorkspaceDirs: jest.fn().mockResolvedValue(["/test/"]),
} as any,
config: {} as any,
embeddingsProvider: null,
reranker: null,
llm: {} as any,
selectedCode: [],
isInAgentMode: false,
};
});
describe("getContextItems", () => {
it("should handle response with valid uri field", async () => {
const mockResponse = {
json: jest.fn().mockResolvedValue({
description: "Test item",
content: "Test content",
name: "Test",
uri: {
type: "file",
value: "/test/file.ts",
},
}),
};
(mockExtras.fetch as jest.Mock).mockResolvedValue(mockResponse);
const result = await provider.getContextItems("test query", mockExtras);
expect(result).toHaveLength(1);
expect(result[0]).toEqual({
description: "Test item",
content: "Test content",
name: "Test",
uri: {
type: "file",
value: "/test/file.ts",
},
});
});
it("should handle response with null uri field", async () => {
const mockResponse = {
json: jest.fn().mockResolvedValue({
description: "Test item",
content: "Test content",
name: "Test",
uri: null,
}),
};
(mockExtras.fetch as jest.Mock).mockResolvedValue(mockResponse);
const result = await provider.getContextItems("test query", mockExtras);
expect(result).toHaveLength(1);
expect(result[0]).toEqual({
description: "Test item",
content: "Test content",
name: "Test",
uri: null, // Should be null when uri is null (logical AND with null returns null)
});
});
``;
it("should handle response with missing uri field", async () => {
const mockResponse = {
json: jest.fn().mockResolvedValue({
description: "Test item",
content: "Test content",
name: "Test",
// uri field is completely missing
}),
};
(mockExtras.fetch as jest.Mock).mockResolvedValue(mockResponse);
const result = await provider.getContextItems("test query", mockExtras);
expect(result).toHaveLength(1);
expect(result[0]).toEqual({
description: "Test item",
content: "Test content",
name: "Test",
uri: undefined, // Should be undefined when uri is missing
});
});
it("should handle array response with mixed uri fields", async () => {
const mockResponse = {
json: jest.fn().mockResolvedValue([
{
description: "Item with uri",
content: "Content 1",
name: "Item1",
uri: {
type: "file",
value: "/test/file1.ts",
},
},
{
description: "Item without uri",
content: "Content 2",
name: "Item2",
// uri field missing
},
{
description: "Item with null uri",
content: "Content 3",
name: "Item3",
uri: null,
},
]),
};
(mockExtras.fetch as jest.Mock).mockResolvedValue(mockResponse);
const result = await provider.getContextItems("test query", mockExtras);
expect(result).toHaveLength(3);
expect(result[0].uri).toEqual({ type: "file", value: "/test/file1.ts" });
expect(result[1].uri).toBeUndefined();
expect(result[2].uri).toBeNull(); // null uri becomes null
});
it("should use default values for missing fields", async () => {
const mockResponse = {
json: jest.fn().mockResolvedValue({
// All fields missing except uri
uri: {
type: "file",
value: "/test/file.ts",
},
}),
};
(mockExtras.fetch as jest.Mock).mockResolvedValue(mockResponse);
const result = await provider.getContextItems("test query", mockExtras);
expect(result).toHaveLength(1);
expect(result[0]).toEqual({
description: "HTTP Context Item", // default value
content: "", // default value
name: "Test HTTP Provider", // from provider options
uri: {
type: "file",
value: "/test/file.ts",
},
});
});
it("should handle partial uri objects gracefully", async () => {
const mockResponse = {
json: jest.fn().mockResolvedValue({
description: "Test item",
content: "Test content",
name: "Test",
uri: {
type: "file",
// missing value field - our fix should handle this gracefully
},
}),
};
(mockExtras.fetch as jest.Mock).mockResolvedValue(mockResponse);
const result = await provider.getContextItems("test query", mockExtras);
expect(result).toHaveLength(1);
expect(result[0]).toEqual({
description: "Test item",
content: "Test content",
name: "Test",
uri: {
type: "file",
value: undefined, // value is undefined when missing
},
});
});
});
});

View file

@ -72,7 +72,7 @@ class HttpContextProvider extends BaseContextProvider {
description: item.description ?? "HTTP Context Item",
content: item.content ?? "",
name: item.name ?? this.options.title ?? "HTTP",
uri: {
uri: item.uri && {
type: item.uri.type,
value: item.uri.value,
},

View file

@ -22,11 +22,11 @@ class RulesContextProvider extends BaseContextProvider {
// This is only used within this class. Worst case if there are exact duplicates is that one always calls the other, but this is an extreme edge case
// Can eventually pull in more metadata, but this is experimental
private getIdFromRule(rule: RuleWithSource): string {
return rule.ruleFile ?? rule.slug ?? rule.name ?? rule.rule;
return rule.slug ?? rule.sourceFile ?? rule.name ?? rule.rule;
}
private getNameFromRule(rule: RuleWithSource): string {
return rule.name ?? rule.slug ?? rule.ruleFile ?? rule.source;
return rule.name ?? rule.slug ?? rule.sourceFile ?? rule.source;
}
private getDescriptionFromRule(rule: RuleWithSource): string {
@ -37,10 +37,10 @@ class RulesContextProvider extends BaseContextProvider {
rule: RuleWithSource,
appUrl: string,
): ContextItemUri | undefined {
if (rule.ruleFile) {
if (rule.sourceFile) {
return {
type: "file",
value: rule.ruleFile,
value: rule.sourceFile,
};
}

View file

@ -33,39 +33,40 @@ export async function getUrlContextItems(
query: string,
fetchFn: FetchFunction,
): Promise<ContextItem[]> {
try {
const url = new URL(query);
const icon = await fetchFavicon(url);
const resp = await fetchFn(url);
const html = await resp.text();
const url = new URL(query);
const icon = await fetchFavicon(url);
const resp = await fetchFn(url);
const dom = new JSDOM(html);
let reader = new Readability(dom.window.document);
let article = reader.parse();
const content = article?.content || "";
const markdown = NodeHtmlMarkdown.translate(
content,
{},
undefined,
undefined,
);
const title = article?.title || url.pathname;
return [
{
icon,
description: url.toString(),
content: markdown,
name: title,
uri: {
type: "url",
value: url.toString(),
},
},
];
} catch (e) {
console.log(e);
return [];
// Check if the response is not OK
if (!resp.ok) {
throw new Error(`HTTP ${resp.status} ${resp.statusText}`);
}
const html = await resp.text();
const dom = new JSDOM(html);
let reader = new Readability(dom.window.document);
let article = reader.parse();
const content = article?.content || "";
const markdown = NodeHtmlMarkdown.translate(
content,
{},
undefined,
undefined,
);
const title = article?.title || url.pathname;
return [
{
icon,
description: url.toString(),
content: markdown,
name: title,
uri: {
type: "url",
value: url.toString(),
},
},
];
}

View file

@ -8,7 +8,7 @@ const SUPPORTED_MODEL_TITLE_FAMILIES = [
"claude-3",
"llama3.1",
"llama3.2",
"gemini-1.5",
"gemini-2.5",
"gpt-4",
];

View file

@ -12,10 +12,10 @@ import fetch, { RequestInit, Response } from "node-fetch";
import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
import {
BaseSessionMetadata,
IDE,
ModelDescription,
Session,
BaseSessionMetadata,
} from "../index.js";
import { Logger } from "../util/Logger.js";
@ -39,12 +39,11 @@ export interface ControlPlaneWorkspace {
export interface ControlPlaneModelDescription extends ModelDescription {}
export interface FreeTrialStatus {
export interface CreditStatus {
optedInToFreeTrial: boolean;
chatCount?: number;
autocompleteCount?: number;
chatLimit: number;
autocompleteLimit: number;
hasCredits: boolean;
creditBalance: number;
hasPurchasedCredits: boolean;
}
export const TRIAL_PROXY_URL =
@ -55,6 +54,39 @@ export interface RemoteSessionMetadata extends BaseSessionMetadata {
remoteId: string;
}
export interface AgentSessionMetadata {
createdBy: string;
github_repo: string;
organizationId?: string;
idempotencyKey?: string;
source?: string;
continueApiKeyId?: string;
s3Url?: string;
prompt?: string | null;
createdBySlug?: string;
}
export interface AgentSessionView {
id: string;
devboxId: string | null;
name: string | null;
icon: string | null;
status: string;
agentStatus: string | null;
unread: boolean;
state: string;
metadata: AgentSessionMetadata;
repoUrl: string;
branch: string | null;
pullRequestUrl: string | null;
pullRequestStatus: string | null;
tunnelUrl: string | null;
createdAt: string;
updatedAt: string;
create_time_ms: string;
end_time_ms: string;
}
export class ControlPlaneClient {
constructor(
readonly sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
@ -260,20 +292,20 @@ export class ControlPlaneClient {
}
}
public async getFreeTrialStatus(): Promise<FreeTrialStatus | null> {
public async getCreditStatus(): Promise<CreditStatus | null> {
if (!(await this.isSignedIn())) {
return null;
}
try {
const resp = await this.requestAndHandleError("ide/free-trial-status", {
const resp = await this.requestAndHandleError("ide/credits", {
method: "GET",
});
return (await resp.json()) as FreeTrialStatus;
return (await resp.json()) as CreditStatus;
} catch (e) {
// Capture control plane API failures to Sentry
Logger.error(e, {
context: "control_plane_free_trial_status",
context: "control_plane_credit_status",
});
return null;
}
@ -320,7 +352,6 @@ export class ControlPlaneClient {
/**
* Check if remote sessions should be enabled based on feature flags
* Requires: PostHog feature flag AND @continue.dev email
*/
public async shouldEnableRemoteSessions(): Promise<boolean> {
// Check if user is signed in
@ -328,17 +359,13 @@ export class ControlPlaneClient {
return false;
}
// Check if user has @continue.dev email
try {
const sessionInfo = await this.sessionInfoPromise;
if (isOnPremSession(sessionInfo) || !sessionInfo) {
return false;
}
const hubSession = sessionInfo as HubSessionInfo;
const email = hubSession.account?.id;
return email ? email.includes("@continue.dev") : false;
return true;
} catch (e) {
Logger.error(e, {
context: "control_plane_check_remote_sessions_enabled",
@ -356,7 +383,6 @@ export class ControlPlaneClient {
/**
* Fetch remote agents/sessions from the control plane
* Currently restricted to @continue.dev emails for internal use
*/
public async listRemoteSessions(): Promise<RemoteSessionMetadata[]> {
if (!(await this.isSignedIn())) {
@ -364,8 +390,6 @@ export class ControlPlaneClient {
}
try {
// Note: This endpoint is currently restricted to internal @continue.dev users
// In the future, this may be expanded to support broader remote session access
const resp = await this.requestAndHandleError("agents/devboxes", {
method: "GET",
});
@ -440,4 +464,203 @@ export class ControlPlaneClient {
);
}
}
/**
* Create a new background agent
*/
public async createBackgroundAgent(
prompt: string,
repoUrl: string,
name: string,
branch?: string,
organizationId?: string,
contextItems?: any[],
selectedCode?: any[],
agent?: string,
): Promise<{ id: string }> {
if (!(await this.isSignedIn())) {
throw new Error("Not signed in to Continue");
}
const requestBody: any = {
prompt,
repoUrl,
name,
branchName: branch,
};
if (organizationId) {
requestBody.organizationId = organizationId;
}
// Include context items if provided
if (contextItems && contextItems.length > 0) {
requestBody.contextItems = contextItems.map((item) => ({
content: item.content,
description: item.description,
name: item.name,
uri: item.uri,
}));
}
// Include selected code if provided
if (selectedCode && selectedCode.length > 0) {
requestBody.selectedCode = selectedCode.map((code) => ({
filepath: code.filepath,
range: code.range,
contents: code.contents,
}));
}
// Include agent configuration if provided
if (agent) {
requestBody.agent = agent;
}
const resp = await this.requestAndHandleError("agents", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
});
return (await resp.json()) as { id: string };
}
/**
* List all background agents for the current user or organization
* @param organizationId - Optional organization ID to filter agents by organization scope
* @param limit - Optional limit for number of agents to return (default: 5)
*/
public async listBackgroundAgents(
organizationId?: string,
limit?: number,
): Promise<{
agents: Array<{
id: string;
name: string | null;
status: string;
repoUrl: string;
createdAt: string;
metadata?: {
github_repo?: string;
};
}>;
totalCount: number;
}> {
if (!(await this.isSignedIn())) {
return { agents: [], totalCount: 0 };
}
try {
// Build URL with query parameters
const params = new URLSearchParams();
if (organizationId) {
params.set("organizationId", organizationId);
}
if (limit !== undefined) {
params.set("limit", limit.toString());
}
const url = `agents${params.toString() ? `?${params.toString()}` : ""}`;
const resp = await this.requestAndHandleError(url, {
method: "GET",
});
const result = (await resp.json()) as {
agents: AgentSessionView[];
totalCount: number;
};
return {
agents: result.agents.map((agent) => ({
id: agent.id,
name: agent.name,
status: agent.status,
repoUrl: agent.repoUrl,
createdAt: agent.createdAt,
metadata: {
github_repo: agent.metadata.github_repo,
},
})),
totalCount: result.totalCount,
};
} catch (e) {
Logger.error(e, {
context: "control_plane_list_background_agents",
});
return { agents: [], totalCount: 0 };
}
}
/**
* Get the full agent session information
* @param agentSessionId - The ID of the agent session
* @returns The agent session view including metadata and status
*/
public async getAgentSession(
agentSessionId: string,
): Promise<AgentSessionView | null> {
if (!(await this.isSignedIn())) {
return null;
}
try {
const resp = await this.requestAndHandleError(
`agents/${agentSessionId}`,
{
method: "GET",
},
);
return (await resp.json()) as AgentSessionView;
} catch (e) {
Logger.error(e, {
context: "control_plane_get_agent_session",
agentSessionId,
});
return null;
}
}
/**
* Get the state of a specific background agent
* @param agentSessionId - The ID of the agent session
* @returns The agent's session state including history, workspace, and branch
*/
public async getAgentState(agentSessionId: string): Promise<{
session: Session;
isProcessing: boolean;
messageQueueLength: number;
pendingPermission: any;
} | null> {
if (!(await this.isSignedIn())) {
return null;
}
try {
const resp = await this.requestAndHandleError(
`agents/${agentSessionId}/state`,
{
method: "GET",
},
);
const result = (await resp.json()) as {
session: Session;
isProcessing: boolean;
messageQueueLength: number;
pendingPermission: any;
};
return result;
} catch (e) {
Logger.error(e, {
context: "control_plane_get_agent_state",
agentSessionId,
});
return null;
}
}
}

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