merge: main

This commit is contained in:
Dallin Romney 2025-10-06 10:50:24 -07:00
commit 0fd58f6c48
946 changed files with 83338 additions and 28769 deletions

View file

@ -1,20 +0,0 @@
#!/bin/bash
# Get file path from hook input
FILE_PATH=$(cat | jq -r '.tool_input.file_path // .tool_input.edits[].file_path // empty' | head -n1)
# Function to run lint and typecheck
run_checks() {
local dir=$1
cd "$dir"
npm run lint >&2 && npm run tsc:check >&2
}
# Run checks based on file location
if [[ "$FILE_PATH" == *"/core/"* ]]; then
run_checks core
elif [[ "$FILE_PATH" == *"/gui/"* ]]; then
run_checks gui
elif [[ "$FILE_PATH" == *"/extensions/vscode/"* ]]; then
run_checks extensions/vscode
fi

View file

@ -1,15 +0,0 @@
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/lint-check.sh"
}
]
}
]
}
}

View file

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

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,5 @@
---
globs: "**/*.{ts,tsx}"
---
Avoid using the `any` type wherever possible. Use unknown or find the correct type. The only acceptable place to use any is when typecasting for test mocks, and even then it's better to avoid and provide a proper mock.

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

@ -107,7 +107,7 @@ runs:
cd binary
npm run build
- name: Start test IDE
- name: Run tests
shell: bash
run: |
cd extensions/intellij
@ -115,21 +115,7 @@ runs:
Xvfb -ac :99 -screen 0 1920x1080x24 &
sleep 10
mkdir -p build/reports
./gradlew runIdeForUiTests &
- name: Wait for JB connection
uses: jtalk/url-health-check-action@v3
with:
url: http://127.0.0.1:8082
max-attempts: 15
retry-delay: 30s
- name: Run tests
shell: bash
run: |
cd extensions/intellij
export DISPLAY=:99.0
./gradlew test
./gradlew test testIntegration
- name: Move video
if: ${{ failure() }}

View file

@ -1,25 +1,25 @@
name: 'Run VS Code E2E Test'
description: 'Run a single VS Code E2E test with all required setup'
name: "Run VS Code E2E Test"
description: "Run a single VS Code E2E test with all required setup"
inputs:
test_file:
description: 'E2E test file to run'
description: "E2E test file to run"
required: true
command:
description: 'Command to run (e2e:ci:run or e2e:ci:run-yaml)'
description: "Command to run (e2e:ci:run or e2e:ci:run-yaml)"
required: true
ssh_key:
description: 'SSH private key for testing'
description: "SSH private key for testing"
required: false
ssh_host:
description: 'SSH host for testing'
description: "SSH host for testing"
required: false
is_fork:
description: 'Whether this is a fork (affects SSH tests)'
description: "Whether this is a fork (affects SSH tests)"
required: false
default: 'false'
default: "false"
runs:
using: 'composite'
using: "composite"
steps:
- uses: actions/setup-node@v4
with:
@ -58,6 +58,7 @@ runs:
cd core
npm ci
cd ../extensions/vscode
npm ci
npm run e2e:ci:download
else
cd core
@ -131,4 +132,4 @@ runs:
uses: actions/upload-artifact@v4
with:
name: e2e-logs-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ inputs.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }}
path: extensions/vscode/e2e.log
path: extensions/vscode/e2e.log

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

@ -0,0 +1,170 @@
name: Auto Fix Failed Tests
on:
workflow_run:
workflows: ["PR Checks", "CLI PR Checks"]
types:
- completed
permissions:
contents: write
pull-requests: write
issues: write
actions: read
jobs:
fix-failed-tests:
# Only run if the workflow failed
# DISABLED: Remove 'false && ' on the next line to enable auto-fixing
if: false && github.event.workflow_run.conclusion == 'failure'
runs-on: ubuntu-latest
steps:
- name: Get workflow run details
id: workflow-details
uses: actions/github-script@v8
with:
script: |
const workflowRun = context.payload.workflow_run;
const { data: jobs } = await github.rest.actions.listJobsForWorkflowRun({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: workflowRun.id
});
// Find all failed jobs since we're only monitoring specific test workflows
const failedJobs = jobs.jobs.filter(job => job.conclusion === 'failure');
if (failedJobs.length === 0) {
core.info('No failed jobs found');
return null;
}
core.setOutput('has_failed_tests', 'true');
core.setOutput('workflow_name', workflowRun.name);
core.setOutput('workflow_run_id', workflowRun.id);
core.setOutput('head_branch', workflowRun.head_branch);
core.setOutput('head_sha', workflowRun.head_sha);
core.setOutput('failed_jobs', JSON.stringify(failedJobs.map(j => j.name)));
return failedJobs;
- name: Get job logs for failed tests
if: steps.workflow-details.outputs.has_failed_tests == 'true'
id: get-logs
uses: actions/github-script@v8
with:
script: |
const workflowRunId = ${{ github.event.workflow_run.id }};
const { data: jobs } = await github.rest.actions.listJobsForWorkflowRun({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: workflowRunId
});
let errorLogs = '';
for (const job of jobs.jobs) {
if (job.conclusion === 'failure') {
try {
const { data: logData } = await github.rest.actions.downloadJobLogsForWorkflowRun({
owner: context.repo.owner,
repo: context.repo.repo,
job_id: job.id
});
errorLogs += `\n\n=== Job: ${job.name} ===\n`;
errorLogs += logData;
} catch (error) {
core.warning(`Could not fetch logs for job ${job.name}: ${error.message}`);
}
}
}
// Store logs in environment file for next step
const fs = require('fs');
fs.writeFileSync('/tmp/test_failure_logs.txt', errorLogs);
core.setOutput('has_logs', errorLogs.length > 0 ? 'true' : 'false');
- name: Checkout repository
if: steps.workflow-details.outputs.has_failed_tests == 'true'
uses: actions/checkout@v5
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
ref: ${{ steps.workflow-details.outputs.head_sha }}
- name: Setup Node.js
if: steps.workflow-details.outputs.has_failed_tests == 'true'
uses: actions/setup-node@v5
with:
node-version: "20"
- name: Install Continue CLI globally
if: steps.workflow-details.outputs.has_failed_tests == 'true'
run: npm i -g @continuedev/cli
- name: Start remote session to fix failed tests
if: steps.workflow-details.outputs.has_failed_tests == 'true'
id: remote-session
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
run: |
# Create a detailed prompt for fixing the failed tests
cat > /tmp/fix_tests_prompt.txt << 'PROMPT_EOF'
🔧 **Auto Test Fix Request**
The following tests failed in workflow "${{ steps.workflow-details.outputs.workflow_name }}" (Run ID: ${{ steps.workflow-details.outputs.workflow_run_id }}):
**Failed Jobs:** ${{ steps.workflow-details.outputs.failed_jobs }}
**Branch:** ${{ steps.workflow-details.outputs.head_branch }}
**Commit:** ${{ steps.workflow-details.outputs.head_sha }}
**Your Task:**
1. Analyze the test failure logs and error messages
2. Identify the root cause of the test failures
3. Fix the failing tests by updating the test code or the underlying implementation
4. Ensure all tests pass after your changes
5. Commit your fixes with a descriptive message
**Test Failure Context:**
Please examine the repository structure, run the failing tests locally to understand the errors, and implement appropriate fixes.
Focus on:
- Understanding what the tests are trying to validate
- Identifying why they're failing (code changes, environment issues, test logic errors)
- Making minimal, targeted fixes that address the root cause
- Ensuring the fixes don't break other functionality
Please start by examining the failing tests and their error messages, then proceed with the necessary fixes.
PROMPT_EOF
echo "Starting Continue CLI remote session for test fixes..."
echo "Prompt content:"
cat /tmp/fix_tests_prompt.txt
# Start remote session and capture JSON output
SESSION_OUTPUT=$(cat /tmp/fix_tests_prompt.txt | cn remote -s --branch ${{ steps.workflow-details.outputs.head_branch }})
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: Log session details
if: steps.workflow-details.outputs.has_failed_tests == 'true'
run: |
echo "✅ Successfully started auto-fix session for failed tests"
echo "Workflow: ${{ steps.workflow-details.outputs.workflow_name }}"
echo "Run ID: ${{ steps.workflow-details.outputs.workflow_run_id }}"
echo "Branch: ${{ steps.workflow-details.outputs.head_branch }}"
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
echo "Failed jobs: ${{ steps.workflow-details.outputs.failed_jobs }}"

View file

@ -24,7 +24,7 @@ jobs:
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
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

@ -25,7 +25,7 @@ jobs:
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version: 20
cache: "npm"
@ -59,6 +59,7 @@ jobs:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [18, 20, 22, 24]
fail-fast: false
runs-on: ${{ matrix.os }}
steps:
@ -66,7 +67,7 @@ jobs:
uses: actions/checkout@v5
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version: ${{ matrix.node-version }}

View file

@ -41,7 +41,7 @@ jobs:
- name: Add PR title guidance comment
if: always() && steps.pr-title-check.outputs.valid == 'false'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const { data: comments } = await github.rest.issues.listComments({
@ -104,7 +104,7 @@ jobs:
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
cache: "npm"

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@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe
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:
- nate/fix-wf
pull_request:
types: [opened, ready_for_review]
issue_comment:
@ -18,7 +21,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Run Continue PR Review Action
uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe
uses: continuedev/continue/actions/general-review@main
with:
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
continue-org: "continuedev"

View file

@ -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@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
@ -370,7 +370,7 @@ jobs:
# 2. Install npm dependencies
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
@ -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
@ -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

View file

@ -44,7 +44,7 @@ jobs:
- name: Determine and apply tier label
if: steps.check-author.outputs.should_label == 'true'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const pr = context.payload.pull_request;

View file

@ -20,14 +20,30 @@ jobs:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v1.0.*-vscode ]]; then
if [[ "${{ github.event.release.tag_name }}" == v1.2.*-vscode ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
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:
@ -70,7 +86,7 @@ jobs:
with:
fetch-depth: 0
- uses: actions/setup-node@v4
- uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
@ -88,22 +104,6 @@ jobs:
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

View file

@ -23,7 +23,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
- uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
@ -84,6 +84,9 @@ jobs:
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 }}
gui-checks:
runs-on: ubuntu-latest
@ -217,6 +220,8 @@ jobs:
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 }}
vscode-get-test-file-matrix:
runs-on: ubuntu-latest
@ -224,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@v4
- uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
@ -338,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@v4
with:
node-version: 20
- name: Cache PR review action node modules
uses: actions/cache@v4
id: pr-review-cache
with:
path: actions/detailed-review/node_modules
key: ${{ runner.os }}-pr-review-action-${{ hashFiles('actions/detailed-review/package.json') }}
- name: Install dependencies
if: steps.pr-review-cache.outputs.cache-hit != 'true'
run: |
cd actions/detailed-review
npm install
- name: Run tests
run: |
cd actions/detailed-review
npm test
# so that creators of new jobs can add them to this list
require-all-checks-to-pass:
@ -380,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

@ -70,7 +70,7 @@ jobs:
with:
fetch-depth: 0
- uses: actions/setup-node@v4
- uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
@ -165,7 +165,7 @@ jobs:
# 4. Create PR with version bump
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"

View file

@ -32,3 +32,5 @@ jobs:
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

@ -32,3 +32,5 @@ jobs:
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,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,11 +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 }}

View file

@ -32,3 +32,5 @@ jobs:
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,215 +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: |
if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
echo "contains_mention=true" >> $GITHUB_OUTPUT
else
echo "contains_mention=false" >> $GITHUB_OUTPUT
fi
- name: Checkout PR branch
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/checkout@v4
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@v7
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@v4
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 the prompt for remote session
PROMPT="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."
# Start remote session and capture JSON output
SESSION_OUTPUT=$(echo "$PROMPT" | cn remote -s --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@v7
with:
script: |
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
> ${{ github.event.comment.body }}`;
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: ${{ github.event.comment.body }}"
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: |
if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
echo "contains_mention=true" >> $GITHUB_OUTPUT
else
echo "contains_mention=false" >> $GITHUB_OUTPUT
fi
- name: Checkout PR branch
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/checkout@v4
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@v4
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 code review comment from @${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}:
**File:** ${{ github.event.comment.path }}
**Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }}
**Comment:** ${{ github.event.comment.body }}
Please analyze the specific file and line mentioned, understand the review feedback, 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 --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@v7
with:
script: |
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
> ${{ github.event.comment.body }}`;
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: ${{ github.event.comment.body }}"

View file

@ -32,6 +32,10 @@ on:
required: false
VOYAGE_API_KEY:
required: false
RELACE_API_KEY:
required: false
INCEPTION_API_KEY:
required: false
permissions:
contents: write
@ -55,7 +59,7 @@ jobs:
uses: ./.github/actions/setup-packages
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
@ -77,6 +81,8 @@ jobs:
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 }}
- name: Release
env:

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
agent:
description: "The agent 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 }}",
"agent": "${{ inputs.agent }}",
"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"
]
}

View file

@ -31,7 +31,7 @@ jobs:
path: deja-view
- name: Setup Python
uses: actions/setup-python@v5
uses: actions/setup-python@v6
with:
python-version: "3.11"
@ -190,7 +190,7 @@ jobs:
echo "confidence=$CONFIDENCE" >> $GITHUB_OUTPUT
- name: Comment with analysis
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
let comment = '';
@ -307,7 +307,7 @@ jobs:
- name: Add labels
if: github.event_name == 'issues'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const labels = [];

View file

@ -40,7 +40,7 @@ jobs:
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
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

@ -10,7 +10,7 @@ jobs:
pull-requests: write
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
- uses: actions/stale@v10
with:
close-issue-message: "This issue was closed because it wasn't updated for 10 days after being marked stale. If it's still important, please reopen + comment and we'll gladly take another look!"
stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after an additional 10 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue."

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>"
agent: continuedev/default-background-agent
branch_name: main
secrets:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}

View file

@ -21,7 +21,7 @@ jobs:
gh auth login --with-token <<< "${{ github.token }}"
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
uses: actions/setup-node@v5
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,24 +4,31 @@ 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
**/CODEOWNERS
core/vendor
coverage
e2e
packages/continue-sdk
# e2e
packages/continue-sdk
.conductor

43
.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": "watch-logs",
"cwd": "${workspaceFolder}/extensions/cli"
"preLaunchTask": "cli:build-and-watch-logs",
"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,
@ -43,7 +44,8 @@
"extensions/vscode/e2e/storage": true,
"extensions/vscode/e2e/vsix": true,
"extensions/.continue-debug": true,
"extensions/cli/dist/**": true
"extensions/cli/dist/**": true,
"packages/config-yaml/dist/**": true
// "sync/**": true
},
"editor.formatOnSave": true,

35
.vscode/tasks.json vendored
View file

@ -330,6 +330,26 @@
"cwd": "${workspaceFolder}/extensions/cli"
}
},
{
"label": "cli:build-no-minify",
"type": "shell",
"command": "npm",
"args": ["run", "build:bundle", "--", "--no-minify"],
"group": "build",
"presentation": {
"echo": true,
"reveal": "silent",
"focus": false,
"panel": "shared",
"showReuseMessage": true,
"clear": false,
"close": true
},
"problemMatcher": ["$tsc"],
"options": {
"cwd": "${workspaceFolder}/extensions/cli"
}
},
{
"label": "cli:test",
"type": "npm",
@ -373,6 +393,21 @@
"options": {
"cwd": "${workspaceFolder}/extensions/cli"
}
},
{
"label": "cli:build-and-watch-logs",
"dependsOn": ["cli:build-no-minify", "watch-logs"],
"dependsOrder": "sequence",
"type": "shell",
"command": "echo",
"args": ["Build and watch logs completed"],
"presentation": {
"group": "build-tasks",
"panel": "shared",
"reveal": "silent",
"close": true,
"focus": false
}
}
]
}

View file

@ -176,9 +176,9 @@ See [`intellij/CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the
### Our Git Workflow
We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the
`main` branch titled `v1.1.x-vscode`, which automatically triggers the workflow
`main` branch titled `v1.3.x-vscode`, which automatically triggers the workflow
in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When
a release has been sufficiently tested, we will create a new release titled `v1.0x-vscode`, triggering a similar
a release has been sufficiently tested, we will create a new release titled `v1.2.x-vscode`, triggering a similar
workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code
extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow
is well explained by <http://releaseflow.org>.
@ -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

@ -35,25 +35,25 @@ Get started in [VS Code](https://marketplace.visualstudio.com/items?itemName=Con
## Agent
[Agent](/features/agent/quick-start) to work on development tasks together with AI
[Agent](https://docs.continue.dev/features/agent/quick-start) to work on development tasks together with AI
![agent](docs/images/agent.gif)
## Chat
[Chat](/features/chat/quick-start) to ask general questions and clarify code sections
[Chat](https://docs.continue.dev/features/chat/quick-start) to ask general questions and clarify code sections
![chat](docs/images/chat.gif)
## Edit
[Edit](/features/edit/quick-start) to modify a code section without leaving your current file
[Edit](https://docs.continue.dev/features/edit/quick-start) to modify a code section without leaving your current file
![edit](docs/images/edit.gif)
## Autocomplete
[Autocomplete](/features/autocomplete/quick-start) to receive inline code suggestions as you type
[Autocomplete](https://docs.continue.dev/features/autocomplete/quick-start) to receive inline code suggestions as you type
![autocomplete](docs/images/autocomplete.gif)

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

View file

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

@ -1,20 +1,20 @@
name: 'Continue PR Review'
description: 'Automated code review for pull requests using Continue CLI'
author: 'Continue Dev, Inc.'
name: "Continue PR Review"
description: "Automated code review for pull requests using Continue CLI"
author: "Continue Dev, Inc."
inputs:
continue-api-key:
description: 'API key for Continue service'
description: "API key for Continue service"
required: true
continue-org:
description: 'Organization for Continue config'
description: "Organization for Continue config"
required: true
continue-config:
description: 'Config path to use (e.g., "myorg/review-bot")'
required: true
runs:
using: 'composite'
using: "composite"
steps:
- name: Checkout Repository
uses: actions/checkout@v4
@ -23,11 +23,11 @@ runs:
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') }}
HAS_TRIGGER_PHRASE: ${{ contains(github.event.comment.body, '@continue-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
@ -51,12 +51,12 @@ runs:
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"
echo "::notice::Skipping review - Comment does not contain @continue-review trigger, or is not on a PR"
fi
else
echo "::notice::Skipping review - Unsupported event type: ${{ github.event_name }}"
fi
echo "SHOULD_RUN=$SHOULD_RUN" >> $GITHUB_ENV
- name: Setup Node.js
@ -68,13 +68,99 @@ runs:
- name: Install Continue CLI
if: env.SHOULD_RUN == 'true'
shell: bash
run: npm install -g @continuedev/cli@1.4.25
run: npm install -g @continuedev/cli@1.4.30
- 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 +170,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 actions/general-review/scripts/buildPrompt.js "$PR_NUMBER"
rm -f pr_data.json
- name: Run Continue CLI Review
if: env.SHOULD_RUN == 'true'
@ -150,26 +183,101 @@ runs:
CONTINUE_API_KEY: ${{ inputs.continue-api-key }}
CONTINUE_ORG: ${{ inputs.continue-org }}
CONTINUE_CONFIG: ${{ inputs.continue-config }}
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 ""
# Validate API key
if [ -z "$CONTINUE_API_KEY" ]; then
echo "Warning: CONTINUE_API_KEY environment variable is not set"
# Create fallback review and continue
node actions/general-review/scripts/writeMarkdown.js code_review.md missing_api_key
echo "SKIP_CLI=true" >> $GITHUB_ENV
else
echo "SKIP_CLI=false" >> $GITHUB_ENV
fi
# Validate inputs to prevent command injection
if [[ ! "$CONTINUE_ORG" =~ ^[a-zA-Z0-9_-]+$ ]]; then
echo "Error: Invalid organization name. Must contain only alphanumeric characters, hyphens, and underscores."
exit 1
fi
if [[ ! "$CONTINUE_CONFIG" =~ ^[a-zA-Z0-9_/-]+$ ]]; then
echo "Error: Invalid config path. Must contain only alphanumeric characters, hyphens, underscores, and forward slashes."
exit 1
fi
# Run the CLI with validated config
cn --readonly --org "$CONTINUE_ORG" --config "$CONTINUE_CONFIG" -p "$(cat review_prompt.txt)" > code_review.md
# Test Continue CLI availability
if [ "$SKIP_CLI" != "true" ]; then
echo "Testing Continue CLI..."
if ! which cn > /dev/null 2>&1; then
echo "Warning: Continue CLI not found or not working"
node actions/general-review/scripts/writeMarkdown.js code_review.md cli_install_failed
echo "SKIP_CLI=true" >> $GITHUB_ENV
else
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"
# 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 (360 seconds = 6 minutes)
echo "Executing command: cn --config $CONTINUE_ORG/$CONTINUE_CONFIG -p @$PROMPT_FILE --allow Bash"
if timeout 360 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -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 actions/general-review/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 actions/general-review/scripts/writeMarkdown.js code_review.md cli_not_found
elif grep -q "config\|assistant" cli_error.log 2>/dev/null; then
node actions/general-review/scripts/writeMarkdown.js code_review.md config_error
elif grep -q "api\|auth" cli_error.log 2>/dev/null; then
node actions/general-review/scripts/writeMarkdown.js code_review.md auth_error
else
node actions/general-review/scripts/writeMarkdown.js code_review.md generic_failure
fi
fi
# Clean up temp file
rm -f "$PROMPT_FILE"
else
echo "Review generation successfully completed"
fi
- name: Upload Review Results
if: env.SHOULD_RUN == 'true' && always()
@ -182,7 +290,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:
@ -191,13 +299,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') {
@ -212,22 +322,120 @@ 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);
}
branding:
icon: 'code'
color: 'blue'
icon: "code"
color: "blue"

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",
@ -56,6 +57,7 @@
"@continuedev/fetch": "file:../packages/fetch",
"@continuedev/llm-info": "file:../packages/llm-info",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@continuedev/terminal-security": "file:../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -106,6 +108,7 @@
"quick-lru": "^7.0.0",
"replicate": "^0.26.0",
"request": "^2.88.2",
"shell-quote": "^1.8.3",
"socket.io-client": "^4.7.3",
"sqlite": "^5.1.1",
"sqlite3": "^5.1.7",
@ -140,6 +143,7 @@
"@types/pg": "^8.11.6",
"@types/plist": "^3.0.5",
"@types/request": "^2.48.12",
"@types/shell-quote": "^1.7.5",
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
@ -6671,9 +6675,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

@ -166,8 +166,13 @@ export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"];
export const CODE_STOP_BLOCK = "[/CODE]";
export const BRACKET_ENDING_CHARS = [")", "]", "}", ";"];
export const PREFIXES_TO_SKIP = ["<COMPLETION>"];
export const LINES_TO_STOP_AT = ["# End of file.", "<STOP EDITING HERE"];
export const LINES_TO_SKIP = ["</START EDITING HERE>"];
export const LINES_TO_STOP_AT = [
"# End of file.",
"<STOP EDITING HERE",
"<|/updated_code|>",
"```",
];
export const LINES_TO_SKIP = ["</START EDITING HERE>", "<|updated_code|>"];
export const LINES_TO_REMOVE_BEFORE_START = [
"<COMPLETION>",
"[CODE]",

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,38 @@ 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 "```" and the last line if it is exactly "```".
*/
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 ```
if (lines[0].trimStart().startsWith("```")) {
startIdx = 1;
}
// Remove last line if it is exactly ```
if (lines.length > startIdx && lines[lines.length - 1].trim() === "```") {
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,
@ -156,5 +188,8 @@ export function postprocessCompletion({
completion = completion.slice(1);
}
// Remove markdown code block delimiters
completion = removeBackticks(completion);
return completion;
}

View file

@ -19,7 +19,7 @@ import {
getSingletonHighlighter,
Highlighter,
} from "shiki";
import { DiffLine } from "..";
import { DiffChar, DiffLine } from "..";
import { escapeForSVG, kebabOfThemeStr } from "../util/text";
interface CodeRendererOptions {
@ -228,6 +228,7 @@ export class CodeRenderer {
options: ConversionOptions,
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
newDiffChars: DiffChar[],
): Promise<Buffer> {
const strokeWidth = 1;
const highlightedCodeHtml = await this.highlightCode(
@ -236,13 +237,14 @@ export class CodeRenderer {
currLineOffsetFromTop,
newDiffLines,
);
// console.log(highlightedCodeHtml);
const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut(
highlightedCodeHtml,
options,
newDiffChars,
);
const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
const borderColor = "#6b6b6b";
const lines = code.split("\n");
const actualHeight = lines.length * options.lineHeight;
@ -256,12 +258,11 @@ export class CodeRenderer {
}
</style>
<g>
<rect x="0" y="0" rx="10" ry="10" width="${options.dimensions.width}" height="${actualHeight}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
<rect x="0" y="0" rx="2" ry="2" width="${options.dimensions.width}" height="${actualHeight}" fill="${backgroundColor}" stroke="${borderColor}" stroke-width="${strokeWidth}" shape-rendering="crispEdges" />
${lineBackgrounds}
${guts}
</g>
</svg>`;
// console.log(svg);
return Buffer.from(svg, "utf8");
}
@ -269,11 +270,56 @@ export class CodeRenderer {
convertShikiHtmlToSvgGut(
shikiHtml: string,
options: ConversionOptions,
diffChars: DiffChar[],
): { guts: string; lineBackgrounds: string } {
const dom = new JSDOM(shikiHtml);
const document = dom.window.document;
const lines = Array.from(document.querySelectorAll(".line"));
const additionSegmentsByLine = new Map<
number,
Array<{ start: number; end: number }>
>();
diffChars.forEach((diff) => {
if (
diff.type !== "new" ||
diff.newLineIndex === undefined ||
diff.newCharIndexInLine === undefined
) {
return;
}
if (diff.char.includes("\n")) {
return;
}
const start = diff.newCharIndexInLine;
const end = start + diff.char.length;
const existing = additionSegmentsByLine.get(diff.newLineIndex) ?? [];
existing.push({ start, end });
additionSegmentsByLine.set(diff.newLineIndex, existing);
});
additionSegmentsByLine.forEach((segments, lineIndex) => {
segments.sort((a, b) => a.start - b.start);
const merged: Array<{ start: number; end: number }> = [];
segments.forEach((segment) => {
if (merged.length === 0) {
merged.push({ ...segment });
return;
}
const last = merged[merged.length - 1];
if (segment.start <= last.end) {
last.end = Math.max(last.end, segment.end);
} else {
merged.push({ ...segment });
}
});
additionSegmentsByLine.set(lineIndex, merged);
});
const svgLines = lines.map((line, index) => {
const spans = Array.from(line.childNodes)
.map((node) => {
@ -309,60 +355,37 @@ export class CodeRenderer {
return `<text x="0" y="${y}" font-family="${options.fontFamily}" font-size="${options.fontSize.toString()}" xml:space="preserve" dominant-baseline="central" shape-rendering="crispEdges">${spans}</text>`;
});
const estimatedCharWidth = options.fontSize * 0.6;
const additionFill = "rgba(40, 167, 69, 0.25)";
const lineBackgrounds = lines
.map((line, index) => {
const classes = line?.getAttribute("class") || "";
const bgColor = classes.includes("highlighted")
? this.editorLineHighlight
: classes.includes("diff add")
? "rgba(255, 255, 0, 0.2)"
: this.editorBackground;
const y = index * options.lineHeight;
const isFirst = index === 0;
const isLast = index === lines.length - 1;
const isSingleLine = isFirst && isLast;
const radius = 10;
const segments = additionSegmentsByLine.get(index) ?? [];
const backgrounds: string[] = [];
// Handle single line case (both first and last)
if (isSingleLine) {
return `<path d="M ${radius} ${y}
L ${options.dimensions.width - radius} ${y}
Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
L ${options.dimensions.width} ${y + options.lineHeight - radius}
Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width - radius} ${y + options.lineHeight}
L ${radius} ${y + options.lineHeight}
Q ${0} ${y + options.lineHeight} ${0} ${y + options.lineHeight - radius}
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
Z"
fill="${bgColor}" />`;
if (classes.includes("highlighted")) {
backgrounds.push(
`<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${this.editorLineHighlight}" shape-rendering="crispEdges" />`,
);
}
// SVG notes:
// By default SVGs have anti-aliasing on.
// This is undesirable in our case because pixel-perfect alignment of these rectangles will introduce thin gaps.
// Turning it off with 'shape-rendering="crispEdges"' solves the issue.
return isFirst
? `<path d="M ${0} ${y + options.lineHeight}
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
L ${options.dimensions.width - radius} ${y}
Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
L ${options.dimensions.width} ${y + options.lineHeight}
Z"
fill="${bgColor}" />`
: isLast
? `<path d="M ${0} ${y}
L ${0} ${y + options.lineHeight - radius}
Q ${0} ${y + options.lineHeight} ${radius} ${y + options.lineHeight}
L ${options.dimensions.width - radius} ${y + options.lineHeight}
Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width} ${y + options.lineHeight - 10}
L ${options.dimensions.width} ${y}
Z"
fill="${bgColor}" />`
: `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
segments.forEach(({ start, end }) => {
const widthInChars = Math.max(end - start, 0);
if (widthInChars <= 0) {
return;
}
const x = start * estimatedCharWidth;
const segmentWidth = widthInChars * estimatedCharWidth;
backgrounds.push(
`<rect x="${x}" y="${y}" width="${segmentWidth}" height="${options.lineHeight}" fill="${additionFill}" shape-rendering="crispEdges" />`,
);
});
return backgrounds.join("\n");
})
.filter((bg) => bg.length > 0)
.join("\n");
return {
@ -394,6 +417,7 @@ export class CodeRenderer {
options: ConversionOptions,
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
newDiffChars: DiffChar[],
): Promise<DataUri> {
switch (options.imageType) {
// case "png":
@ -413,6 +437,7 @@ export class CodeRenderer {
options,
currLineOffsetFromTop,
newDiffLines,
newDiffChars,
);
return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
}

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

@ -0,0 +1,16 @@
import { RuleWithSource, SlashCommandWithSource } from "../..";
export function convertRuleBlockToSlashCommand(
rule: RuleWithSource,
): SlashCommandWithSource {
return {
name:
rule.name ||
(rule.rule.length > 20 ? rule.rule.substring(0, 20) + "..." : rule.rule),
description: rule.description ?? "",
prompt: rule.rule,
source: "invokable-rule",
sourceFile: rule.sourceFile,
slug: rule.slug,
};
}

View file

@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import { RuleWithSource } from "../..";
import { convertRuleBlockToSlashCommand } from "./ruleBlockSlashCommand";
describe("convertRuleBlockToSlashCommand", () => {
it("should convert a rule with all properties to a slash command", () => {
const rule: RuleWithSource = {
name: "Code Review",
rule: "Review this code for best practices",
description: "Performs a code review",
source: "rules-block",
sourceFile: "file:///path/to/rules.yaml",
invokable: true,
};
const result = convertRuleBlockToSlashCommand(rule);
expect(result).toEqual({
name: "Code Review",
description: "Performs a code review",
prompt: "Review this code for best practices",
source: "invokable-rule",
sourceFile: "file:///path/to/rules.yaml",
});
});
it("should handle a rule without name", () => {
const rule: RuleWithSource = {
rule: "Review this code",
source: "rules-block",
invokable: true,
};
const result = convertRuleBlockToSlashCommand(rule);
expect(result.name).toBe("Review this code");
expect(result.prompt).toBe("Review this code");
});
it("should truncate long rule text when used as name", () => {
const rule: RuleWithSource = {
rule: "This is a very long rule text that should be truncated",
source: "rules-block",
invokable: true,
};
const result = convertRuleBlockToSlashCommand(rule);
expect(result.name).toBe("This is a very long ...");
expect(result.prompt).toBe(
"This is a very long rule text that should be truncated",
);
});
it("should handle a rule without description", () => {
const rule: RuleWithSource = {
name: "Test Rule",
rule: "Test rule content",
source: "rules-block",
invokable: true,
};
const result = convertRuleBlockToSlashCommand(rule);
expect(result.description).toBe("");
});
it("should use rule text as the prompt", () => {
const rule: RuleWithSource = {
name: "Explain Code",
rule: "Explain what this code does in simple terms",
source: "rules-block",
invokable: true,
};
const result = convertRuleBlockToSlashCommand(rule);
expect(result.prompt).toBe("Explain what this code does in simple terms");
});
it("should always set source to 'invokable-rule'", () => {
const rule: RuleWithSource = {
name: "Test",
rule: "Test",
source: "default-chat",
invokable: true,
};
const result = convertRuleBlockToSlashCommand(rule);
expect(result.source).toBe("invokable-rule");
});
});

View file

@ -59,27 +59,17 @@ export class ConfigHandler {
constructor(
private readonly ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private llmLogger: ILLMLogger,
sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
initialSessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
) {
this.ide = ide;
this.ideSettingsPromise = ideSettingsPromise;
this.controlPlaneClient = new ControlPlaneClient(
sessionInfoPromise,
ideSettingsPromise,
this.ide.getIdeInfo(),
initialSessionInfoPromise,
this.ide,
);
// This profile manager will always be available
this.globalLocalProfileManager = new ProfileLifecycleManager(
new LocalProfileLoader(
ide,
ideSettingsPromise,
this.controlPlaneClient,
this.llmLogger,
),
new LocalProfileLoader(ide, this.controlPlaneClient, this.llmLogger),
this.ide,
);
@ -97,6 +87,7 @@ export class ConfigHandler {
}
private workspaceDirs: string[] | null = null;
async getWorkspaceId() {
if (!this.workspaceDirs) {
this.workspaceDirs = await this.ide.getWorkspaceDirs();
@ -113,6 +104,13 @@ export class ConfigHandler {
const signal = this.cascadeAbortController.signal;
this.workspaceDirs = null; // forces workspace dirs reload
// Always update globalLocalProfileManager before recreating all the loaders
// during every cascadeInit so it holds the most recent controlPlaneClient.
this.globalLocalProfileManager = new ProfileLifecycleManager(
new LocalProfileLoader(this.ide, this.controlPlaneClient, this.llmLogger),
this.ide,
);
try {
const { orgs, errors } = await this.getOrgs();
@ -202,6 +200,8 @@ export class ConfigHandler {
message: `Error loading Continue Hub assistants${e instanceof Error ? ":\n" + e.message : ""}`,
});
}
} else {
PolicySingleton.getInstance().policy = null;
}
// Load local org if not signed in or hub orgs fail
try {
@ -246,7 +246,6 @@ export class ConfigHandler {
versionSlug: assistant.configResult.config?.version ?? "latest",
controlPlaneClient: this.controlPlaneClient,
ide: this.ide,
ideSettingsPromise: this.ideSettingsPromise,
llmLogger: this.llmLogger,
rawYaml: assistant.rawYaml,
orgScopeId: orgScopeId,
@ -367,7 +366,6 @@ export class ConfigHandler {
const profiles = [...assistantFiles, ...agentFiles].map((assistant) => {
return new LocalProfileLoader(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.llmLogger,
assistant,
@ -392,7 +390,6 @@ export class ConfigHandler {
// Ide settings change: refresh session and cascade refresh from the top
async updateIdeSettings(ideSettings: IdeSettings) {
this.ideSettingsPromise = Promise.resolve(ideSettings);
this.abortCascade();
await this.cascadeInit("IDE settings update");
}
@ -430,8 +427,7 @@ export class ConfigHandler {
if (reload) {
this.controlPlaneClient = new ControlPlaneClient(
Promise.resolve(sessionInfo),
this.ideSettingsPromise,
this.ide.getIdeInfo(),
this.ide,
);
this.abortCascade();
await this.cascadeInit("Control plane session info update");

View file

@ -1,32 +1,32 @@
import { IDE } from "..";
import { joinPathsToUri } from "../util/uri";
const DEFAULT_ASSISTANT_FILE = `# This is an example assistant configuration file
# It is used to define custom AI assistants within Continue
# Each assistant file can be accessed by selecting it from the assistant dropdown
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
# To learn more, see the full assistant reference: https://docs.continue.dev/reference
# To learn more, see the full config.yaml reference: https://docs.continue.dev/reference
name: Example Assistant
name: Example Agent
version: 1.0.0
schema: v1
# Models define which AI models this assistant can use
# Models define which AI models this agent can use
# https://docs.continue.dev/customization/models
models:
- name: my gpt-5
provider: openai
model: gpt-5
apiKey: YOUR_API_KEY_HERE
apiKey: YOUR_OPENAI_API_KEY_HERE
- uses: ollama/qwen2.5-coder-7b
- uses: anthropic/claude-4-sonnet
with:
ANTHROPIC_API_KEY: \${{ secrets.ANTHROPIC_API_KEY }}
# Context providers define what information the assistant can access
context:
- provider: code
- provider: docs
- provider: diff
- provider: terminal
- provider: problems
- provider: folder
- provider: codebase
# MCP Servers the agent can use
# https://docs.continue.dev/customization/mcp-tools
mcpServers:
- uses: anthropic/memory-mcp
`;
export async function createNewAssistantFile(
@ -42,7 +42,7 @@ export async function createNewAssistantFile(
const baseDirUri = joinPathsToUri(
workspaceDirs[0],
assistantPath ?? ".continue/assistants",
assistantPath ?? ".continue/agents",
);
// Find the first available filename
@ -50,10 +50,7 @@ export async function createNewAssistantFile(
let assistantFileUri: string;
do {
const suffix = counter === 0 ? "" : `-${counter}`;
assistantFileUri = joinPathsToUri(
baseDirUri,
`new-assistant${suffix}.yaml`,
);
assistantFileUri = joinPathsToUri(baseDirUri, `new-agent${suffix}.yaml`);
counter++;
} while (await ide.fileExists(assistantFileUri));

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,6 +6,7 @@ import path from "path";
import {
ConfigResult,
ConfigValidationError,
mergeConfigYamlRequestOptions,
ModelRole,
} from "@continuedev/config-yaml";
import * as JSONC from "comment-json";
@ -25,6 +26,7 @@ import {
IdeType,
ILLM,
ILLMLogger,
InternalMcpOptions,
LLMOptions,
ModelDescription,
RerankerDescription,
@ -57,8 +59,10 @@ import {
} from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
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";
@ -214,8 +218,8 @@ function applyRequestOptionsToModels(
// Prepare models
for (const model of models) {
model.requestOptions = {
...model.requestOptions,
...config.requestOptions,
...model.requestOptions,
};
if (roles !== undefined) {
model.roles = model.roles ?? roles;
@ -544,16 +548,33 @@ async function intermediateToFinalConfig({
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
mcpManager.setConnections(
(config.experimental?.modelContextProtocolServers ?? []).map(
(server, index) => ({
id: `continue-mcp-server-${index + 1}`,
name: `MCP Server`,
...server,
}),
),
false,
);
const orgPolicy = PolicySingleton.getInstance().policy;
if (orgPolicy?.policy?.allowMcpServers === false) {
await mcpManager.shutdown();
} else {
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,
),
...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
const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
@ -651,7 +672,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()),

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,13 @@ import {
markdownToRule,
} from "@continuedev/config-yaml";
import { IDE, RuleWithSource } from "../..";
import { findUriInDirs } from "../../util/uri";
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
* and agent files (AGENTS.md, AGENT.md, CLAUDE.md) at workspace root
*/
export async function loadMarkdownRules(ide: IDE): Promise<{
rules: RuleWithSource[];
@ -16,6 +18,41 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
const errors: ConfigValidationError[] = [];
const rules: RuleWithSource[] = [];
// First, try to load agent files from workspace root
const workspaceDirs = await ide.getWorkspaceDirs();
for (const workspaceDir of workspaceDirs) {
let agentFileFound = false;
for (const fileName of SUPPORTED_AGENT_FILES) {
try {
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: "agent-file",
sourceFile: agentFileUri,
alwaysApply: true,
});
agentFileFound = true;
}
break; // Use the first found agent file in this workspace
} catch (e) {
// File doesn't exist or can't be read, continue to next file
}
}
if (agentFileFound) {
break; // Use agent file from first workspace that has one
}
}
try {
// Get all .md files from .continue/rules
const markdownFiles = await getAllDotContinueDefinitionFiles(
@ -30,15 +67,11 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
// Process each markdown file
for (const file of mdFiles) {
try {
const { relativePathOrBasename } = findUriInDirs(
file.path,
await ide.getWorkspaceDirs(),
);
const rule = markdownToRule(file.content, {
uriType: "file",
fileUri: relativePathOrBasename,
fileUri: file.path,
});
rules.push({ ...rule, source: "rules-block", ruleFile: file.path });
rules.push({ ...rule, source: "rules-block", sourceFile: file.path });
} catch (e) {
errors.push({
fatal: false,

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

@ -1,7 +1,7 @@
import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js";
import { ContinueConfig, IDE, ILLMLogger } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import { getPrimaryConfigFilePath } from "../../util/paths.js";
@ -15,7 +15,6 @@ export default class LocalProfileLoader implements IProfileLoader {
constructor(
private ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private controlPlaneClient: ControlPlaneClient,
private llmLogger: ILLMLogger,
private overrideAssistantFile?:
@ -57,7 +56,6 @@ export default class LocalProfileLoader implements IProfileLoader {
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
const result = await doLoadConfig({
ide: this.ide,
ideSettingsPromise: this.ideSettingsPromise,
controlPlaneClient: this.controlPlaneClient,
llmLogger: this.llmLogger,
profileId: this.description.id,

View file

@ -2,7 +2,7 @@ import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { ContinueConfig, IDE, IdeSettings, ILLMLogger } from "../../index.js";
import { ContinueConfig, IDE, ILLMLogger } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import doLoadConfig from "./doLoadConfig.js";
@ -28,7 +28,6 @@ export default class PlatformProfileLoader implements IProfileLoader {
private readonly versionSlug: string;
private readonly controlPlaneClient: ControlPlaneClient;
private readonly ide: IDE;
private ideSettingsPromise: Promise<IdeSettings>;
private llmLogger: ILLMLogger;
readonly description: ProfileDescription;
private readonly orgScopeId: string | null;
@ -41,7 +40,6 @@ export default class PlatformProfileLoader implements IProfileLoader {
versionSlug,
controlPlaneClient,
ide,
ideSettingsPromise,
llmLogger,
description,
orgScopeId,
@ -53,7 +51,6 @@ export default class PlatformProfileLoader implements IProfileLoader {
versionSlug: string;
controlPlaneClient: ControlPlaneClient;
ide: IDE;
ideSettingsPromise: Promise<IdeSettings>;
llmLogger: ILLMLogger;
description: ProfileDescription;
orgScopeId: string | null;
@ -65,7 +62,6 @@ export default class PlatformProfileLoader implements IProfileLoader {
this.versionSlug = versionSlug;
this.controlPlaneClient = controlPlaneClient;
this.ide = ide;
this.ideSettingsPromise = ideSettingsPromise;
this.llmLogger = llmLogger;
this.description = description;
this.orgScopeId = orgScopeId;
@ -79,7 +75,6 @@ export default class PlatformProfileLoader implements IProfileLoader {
versionSlug,
controlPlaneClient,
ide,
ideSettingsPromise,
llmLogger,
rawYaml,
orgScopeId,
@ -91,12 +86,11 @@ export default class PlatformProfileLoader implements IProfileLoader {
versionSlug: string;
controlPlaneClient: ControlPlaneClient;
ide: IDE;
ideSettingsPromise: Promise<IdeSettings>;
llmLogger: ILLMLogger;
rawYaml: string;
orgScopeId: string | null;
}): Promise<PlatformProfileLoader> {
const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise);
const controlPlaneEnv = await getControlPlaneEnv(ide.getIdeSettings());
const description: ProfileDescription = {
id: `${ownerSlug}/${packageSlug}`,
@ -121,7 +115,6 @@ export default class PlatformProfileLoader implements IProfileLoader {
versionSlug,
controlPlaneClient,
ide,
ideSettingsPromise,
llmLogger,
description,
orgScopeId,
@ -139,7 +132,6 @@ export default class PlatformProfileLoader implements IProfileLoader {
const results = await doLoadConfig({
ide: this.ide,
ideSettingsPromise: this.ideSettingsPromise,
controlPlaneClient: this.controlPlaneClient,
llmLogger: this.llmLogger,
overrideConfigYaml: this.configResult.config,

View file

@ -11,7 +11,6 @@ import {
import {
ContinueConfig,
IDE,
IdeSettings,
ILLMLogger,
RuleWithSource,
SerializedContinueConfig,
@ -19,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";
@ -28,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";
@ -70,7 +71,6 @@ async function loadRules(ide: IDE) {
}
export default async function doLoadConfig(options: {
ide: IDE;
ideSettingsPromise: Promise<IdeSettings>;
controlPlaneClient: ControlPlaneClient;
llmLogger: ILLMLogger;
overrideConfigJson?: SerializedContinueConfig;
@ -82,7 +82,6 @@ export default async function doLoadConfig(options: {
}): Promise<ConfigResult<ContinueConfig>> {
const {
ide,
ideSettingsPromise,
controlPlaneClient,
llmLogger,
overrideConfigJson,
@ -95,7 +94,7 @@ export default async function doLoadConfig(options: {
const ideInfo = await ide.getIdeInfo();
const uniqueId = await ide.getUniqueId();
const ideSettings = await ideSettingsPromise;
const ideSettings = await ide.getIdeSettings();
const workOsAccessToken = await controlPlaneClient.getAccessToken();
const isSignedIn = await controlPlaneClient.isSignedIn();
@ -158,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",
);
@ -190,7 +206,6 @@ export default async function doLoadConfig(options: {
const mcpManager = MCPManagerSingleton.getInstance();
const mcpServerStatuses = mcpManager.getStatuses();
// Slightly hacky just need connection's client to make slash command for now
const serializableStatuses = mcpServerStatuses.map((server) => {
const { client, ...rest } = server;
return rest;
@ -198,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,
@ -332,12 +354,14 @@ export default async function doLoadConfig(options: {
}
}
if (
PolicySingleton.getInstance().policy?.policy?.allowAnonymousTelemetry ===
false
) {
// Org policies
const policy = PolicySingleton.getInstance().policy?.policy;
if (policy?.allowAnonymousTelemetry === false) {
newConfig.allowAnonymousTelemetry = false;
}
if (policy?.allowCodebaseIndexing === false) {
newConfig.disableIndexing = true;
}
// Setup telemetry only after (and if) we know it is enabled
await Telemetry.setup(
@ -372,7 +396,7 @@ export default async function doLoadConfig(options: {
const useOnPremProxy =
controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl;
const env = await getControlPlaneEnv(ideSettingsPromise);
const env = await getControlPlaneEnv(Promise.resolve(ideSettings));
let controlPlaneProxyUrl: string = useOnPremProxy
? controlPlane?.proxyUrl
: env.DEFAULT_CONTROL_PLANE_PROXY_URL;

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>;
@ -1061,6 +1059,7 @@ declare global {
filepath?: string;
fileContent?: string;
originalFileContent?: string;
autoFormattingDiff?: string;
}
export interface RangeInFileWithContents {

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,6 +4,7 @@ import {
ConfigResult,
ConfigValidationError,
isAssistantUnrolledNonNullable,
mergeConfigYamlRequestOptions,
mergeUnrolledAssistants,
ModelRole,
PackageIdentifier,
@ -14,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";
@ -24,7 +32,9 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
import { loadJsonMcpConfigs } from "../../context/mcp/json/loadJsonMcpConfigs";
import { getControlPlaneEnvSync } from "../../control-plane/env";
import { PolicySingleton } from "../../control-plane/PolicySingleton";
import { getBaseToolDefinitions } from "../../tools";
import { getCleanUriPath } from "../../util/uri";
import { loadConfigContextProviders } from "../loadContextProviders";
@ -33,7 +43,7 @@ import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks";
import { LocalPlatformClient } from "./LocalPlatformClient";
import { llmsFromModelConfig } from "./models";
import {
convertYamlMcpToContinueMcp,
convertYamlMcpConfigToInternalMcpOptions,
convertYamlRuleToContinueRule,
} from "./yamlToContinueConfig";
@ -153,16 +163,15 @@ async function loadConfigYaml(options: {
};
}
async function configYamlToContinueConfig(options: {
export async function configYamlToContinueConfig(options: {
config: AssistantUnrolled;
ide: IDE;
ideSettings: IdeSettings;
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
workOsAccessToken: string | undefined;
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
let { config, ide, ideSettings, ideInfo, uniqueId, llmLogger } = options;
let { config, ide, ideInfo, uniqueId, llmLogger } = options;
const localErrors: ConfigValidationError[] = [];
@ -190,6 +199,7 @@ async function configYamlToContinueConfig(options: {
summarize: null,
},
rules: [],
requestOptions: { ...config.requestOptions },
};
// Right now, if there are any missing packages in the config, then we will just throw an error
@ -207,10 +217,17 @@ async function configYamlToContinueConfig(options: {
}
for (const rule of config.rules ?? []) {
continueConfig.rules.push(convertYamlRuleToContinueRule(rule));
const convertedRule = convertYamlRuleToContinueRule(rule);
continueConfig.rules.push(convertedRule);
}
continueConfig.data = config.data;
continueConfig.data = config.data?.map((d) => ({
...d,
requestOptions: mergeConfigYamlRequestOptions(
d.requestOptions,
continueConfig.requestOptions,
),
}));
continueConfig.docs = config.docs?.map((doc) => ({
title: doc.name,
startUrl: doc.startUrl,
@ -221,25 +238,21 @@ 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.`,
});
});
continueConfig.experimental = {
modelContextProtocolServers: config.mcpServers?.map(
convertYamlMcpToContinueMcp,
),
};
// Prompt files -
try {
const promptFiles = await getAllPromptFiles(ide, undefined, true);
@ -291,9 +304,7 @@ async function configYamlToContinueConfig(options: {
try {
const llms = await llmsFromModelConfig({
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config: continueConfig,
});
@ -378,21 +389,24 @@ async function configYamlToContinueConfig(options: {
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
mcpManager.setConnections(
(config.mcpServers ?? []).map((server) => ({
id: server.name,
name: server.name,
sourceFile: server.sourceFile,
transport: {
type: "stdio",
args: [],
...(server as any), // TODO: fix the types on mcpServers in config-yaml
},
timeout: server.connectionTimeout,
})),
false,
{ ide },
);
const orgPolicy = PolicySingleton.getInstance().policy;
if (orgPolicy?.policy?.allowMcpServers === false) {
await mcpManager.shutdown();
} else {
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 };
}
@ -443,7 +457,6 @@ export async function loadContinueConfigFromYaml(options: {
await configYamlToContinueConfig({
config: configYamlResult.config,
ide,
ideSettings,
ideInfo,
uniqueId,
llmLogger,

View file

@ -1,12 +1,9 @@
import { ModelConfig } from "@continuedev/config-yaml";
import {
ContinueConfig,
IDE,
IdeSettings,
ILLMLogger,
LLMOptions,
} from "../..";
mergeConfigYamlRequestOptions,
ModelConfig,
} from "@continuedev/config-yaml";
import { ContinueConfig, ILLMLogger, LLMOptions } from "../..";
import { BaseLLM } from "../../llm";
import { LLMClasses } from "../../llm/llms";
@ -29,14 +26,12 @@ function getModelClass(
async function modelConfigToBaseLLM({
model,
uniqueId,
ideSettings,
llmLogger,
config,
isFromAutoDetect,
}: {
model: ModelConfig;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
config: ContinueConfig;
isFromAutoDetect?: boolean;
@ -49,6 +44,11 @@ async function modelConfigToBaseLLM({
const { capabilities, ...rest } = model;
const mergedRequestOptions = mergeConfigYamlRequestOptions(
rest.requestOptions,
config.requestOptions,
);
let options: LLMOptions = {
...rest,
contextLength: model.defaultCompletionOptions?.contextLength,
@ -74,6 +74,7 @@ async function modelConfigToBaseLLM({
},
autocompleteOptions: model.autocompleteOptions,
isFromAutoDetect,
requestOptions: mergedRequestOptions,
};
// Model capabilities - need to be undefined if not found
@ -154,17 +155,13 @@ async function modelConfigToBaseLLM({
async function autodetectModels({
llm,
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config,
}: {
llm: BaseLLM;
model: ModelConfig;
ide: IDE;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
@ -183,7 +180,6 @@ async function autodetectModels({
name: modelName,
},
uniqueId,
ideSettings,
llmLogger,
config,
isFromAutoDetect: true,
@ -199,23 +195,18 @@ async function autodetectModels({
export async function llmsFromModelConfig({
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config,
}: {
model: ModelConfig;
ide: IDE;
uniqueId: string;
ideSettings: IdeSettings;
llmLogger: ILLMLogger;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
const baseLlm = await modelConfigToBaseLLM({
model,
uniqueId,
ideSettings,
llmLogger,
config,
});
@ -227,9 +218,7 @@ export async function llmsFromModelConfig({
const models = await autodetectModels({
llm: baseLlm,
model,
ide,
uniqueId,
ideSettings,
llmLogger,
config,
});

View file

@ -0,0 +1,355 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { ContinueConfig, ILLMLogger } from "../..";
import { llmsFromModelConfig } from "./models";
// Mock the LLM classes
vi.mock("../../llm/llms", () => ({
LLMClasses: [
class MockOpenAI {
static providerName = "openai";
static defaultOptions = {
completionOptions: {
maxTokens: 2048,
},
};
constructor(options: any) {
Object.assign(this, options);
}
async listModels() {
return ["gpt-4", "gpt-3.5-turbo"];
}
},
class MockAnthropic {
static providerName = "anthropic";
static defaultOptions = {
completionOptions: {
maxTokens: 4096,
},
};
constructor(options: any) {
Object.assign(this, options);
}
async listModels() {
return ["claude-3-5-sonnet-20241022", "claude-3-haiku-20240307"];
}
},
],
}));
describe("llmsFromModelConfig requestOptions merging", () => {
let mockLLMLogger: ILLMLogger;
let mockConfig: ContinueConfig;
beforeEach(() => {
mockLLMLogger = { log: vi.fn() } as any;
mockConfig = {
requestOptions: {
timeout: 30000,
headers: {
"User-Agent": "Continue/1.0.0",
},
proxy: "global-proxy",
},
contextProviders: [],
mcpServerStatuses: [],
rules: [],
selectedModelByRole: {
apply: null,
autocomplete: null,
chat: null,
edit: null,
embed: null,
rerank: null,
summarize: null,
},
modelsByRole: {
apply: [],
autocomplete: [],
chat: [],
edit: [],
embed: [],
rerank: [],
summarize: [],
},
slashCommands: [],
tools: [],
allowAnonymousTelemetry: false,
} as ContinueConfig;
vi.clearAllMocks();
});
it("should merge model requestOptions with config requestOptions", async () => {
const model: ModelConfig = {
name: "test-openai",
provider: "openai",
model: "gpt-4",
requestOptions: {
timeout: 60000,
headers: {
Authorization: "Bearer token123",
},
proxy: "model-proxy",
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: mockConfig,
});
expect(result).toHaveLength(1);
const llm = result[0];
// The LLM should have merged requestOptions
expect(llm.requestOptions).toEqual({
timeout: 60000, // model-specific takes precedence
headers: {
"User-Agent": "Continue/1.0.0", // from global request options
Authorization: "Bearer token123", // from model
},
proxy: "model-proxy", // model-specific takes precedence
});
});
it("should use config requestOptions when model has no requestOptions", async () => {
const model: ModelConfig = {
name: "test-openai",
provider: "openai",
model: "gpt-4",
// no requestOptions
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: mockConfig,
});
expect(result).toHaveLength(1);
const llm = result[0];
// The LLM should have config requestOptions
expect(llm.requestOptions).toEqual(mockConfig.requestOptions);
});
it("should use model requestOptions when config has no requestOptions", async () => {
const model: ModelConfig = {
name: "test-openai",
provider: "openai",
model: "gpt-4",
requestOptions: {
timeout: 45000,
headers: {
"API-Key": "secret",
},
},
};
const configWithoutOptions = { ...mockConfig };
delete configWithoutOptions.requestOptions;
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: configWithoutOptions,
});
expect(result).toHaveLength(1);
const llm = result[0];
// The LLM should have model requestOptions
expect(llm.requestOptions).toEqual(model.requestOptions);
});
it("should handle empty headers correctly in merge", async () => {
const model: ModelConfig = {
name: "test-openai",
provider: "openai",
model: "gpt-4",
requestOptions: {
timeout: 60000,
headers: {},
},
};
const configWithEmptyHeaders = {
...mockConfig,
requestOptions: {
...mockConfig.requestOptions!,
headers: {},
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: configWithEmptyHeaders,
});
expect(result).toHaveLength(1);
const llm = result[0];
// When headers merge to empty object, they should be undefined
expect(llm.requestOptions).toEqual({
timeout: 60000,
proxy: "global-proxy",
headers: undefined,
});
});
it("should handle autodetect models with merged requestOptions", async () => {
const model: ModelConfig = {
name: "autodetect-openai",
provider: "openai",
model: "AUTODETECT",
requestOptions: {
timeout: 120000,
headers: {
"X-Custom": "autodetect",
},
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: mockConfig,
});
// Should return multiple models from listModels()
expect(result.length).toBeGreaterThan(0);
// Each detected model should have the merged requestOptions
result.forEach((llm) => {
expect(llm.requestOptions).toEqual({
timeout: 120000, // model-specific takes precedence
headers: {
"User-Agent": "Continue/1.0.0", // from global request options
"X-Custom": "autodetect", // from model
},
proxy: "global-proxy", // from global request options
});
});
});
it("should handle unknown provider gracefully", async () => {
const model: ModelConfig = {
name: "unknown-provider",
provider: "unknown",
model: "unknown-model",
requestOptions: {
timeout: 60000,
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: mockConfig,
});
// Should return empty array for unknown provider
expect(result).toHaveLength(0);
});
it("should preserve other model properties while merging requestOptions", async () => {
const model: ModelConfig = {
name: "test-anthropic",
provider: "anthropic",
model: "claude-3-5-sonnet-20241022",
roles: ["chat", "summarize"],
capabilities: ["tool_use", "image_input"],
defaultCompletionOptions: {
temperature: 0.7,
maxTokens: 1000,
},
requestOptions: {
timeout: 90000,
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: mockConfig,
});
expect(result).toHaveLength(1);
const llm = result[0];
// Should preserve model properties
expect(llm.title).toBe("test-anthropic");
expect(llm.completionOptions?.temperature).toBe(0.7);
expect(llm.completionOptions?.maxTokens).toBe(1000);
expect(llm.capabilities?.tools).toBe(true);
expect(llm.capabilities?.uploadImage).toBe(true);
// Should have merged requestOptions
expect(llm.requestOptions).toEqual({
timeout: 90000,
headers: {
"User-Agent": "Continue/1.0.0",
},
proxy: "global-proxy",
});
});
it("should handle complex header merging scenarios", async () => {
const model: ModelConfig = {
name: "complex-headers",
provider: "openai",
model: "gpt-4",
requestOptions: {
headers: {
Authorization: "Bearer model-token",
Accept: "application/json", // Should override config Accept
"X-Model-Specific": "true",
},
},
};
const configWithMoreHeaders = {
...mockConfig,
requestOptions: {
...mockConfig.requestOptions!,
headers: {
...mockConfig.requestOptions!.headers,
Accept: "text/plain", // Should be overridden by model
"Cache-Control": "no-cache",
},
},
};
const result = await llmsFromModelConfig({
model,
uniqueId: "test-id",
llmLogger: mockLLMLogger,
config: configWithMoreHeaders,
});
expect(result).toHaveLength(1);
const llm = result[0];
expect(llm.requestOptions?.headers).toEqual({
"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)
"X-Model-Specific": "true", // from model
});
});
});

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") {
@ -13,23 +24,51 @@ export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
rule: rule.rule,
globs: rule.globs,
name: rule.name,
ruleFile: rule.sourceFile,
description: rule.description,
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, requestOptions } = config;
const httpSseConfig:
| InternalStreamableHttpMcpOptions
| InternalSseMcpOptions = {
...shared,
type,
url,
requestOptions: mergeConfigYamlRequestOptions(
requestOptions,
globalRequestOptions,
),
};
return httpSseConfig;
}

View file

@ -9,11 +9,15 @@ 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 { Agent as HttpsAgent } from "https";
import {
IDE,
InternalMcpOptions,
InternalSseMcpOptions,
InternalStdioMcpOptions,
InternalStreamableHttpMcpOptions,
InternalWebsocketMcpOptions,
MCPConnectionStatus,
MCPOptions,
MCPPrompt,
MCPResource,
MCPResourceTemplate,
@ -55,6 +59,7 @@ class MCPConnection {
public status: MCPConnectionStatus = "not-connected";
public isProtectedResource = false;
public errors: string[] = [];
public infos: string[] = [];
public prompts: MCPPrompt[] = [];
public tools: MCPTool[] = [];
public resources: MCPResource[] = [];
@ -67,7 +72,7 @@ class MCPConnection {
};
constructor(
public options: MCPOptions,
public options: InternalMcpOptions,
public extras?: MCPExtras,
) {
// Don't construct transport in constructor to avoid blocking
@ -86,16 +91,18 @@ 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 {
return {
...this.options,
errors: this.errors,
infos: this.infos,
prompts: this.prompts,
resources: this.resources,
resourceTemplates: this.resourceTemplates,
@ -106,6 +113,9 @@ class MCPConnection {
}
async connectClient(forceRefresh: boolean, externalSignal: AbortSignal) {
if (this.status === "disabled") {
return;
}
if (!forceRefresh) {
// Already connected
if (this.status === "connected") {
@ -125,26 +135,27 @@ class MCPConnection {
this.resources = [];
this.resourceTemplates = [];
this.errors = [];
this.infos = [];
this.stdioOutput = { stdout: "", stderr: "" };
this.abortController.abort();
this.abortController = new AbortController();
// currently support oauth for sse transports only
if (this.options.transport.type === "sse") {
if (!this.options.transport.requestOptions) {
this.options.transport.requestOptions = {
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 +188,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 +261,6 @@ class MCPConnection {
// this.client.setNotificationHandler(, notification => {
// console.log(notification)
// })
const capabilities = this.client.getServerCapabilities();
// Resources <—> Context Provider
@ -283,6 +342,16 @@ class MCPConnection {
if (msg.includes("spawn") && msg.includes("enoent")) {
const command = msg.split(" ")[1];
errorMessage += `Error: command "${command}" not found. To use this MCP server, install the ${command} CLI.`;
if (["uv", "uvx"].includes(command)) {
this.infos.push(
'Please install uv by following the installation guide: <a href="https://docs.astral.sh/uv/getting-started/installation/">https://docs.astral.sh/uv/getting-started/installation/</a>',
);
}
if (["node", "npx"].includes(command)) {
this.infos.push(
'Please install npx by following the installation guide: <a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm">https://docs.npmjs.com/downloading-and-installing-node-js-and-npm</a>',
);
}
} else {
errorMessage += "Error: " + error.message;
}
@ -294,7 +363,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:";
@ -368,7 +437,7 @@ class MCPConnection {
}
private async resolveWorkspaceCwd(cwd: string | undefined) {
const IDE = await this.extras?.ide;
const IDE = this.extras?.ide;
if (IDE) {
const target = cwd ?? ".";
const resolved = await resolveRelativePathInDir(target, IDE);
@ -383,83 +452,99 @@ class MCPConnection {
return cwd;
}
private async constructTransportAsync(
options: MCPOptions,
): Promise<Transport> {
switch (options.transport.type) {
case "stdio":
const env: Record<string, string> = options.transport.env
? { ...options.transport.env }
: {};
private constructWebsocketTransport(
options: InternalWebsocketMcpOptions,
): WebSocketClientTransport {
return new WebSocketClientTransport(new URL(options.url));
}
if (process.env.PATH !== undefined) {
// Set the initial PATH from process.env
env.PATH = process.env.PATH;
private constructSseTransport(
options: InternalSseMcpOptions,
): SSEClientTransport {
const sseAgent =
options.requestOptions?.verifySsl === false
? new HttpsAgent({ rejectUnauthorized: false })
: undefined;
// 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);
}
return new SSEClientTransport(new URL(options.url), {
eventSourceInit: {
fetch: (input, init) =>
fetch(input, {
...init,
headers: {
...init?.headers,
...options.requestOptions?.headers,
},
...(sseAgent && { agent: sseAgent }),
}),
},
requestInit: {
headers: options.requestOptions?.headers,
...(sseAgent && { agent: sseAgent }),
},
});
}
private constructHttpTransport(
options: InternalStreamableHttpMcpOptions,
): StreamableHTTPClientTransport {
const { url, requestOptions } = options;
const streamableAgent =
requestOptions?.verifySsl === false
? new HttpsAgent({ rejectUnauthorized: false })
: undefined;
return new StreamableHTTPClientTransport(new URL(url), {
requestInit: {
headers: requestOptions?.headers,
...(streamableAgent && { agent: streamableAgent }),
},
});
}
private async constructStdioTransport(
options: InternalStdioMcpOptions,
): Promise<StdioClientTransport> {
const env: Record<string, string> = options.env ? { ...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);
}
// 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: await this.resolveCwd(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":
return new SSEClientTransport(new URL(options.transport.url), {
eventSourceInit: {
fetch: (input, init) =>
fetch(input, {
...init,
headers: {
...init?.headers,
...(options.transport.requestOptions?.headers as
| Record<string, string>
| undefined),
},
}),
},
requestInit: { headers: options.transport.requestOptions?.headers },
});
case "streamable-http":
return new StreamableHTTPClientTransport(
new URL(options.transport.url),
{
requestInit: { headers: options.transport.requestOptions?.headers },
},
);
default:
throw new Error(
`Unsupported transport type: ${(options.transport as any).type}`,
);
}
}
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,10 @@
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";
@ -17,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);
@ -34,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);
@ -70,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);
@ -85,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",
},
},
};
@ -109,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);
@ -127,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);
@ -143,6 +135,7 @@ describe("MCPConnection", () => {
expect(status).toEqual({
...options,
errors: [],
infos: [],
isProtectedResource: false,
prompts: [],
resources: [],
@ -157,11 +150,9 @@ describe("MCPConnection", () => {
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 () => {
@ -187,14 +178,12 @@ describe("MCPConnection", () => {
});
describe("connectClient", () => {
const options = {
const options: InternalStdioMcpOptions = {
name: "test-mcp",
id: "test-id",
transport: {
type: "stdio" as const,
command: "test-cmd",
args: [],
},
type: "stdio",
command: "test-cmd",
args: [],
};
it("should connect successfully", async () => {
@ -315,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
};
@ -348,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,17 +50,23 @@ export class MCPManagerSingleton {
return this.connections.get(id);
}
async removeConnection(id: string) {
const connection = this.connections.get(id);
if (connection) {
await connection.client.close();
async shutdown() {
if (this.connections.size > 0) {
await Promise.allSettled(
Array.from(this.connections.entries()).map(([id, connection]) => {
try {
connection.abortController.abort();
void connection.client.close();
} finally {
this.connections.delete(id);
}
}),
);
}
this.connections.delete(id);
}
setConnections(
servers: MCPOptions[],
servers: InternalMcpOptions[],
forceRefresh: boolean,
extras?: MCPExtras,
) {
@ -61,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;
@ -96,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])
);
}
@ -166,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,204 @@
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,
})),
);
return convertYamlMcpConfigToInternalMcpOptions(
c.yamlConfig,
globalRequestOptions,
);
});
// Parse and convert files
return {
mcpServers,
errors,
};
}

View file

@ -16,7 +16,7 @@ class CodeContextProvider extends BaseContextProvider {
displayTitle: "Code",
description: "Type to search",
type: "submenu",
dependsOnIndexing: true,
dependsOnIndexing: ["chunk", "codeSnippets"],
};
async getContextItems(

View file

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

View file

@ -19,7 +19,7 @@ class FolderContextProvider extends BaseContextProvider {
displayTitle: "Folder",
description: "Type to search",
type: "submenu",
dependsOnIndexing: true,
dependsOnIndexing: ["embeddings", "fullTextSearch", "chunk"],
};
async getContextItems(

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

@ -28,11 +28,9 @@ async function getContextProviderExtras(
): Promise<ContextProviderExtras> {
setUpTestDir();
const ide = new FileSystemIde(TEST_DIR);
const ideSettingsPromise = ide.getIdeSettings();
const llmLogger = new LLMLogger();
const configHandler = new ConfigHandler(
ide,
ideSettingsPromise,
llmLogger,
Promise.resolve(undefined),
);

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

@ -11,10 +11,19 @@ import {
import fetch, { RequestInit, Response } from "node-fetch";
import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
import { IdeInfo, IdeSettings, ModelDescription } from "../index.js";
import {
IDE,
ModelDescription,
Session,
BaseSessionMetadata,
} from "../index.js";
import { Logger } from "../util/Logger.js";
import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
import {
ControlPlaneSessionInfo,
HubSessionInfo,
isOnPremSession,
} from "./AuthTypes.js";
import { getControlPlaneEnv } from "./env.js";
export interface PolicyResponse {
@ -41,11 +50,15 @@ export interface FreeTrialStatus {
export const TRIAL_PROXY_URL =
"https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
export interface RemoteSessionMetadata extends BaseSessionMetadata {
isRemote: true;
remoteId: string;
}
export class ControlPlaneClient {
constructor(
readonly sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
private readonly ideSettingsPromise: Promise<IdeSettings>,
private readonly ideInfoPromise: Promise<IdeInfo>,
private readonly ide: IDE,
) {}
async resolveFQSNs(
@ -90,9 +103,9 @@ export class ControlPlaneClient {
throw new Error("No access token");
}
const env = await getControlPlaneEnv(this.ideSettingsPromise);
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
const url = new URL(path, env.CONTROL_PLANE_URL).toString();
const ideInfo = await this.ideInfoPromise;
const ideInfo = await this.ide.getIdeInfo();
const resp = await fetch(url, {
...init,
@ -304,4 +317,127 @@ export class ControlPlaneClient {
return null;
}
}
/**
* 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
if (!(await this.isSignedIn())) {
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;
} catch (e) {
Logger.error(e, {
context: "control_plane_check_remote_sessions_enabled",
});
return false;
}
}
/**
* Get current user's session info
*/
public async getSessionInfo(): Promise<ControlPlaneSessionInfo | undefined> {
return await this.sessionInfoPromise;
}
/**
* 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())) {
return [];
}
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",
});
const agents = (await resp.json()) as any[];
return agents.map(
(agent: any): RemoteSessionMetadata => ({
sessionId: `remote-${agent.id}`,
title: agent.name || "Remote Agent",
dateCreated: new Date(agent.create_time_ms).toISOString(),
workspaceDirectory: "",
isRemote: true,
remoteId: agent.id,
}),
);
} catch (e) {
// Log error but don't throw - remote sessions are optional
Logger.error(e, {
context: "control_plane_list_remote_sessions",
});
return [];
}
}
public async loadRemoteSession(remoteId: string): Promise<Session> {
if (!(await this.isSignedIn())) {
throw new Error("Not signed in to load remote session");
}
try {
// First get the tunnel URL for the remote agent
const tunnelResp = await this.requestAndHandleError(
`agents/devboxes/${remoteId}/tunnel`,
{
method: "POST",
},
);
const tunnelData = (await tunnelResp.json()) as { url?: string };
const tunnelUrl = tunnelData.url;
if (!tunnelUrl) {
throw new Error(`Failed to get tunnel URL for agent ${remoteId}`);
}
// Now fetch the session state from the remote agent's /state endpoint
const stateResponse = await fetch(`${tunnelUrl}/state`);
if (!stateResponse.ok) {
throw new Error(
`Failed to fetch state from remote agent: ${stateResponse.statusText}`,
);
}
const remoteState = (await stateResponse.json()) as { session?: Session };
// The remote state contains a session property with the full session data
if (!remoteState.session) {
throw new Error(
"Remote agent returned invalid state - no session found",
);
}
return remoteState.session;
} catch (e) {
Logger.error(e, {
context: "control_plane_load_remote_session",
remoteId,
});
throw new Error(
`Failed to load remote session: ${e instanceof Error ? e.message : "Unknown error"}`,
);
}
}
}

View file

@ -8,7 +8,6 @@ import {
prevFilepaths,
} from "./autocomplete/util/openedFilesLruCache";
import { ConfigHandler } from "./config/ConfigHandler";
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
import { addModel, deleteModel } from "./config/util";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
import { getControlPlaneEnv } from "./control-plane/env";
@ -17,6 +16,7 @@ import { DataLogger } from "./data/log";
import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { countTokens } from "./llm/countTokens";
import Lemonade from "./llm/llms/Lemonade";
import Ollama from "./llm/llms/Ollama";
import { EditAggregator } from "./nextEdit/context/aggregateEdits";
import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
@ -29,8 +29,9 @@ import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
import { Telemetry } from "./util/posthog";
import {
isProcessBackgrounded,
killTerminalProcess,
markProcessAsBackgrounded,
} from "./util/processTerminalBackgroundStates";
} from "./util/processTerminalStates";
import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
@ -47,18 +48,25 @@ import {
type IDE,
} from ".";
import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
import { ConfigYaml } from "@continuedev/config-yaml";
import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
import { createNewAssistantFile } from "./config/createNewAssistantFile";
import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
import {
isColocatedRulesFile,
isContinueAgentConfigFile,
isContinueConfigRelatedUri,
} from "./config/loadLocalAssistants";
import { CodebaseRulesCache } from "./config/markdown/loadCodebaseRules";
import {
setupLocalConfig,
setupProviderConfig,
setupQuickstartConfig,
} from "./config/onboarding";
import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
import {
createNewGlobalRuleFile,
createNewWorkspaceBlockFile,
} from "./config/workspace/workspaceBlocks";
import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
import { performAuth, removeMCPAuth } from "./context/mcp/MCPOauth";
import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
@ -67,7 +75,6 @@ import { streamDiffLines } from "./edit/streamDiffLines";
import { shouldIgnore } from "./indexing/shouldIgnore";
import { walkDirCache } from "./indexing/walkDir";
import { LLMLogger } from "./llm/logger";
import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants";
import { llmStreamChat } from "./llm/streamChat";
import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting";
import { processSmallEdit } from "./nextEdit/context/processSmallEdit";
@ -76,18 +83,9 @@ import { NextEditProvider } from "./nextEdit/NextEditProvider";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import { OnboardingModes } from "./protocol/core";
import type { IMessenger, Message } from "./protocol/messenger";
import { ContinueError, ContinueErrorReason } from "./util/errors";
import { shareSession } from "./util/historyUtils";
import { Logger } from "./util/Logger.js";
import { getUriPathBasename } from "./util/uri";
const hasRulesFiles = (uris: string[]): boolean => {
for (const uri of uris) {
const filename = getUriPathBasename(uri);
if (filename === RULES_MARKDOWN_FILENAME) {
return true;
}
}
return false;
};
export class Core {
configHandler: ConfigHandler;
@ -138,7 +136,7 @@ export class Core {
const ideInfoPromise = messenger.request("getIdeInfo", undefined);
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
const sessionInfoPromise = messenger.request(
const initialSessionInfoPromise = messenger.request(
"getControlPlaneSessionInfo",
{
silent: true,
@ -148,9 +146,8 @@ export class Core {
this.configHandler = new ConfigHandler(
this.ide,
ideSettingsPromise,
this.llmLogger,
sessionInfoPromise,
initialSessionInfoPromise,
);
this.docsService = DocsService.createSingleton(
@ -175,6 +172,13 @@ export class Core {
}
};
this.codeBaseIndexer = new CodebaseIndexer(
this.configHandler,
this.ide,
this.messenger,
this.globalContext.get("indexingPaused"),
);
this.configHandler.onConfigUpdate((result) => {
void (async () => {
const serializedResult =
@ -187,6 +191,12 @@ export class Core {
selectedOrgId: this.configHandler.currentOrg?.id ?? null,
});
if (await this.codeBaseIndexer.wasAnyOneIndexAdded()) {
await this.codeBaseIndexer.refreshCodebaseIndex(
await this.ide.getWorkspaceDirs(),
);
}
// update additional submenu context providers registered via VSCode API
const additionalProviders =
this.configHandler.getAdditionalSubmenuContextProviders();
@ -198,13 +208,6 @@ export class Core {
})();
});
this.codeBaseIndexer = new CodebaseIndexer(
this.configHandler,
this.ide,
this.messenger,
this.globalContext.get("indexingPaused"),
);
// Dev Data Logger
const dataLogger = DataLogger.getInstance();
dataLogger.core = this;
@ -225,6 +228,17 @@ export class Core {
return;
}
// Check for disableIndexing to prevent race condition
const { config } = await this.configHandler.loadConfig();
if (!config || config.disableIndexing) {
void this.messenger.request("indexProgress", {
progress: 0,
desc: "Indexing is disabled",
status: "disabled",
});
return;
}
void this.codeBaseIndexer.refreshCodebaseIndex(dirs);
});
});
@ -307,8 +321,27 @@ export class Core {
});
// History
on("history/list", (msg) => {
return historyManager.list(msg.data);
on("history/list", async (msg) => {
const localSessions = historyManager.list(msg.data);
// Check if remote sessions should be enabled based on feature flags
const shouldFetchRemote =
await this.configHandler.controlPlaneClient.shouldEnableRemoteSessions();
// Get remote sessions from control plane if feature is enabled
const remoteSessions = shouldFetchRemote
? await this.configHandler.controlPlaneClient.listRemoteSessions()
: [];
// Combine and sort by date (most recent first)
const allSessions = [...localSessions, ...remoteSessions].sort(
(a, b) =>
new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime(),
);
// Apply limit if specified
const limit = msg.data?.limit ?? 100;
return allSessions.slice(0, limit);
});
on("history/delete", (msg) => {
@ -319,10 +352,23 @@ export class Core {
return historyManager.load(msg.data.id);
});
on("history/loadRemote", async (msg) => {
return this.configHandler.controlPlaneClient.loadRemoteSession(
msg.data.remoteId,
);
});
on("history/save", (msg) => {
historyManager.save(msg.data);
});
on("history/share", async (msg) => {
const session = historyManager.load(msg.data.id);
const outputDir = msg.data.outputDir;
const history = session.history.map((msg) => msg.message);
await shareSession(this.ide, history, outputDir);
});
on("history/clear", (msg) => {
historyManager.clearAll();
});
@ -368,11 +414,19 @@ export class Core {
);
});
on("config/addGlobalRule", async (msg) => {
try {
await createNewGlobalRuleFile(this.ide);
await this.configHandler.reloadConfig(
"Global rule created (config/addGlobalRule message)",
);
} catch (error) {
throw error;
}
});
on("config/openProfile", async (msg) => {
await this.configHandler.openConfigProfile(
msg.data.profileId,
msg.data?.element,
);
await this.configHandler.openConfigProfile(msg.data.profileId);
});
on("config/ideSettingsUpdate", async (msg) => {
@ -442,6 +496,10 @@ export class Core {
on("mcp/reloadServer", async (msg) => {
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
});
on("mcp/setServerEnabled", async (msg) => {
const { id, enabled } = msg.data;
await MCPManagerSingleton.getInstance().setEnabled(id, enabled);
});
on("mcp/getPrompt", async (msg) => {
const { serverName, promptName, args } = msg.data;
const prompt = await MCPManagerSingleton.getInstance().getPrompt(
@ -457,15 +515,26 @@ export class Core {
});
on("mcp/startAuthentication", async (msg) => {
await new Promise((resolve) => setTimeout(resolve, 5000));
MCPManagerSingleton.getInstance().setStatus(msg.data, "authenticating");
const status = await performAuth(msg.data, this.ide);
MCPManagerSingleton.getInstance().setStatus(
msg.data.serverId,
"authenticating",
);
const status = await performAuth(
msg.data.serverId,
msg.data.serverUrl,
this.ide,
);
if (status === "AUTHORIZED") {
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
await MCPManagerSingleton.getInstance().refreshConnection(
msg.data.serverId,
);
}
});
on("mcp/removeAuthentication", async (msg) => {
removeMCPAuth(msg.data, this.ide);
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
removeMCPAuth(msg.data.serverUrl, this.ide);
await MCPManagerSingleton.getInstance().refreshConnection(
msg.data.serverId,
);
});
// Context providers
@ -668,6 +737,8 @@ export class Core {
return queue.dequeueProcessed() || null;
});
// NOTE: This is not used unless prefetch is used.
// At this point this is not used because I opted to rely on the model to return multiple diffs than to use prefetching.
on("nextEdit/queue/processOne", async (msg) => {
console.log("nextEdit/queue/processOne");
const { ctx, recentlyVisitedRanges, recentlyEditedRanges } = msg.data;
@ -720,20 +791,13 @@ export class Core {
data.fileUri ?? "current-file-stream",
); // not super important since currently cancelling apply will cancel all streams it's one file at a time
return streamDiffLines({
highlighted: data.highlighted,
prefix: data.prefix,
suffix: data.suffix,
return streamDiffLines(
data,
llm,
// rules included for edit, NOT apply
rulesToInclude: data.includeRulesInSystemMessage
? config.rules
: undefined,
input: data.input,
language: data.language,
overridePrompt: undefined,
abortController,
});
undefined,
data.includeRulesInSystemMessage ? config.rules : undefined,
);
});
on("cancelApply", async (msg) => {
@ -763,7 +827,6 @@ export class Core {
if (data?.shouldClearIndexes) {
await this.codeBaseIndexer.clearIndexes();
}
const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs());
await this.codeBaseIndexer.refreshCodebaseIndex(dirs);
});
@ -804,45 +867,70 @@ export class Core {
};
on("files/created", async ({ data }) => {
if (data?.uris?.length) {
walkDirCache.invalidate();
void refreshIfNotIgnored(data.uris);
if (!data?.uris?.length) {
return;
}
if (hasRulesFiles(data.uris)) {
const rulesCache = CodebaseRulesCache.getInstance();
await Promise.all(
data.uris.map((uri) => rulesCache.update(this.ide, uri)),
);
await this.configHandler.reloadConfig("Rules file created");
}
// If it's a local assistant being created, we want to reload all assistants so it shows up in the list
let localAssistantCreated = false;
for (const uri of data.uris) {
if (isLocalDefinitionFile(uri)) {
localAssistantCreated = true;
}
}
if (localAssistantCreated) {
await this.configHandler.refreshAll("Local assistant file created");
}
walkDirCache.invalidate();
void refreshIfNotIgnored(data.uris);
const colocatedRulesUris = data.uris.filter(isColocatedRulesFile);
const nonColocatedRuleUris = data.uris.filter(
(uri) => !isColocatedRulesFile(uri),
);
if (colocatedRulesUris) {
const rulesCache = CodebaseRulesCache.getInstance();
void Promise.all(
colocatedRulesUris.map((uri) => rulesCache.update(this.ide, uri)),
).then(() => {
void this.configHandler.reloadConfig("Codebase rule file created");
});
}
// If it's a local agent being created, we want to reload all agent so it shows up in the list
if (nonColocatedRuleUris.some(isContinueAgentConfigFile)) {
await this.configHandler.refreshAll("Local assistant file created");
} else if (nonColocatedRuleUris.some(isContinueConfigRelatedUri)) {
await this.configHandler.reloadConfig(
".continue config-related file created",
);
}
});
on("files/deleted", async ({ data }) => {
if (data?.uris?.length) {
walkDirCache.invalidate();
void refreshIfNotIgnored(data.uris);
if (!data?.uris?.length) {
return;
}
if (hasRulesFiles(data.uris)) {
const rulesCache = CodebaseRulesCache.getInstance();
data.uris.forEach((uri) => rulesCache.remove(uri));
await this.configHandler.reloadConfig("Codebase rule file deleted");
}
walkDirCache.invalidate();
void refreshIfNotIgnored(data.uris);
const colocatedRulesUris = data.uris.filter(isColocatedRulesFile);
const nonColocatedRuleUris = data.uris.filter(
(uri) => !isColocatedRulesFile(uri),
);
if (colocatedRulesUris) {
const rulesCache = CodebaseRulesCache.getInstance();
void Promise.all(
colocatedRulesUris.map((uri) => rulesCache.remove(uri)),
).then(() => {
void this.configHandler.reloadConfig("Codebase rule file deleted");
});
}
// If it's a local agent being deleted, we want to reload all agent so it disappears from the list
if (nonColocatedRuleUris.some(isContinueAgentConfigFile)) {
await this.configHandler.refreshAll("Local assistant file deleted");
} else if (nonColocatedRuleUris.some(isContinueConfigRelatedUri)) {
await this.configHandler.reloadConfig(
".continue config-related file deleted",
);
}
});
on("files/closed", async ({ data }) => {
console.log("deleteChain called from files/closed");
console.debug("deleteChain called from files/closed");
await NextEditProvider.getInstance().deleteChain();
try {
@ -1007,6 +1095,66 @@ export class Core {
this.handleToolCall(toolCall),
);
on(
"tools/evaluatePolicy",
async ({ data: { toolName, basePolicy, args } }) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
const tool = config.tools.find((t) => t.function.name === toolName);
if (!tool) {
return { policy: basePolicy };
}
// Extract display value for specific tools
let displayValue: string | undefined;
if (toolName === "runTerminalCommand" && args.command) {
displayValue = args.command as string;
}
if (tool.evaluateToolCallPolicy) {
const evaluatedPolicy = tool.evaluateToolCallPolicy(basePolicy, args);
return { policy: evaluatedPolicy, displayValue };
}
return { policy: basePolicy, displayValue };
},
);
on("tools/preprocessArgs", async ({ data: { toolName, args } }) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
const tool = config?.tools.find((t) => t.function.name === toolName);
if (!tool) {
throw new Error(`Tool ${toolName} not found`);
}
try {
const preprocessedArgs = await tool.preprocessArgs?.(args, {
ide: this.ide,
});
return {
preprocessedArgs,
};
} catch (e) {
let errorReason =
e instanceof ContinueError ? e.reason : ContinueErrorReason.Unknown;
let errorMessage =
e instanceof Error
? e.message
: `Error preprocessing tool call args for ${toolName}\n${JSON.stringify(args)}`;
return {
preprocessedArgs: undefined,
errorReason,
errorMessage,
};
}
});
on("isItemTooBig", async ({ data: { item } }) => {
return this.isItemTooBig(item);
});
@ -1024,6 +1172,10 @@ export class Core {
},
);
on("process/killTerminalProcess", async ({ data: { toolCallId } }) => {
await killTerminalProcess(toolCallId);
});
on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
const isValid = setMdmLicenseKey(licenseKey);
return isValid;
@ -1131,10 +1283,9 @@ export class Core {
const diffCache = GitDiffCache.getInstance(getDiffFn(this.ide));
diffCache.invalidate();
walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes
const currentProfileUri =
this.configHandler.currentProfile?.profileDescription.uri ?? "";
for (const uri of data.uris) {
const currentProfileUri =
this.configHandler.currentProfile?.profileDescription.uri ?? "";
if (URI.equal(uri, currentProfileUri)) {
// Trigger a toast notification to provide UI feedback that config has been updated
const showToast =
@ -1154,21 +1305,7 @@ export class Core {
);
continue;
}
if (
uri.endsWith(".continuerc.json") ||
uri.endsWith(".prompt") ||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
(uri.includes(".continue") &&
(uri.endsWith(".yaml") || uri.endsWith("yml"))) ||
BLOCK_TYPES.some((blockType) =>
uri.includes(`.continue/${blockType}`),
)
) {
await this.configHandler.reloadConfig(
"Config-related file updated: continuerc, prompt, local block, etc",
);
} else if (uri.endsWith(RULES_MARKDOWN_FILENAME)) {
if (isColocatedRulesFile(uri)) {
try {
const codebaseRulesCache = CodebaseRulesCache.getInstance();
void codebaseRulesCache.update(this.ide, uri).then(() => {
@ -1177,6 +1314,10 @@ export class Core {
} catch (e) {
Logger.error(`Failed to update codebase rule: ${e}`);
}
} else if (isContinueConfigRelatedUri(uri)) {
await this.configHandler.reloadConfig(
"Local config-related file updated",
);
} else if (
uri.endsWith(".continueignore") ||
uri.endsWith(".gitignore")
@ -1220,6 +1361,9 @@ export class Core {
if (msg.data.title === "Ollama") {
const models = await new Ollama({ model: "" }).listModels();
return models;
} else if (msg.data.title === "Lemonade") {
const models = await new Lemonade({ model: "" }).listModels();
return models;
} else {
return undefined;
}
@ -1305,6 +1449,8 @@ export class Core {
selectedCode,
reranker: config.selectedModelByRole.rerank,
fetch: (url, init) =>
// Important note: context providers fetch uses global request options not LLM request options
// Because LLM calls are handled separately
fetchwithRequestOptions(url, init, config.requestOptions),
isInAgentMode: msg.data.isInAgentMode,
});

View file

@ -1 +1,3 @@
export const EDIT_MODE_STREAM_ID = "edit-mode";
export const APPLY_UNIQUE_TOKEN = "<|!@#IS_APPLY!@#|>";

View file

@ -1,7 +1,14 @@
import { ChatMessage, ILLM, Prediction, PromptLog } from "..";
import {
ChatMessage,
ILLM,
Prediction,
PromptLog,
type StreamDiffLinesType,
} from "..";
import { DEFAULT_MAX_TOKENS } from "../llm/constants";
import { countTokens } from "../llm/countTokens";
import { renderChatMessage } from "../util/messageContent";
import { APPLY_UNIQUE_TOKEN } from "./constants.js";
const INFINITE_STREAM_SAFETY = 0.9;
@ -17,6 +24,7 @@ const RECURSIVE_PROMPT = `Continue EXACTLY where you left`;
export async function* recursiveStream(
llm: ILLM,
abortController: AbortController,
type: StreamDiffLinesType,
prompt: ChatMessage[] | string,
prediction: Prediction | undefined,
currentBuffer = "",
@ -28,8 +36,11 @@ export async function* recursiveStream(
let buffer = currentBuffer;
// let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries
const injectApplyToken = type === "apply" && shouldInjectApplyToken(llm);
if (typeof prompt === "string") {
const generator = llm.streamComplete(prompt, abortController.signal, {
const finalPrompt = injectApplyToken ? prompt + APPLY_UNIQUE_TOKEN : prompt;
const generator = llm.streamComplete(finalPrompt, abortController.signal, {
raw: true,
prediction: undefined,
reasoning: false,
@ -62,7 +73,11 @@ export async function* recursiveStream(
}
}
} else {
const generator = llm.streamChat(prompt, abortController.signal, {
const promptMessages = injectApplyToken
? appendTokenToLastMessage(prompt, APPLY_UNIQUE_TOKEN)
: prompt;
const generator = llm.streamChat(promptMessages, abortController.signal, {
raw: true,
prediction: undefined,
reasoning: false,
@ -104,3 +119,36 @@ export async function* recursiveStream(
}
}
}
function shouldInjectApplyToken(llm: ILLM): boolean {
const model = llm.model?.toLowerCase() ?? "";
return (
llm.underlyingProviderName === "inception" && model.includes("mercury")
);
}
function appendTokenToLastMessage(
messages: ChatMessage[],
token: string,
): ChatMessage[] {
if (messages.length === 0) {
return messages;
}
const lastMessage = messages[messages.length - 1];
if (typeof lastMessage.content !== "string") {
return messages;
}
if (lastMessage.content.endsWith(token)) {
return messages;
}
const updatedMessages = [...messages];
updatedMessages[updatedMessages.length - 1] = {
...lastMessage,
content: lastMessage.content + token,
};
return updatedMessages;
}

View file

@ -0,0 +1,252 @@
import { describe, expect, it } from "vitest";
import { ContinueErrorReason } from "../../util/errors";
import { executeFindAndReplace } from "./performReplace";
describe("executeFindAndReplace", () => {
describe("normal cases", () => {
it("should replace single occurrence by default", () => {
const content = "Hello world\nThis is a test file\nGoodbye";
const result = executeFindAndReplace(content, "Hello", "Hi", false);
expect(result).toBe("Hi world\nThis is a test file\nGoodbye");
});
it("should replace single occurrence when replaceAll is false", () => {
const content = "Hello world\nHello again";
const result = executeFindAndReplace(
content,
"Hello world",
"Hi world",
false,
);
expect(result).toBe("Hi world\nHello again");
});
it("should replace all occurrences when replaceAll is true", () => {
const content = "Hello world\nHello again\nHello there";
const result = executeFindAndReplace(content, "Hello", "Hi", true);
expect(result).toBe("Hi world\nHi again\nHi there");
});
it("should handle empty new string (deletion)", () => {
const content = "Hello world";
const result = executeFindAndReplace(content, "Hello ", "", false);
expect(result).toBe("world");
});
it("should handle empty old string replacement (insertion at start)", () => {
const content = "";
const result = executeFindAndReplace(content, "", "Hello world", false);
expect(result).toBe("Hello world");
});
it("should preserve whitespace and indentation", () => {
const content =
"function test() {\n const value = 'old';\n return value;\n}";
const result = executeFindAndReplace(
content,
" const value = 'old';",
" const value = 'new';",
false,
);
expect(result).toBe(
"function test() {\n const value = 'new';\n return value;\n}",
);
});
it("should handle multiline strings", () => {
const content = "line1\nline2\nline3";
const result = executeFindAndReplace(
content,
"line1\nline2",
"newline1\nnewline2",
false,
);
expect(result).toBe("newline1\nnewline2\nline3");
});
});
describe("special character handling", () => {
it("should handle regex special characters in old string", () => {
const content = "const regex = /[a-z]+/g;";
const result = executeFindAndReplace(
content,
"/[a-z]+/g",
"/[A-Z]+/g",
false,
);
expect(result).toBe("const regex = /[A-Z]+/g;");
});
it("should handle dollar signs in strings", () => {
const content = 'const text = "Hello $world"';
const result = executeFindAndReplace(
content,
'"Hello $world"',
'"Hi $universe"',
false,
);
expect(result).toBe('const text = "Hi $universe"');
});
it("should handle backslashes", () => {
const content = 'const path = "C:\\Users\\test"';
const result = executeFindAndReplace(
content,
"C:\\Users\\test",
"D:\\Users\\test",
false,
);
expect(result).toBe('const path = "D:\\Users\\test"');
});
it("should handle parentheses", () => {
const content = "function test() { return 'old'; }";
const result = executeFindAndReplace(
content,
"() { return 'old'; }",
"() { return 'new'; }",
false,
);
expect(result).toBe("function test() { return 'new'; }");
});
it("should handle square brackets", () => {
const content = "const arr = [1, 2, 3];";
const result = executeFindAndReplace(
content,
"[1, 2, 3]",
"[4, 5, 6]",
false,
);
expect(result).toBe("const arr = [4, 5, 6];");
});
});
describe("replaceAll behavior", () => {
it("should replace all occurrences including partial matches", () => {
const content = "test testing tested test";
const result = executeFindAndReplace(content, "test", "exam", true);
expect(result).toBe("exam examing examed exam");
});
it("should replace all occurrences with empty string", () => {
const content = "remove this remove that remove everything";
const result = executeFindAndReplace(content, "remove ", "", true);
expect(result).toBe("this that everything");
});
it("should handle overlapping patterns correctly", () => {
const content = "aaaa";
const result = executeFindAndReplace(content, "aa", "b", true);
expect(result).toBe("bb");
});
});
describe("error cases", () => {
it("should throw error when string not found", () => {
const content = "Hello world";
expect(() => {
executeFindAndReplace(content, "xyz", "abc", false);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceOldStringNotFound,
}),
);
});
it("should throw error with edit context when string not found", () => {
const content = "Hello world";
expect(() => {
executeFindAndReplace(content, "xyz", "abc", false, 2);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceOldStringNotFound,
}),
);
});
it("should throw error when multiple occurrences exist and replaceAll is false", () => {
const content = "Hello world\nHello again\nHello there";
expect(() => {
executeFindAndReplace(content, "Hello", "Hi", false);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences,
}),
);
});
it("should throw error with edit context for multiple occurrences", () => {
const content = "test test test";
expect(() => {
executeFindAndReplace(content, "test", "exam", false, 1);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMultipleOccurrences,
}),
);
});
});
describe("edge cases", () => {
it("should handle single character replacement", () => {
const content = "a b c";
const result = executeFindAndReplace(content, "b", "x", false);
expect(result).toBe("a x c");
});
it("should handle very long strings", () => {
const longString = "a".repeat(10000);
const content = `start${longString}end`;
const result = executeFindAndReplace(content, longString, "short", false);
expect(result).toBe("startshortend");
});
it("should handle strings at beginning of content", () => {
const content = "start middle end";
const result = executeFindAndReplace(content, "start", "begin", false);
expect(result).toBe("begin middle end");
});
it("should handle strings at end of content", () => {
const content = "start middle end";
const result = executeFindAndReplace(content, "end", "finish", false);
expect(result).toBe("start middle finish");
});
it("should handle entire content replacement", () => {
const content = "replace everything";
const result = executeFindAndReplace(
content,
"replace everything",
"new content",
false,
);
expect(result).toBe("new content");
});
});
});

View file

@ -0,0 +1,61 @@
import { ContinueError, ContinueErrorReason } from "../../util/errors";
export const FOUND_MULTIPLE_FIND_STRINGS_ERROR =
"Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.";
/**
* Validates a single edit operation
*/
export function validateSingleEdit(
oldString: unknown,
newString: unknown,
replaceAll: unknown,
index?: number,
): { oldString: string; newString: string; replaceAll?: boolean } {
const context = index !== undefined ? `edit at index ${index}: ` : "";
if (oldString === undefined || typeof oldString !== "string") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingOldString,
`${context}string old_string is required`,
);
}
if (newString === undefined || typeof newString !== "string") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingNewString,
`${context}string new_string is required`,
);
}
if (oldString === newString) {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
`${context}old_string and new_string must be different`,
);
}
if (replaceAll !== undefined && typeof replaceAll !== "boolean") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceInvalidReplaceAll,
`${context}replace_all must be a valid boolean`,
);
}
return { oldString, newString, replaceAll };
}
export function trimEmptyLines({
lines,
fromEnd,
}: {
lines: string[];
fromEnd: boolean;
}): string[] {
lines = fromEnd ? lines.slice().reverse() : lines.slice();
const newLines: string[] = [];
let shouldContinueRemoving = true;
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
if (shouldContinueRemoving && line.trim() === "") continue;
shouldContinueRemoving = false;
newLines.push(line);
}
return fromEnd ? newLines.reverse() : newLines;
}

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