Merge branch 'main' into remove_runtime_esbuild

This commit is contained in:
Dallin Romney 2025-10-09 13:53:01 -07:00 • committed by GitHub
commit b1bb2b1914
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
331 changed files with 18523 additions and 8399 deletions

View file

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

@ -119,12 +119,12 @@ jobs:
run: npm audit --audit-level=moderate
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
uses: github/codeql-action/init@v4
with:
languages: javascript
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
uses: github/codeql-action/analyze@v4
# Use this for any files that we want to be certain exist
# Basically creates a forcing function to discuss were anyone to want to remove them

View file

@ -1,6 +1,9 @@
name: Continue General Review
on:
push:
branches:
- nate/fix-wf
pull_request:
types: [opened, ready_for_review]
issue_comment:

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

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

@ -3,6 +3,8 @@
"system_setup_commands": [
"npm i -g @continuedev/cli@latest",
"sudo apt update",
"sudo apt install -y ripgrep"
"sudo apt install -y ripgrep",
"sudo apt install asciinema",
"sudo apt install expect"
]
}

View file

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

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

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

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

View file

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

View file

@ -170,62 +170,11 @@ runs:
PR_NUMBER="${{ github.event.issue.number }}"
fi
# Get PR diff
gh pr diff $PR_NUMBER > pr_diff.txt
# Get PR details
PR_TITLE=$(gh pr view $PR_NUMBER --json title -q .title)
PR_AUTHOR=$(gh pr view $PR_NUMBER --json author -q .author.login)
PR_BODY=$(gh pr view $PR_NUMBER --json body -q .body)
FILES_CHANGED=$(gh pr view $PR_NUMBER --json files -q '.files | length')
# Create review prompt
cat > review_prompt.txt << EOF
You are reviewing a pull request. Please provide helpful, context-aware feedback.
CONTEXT:
- Repository: ${{ github.repository }}
- PR #$PR_NUMBER: $PR_TITLE
- Files Changed: $FILES_CHANGED
- Author: $PR_AUTHOR
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: ${PR_BODY:-No description provided}
Code Changes:
EOF
# Add the diff
cat pr_diff.txt >> review_prompt.txt
cat >> review_prompt.txt << 'EOF'
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.
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'
@ -247,15 +196,7 @@ runs:
if [ -z "$CONTINUE_API_KEY" ]; then
echo "Warning: CONTINUE_API_KEY environment variable is not set"
# Create fallback review and continue
cat > code_review.md << 'EOF'
## Code Review Summary
⚠️ AI review skipped: CONTINUE_API_KEY not configured.
### Configuration Required
- Please set the CONTINUE_API_KEY secret in repository settings
- Verify that the organization and config path are valid
EOF
node 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
@ -277,15 +218,7 @@ runs:
echo "Testing Continue CLI..."
if ! which cn > /dev/null 2>&1; then
echo "Warning: Continue CLI not found or not working"
cat > code_review.md << 'EOF'
## Code Review Summary
⚠️ AI review skipped: Continue CLI installation failed.
### Troubleshooting
- Check that npm installation succeeded
- Verify @continuedev/cli package is available
EOF
node 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)"
@ -321,11 +254,7 @@ runs:
# Check if output is empty
if [ ! -s code_review.md ]; then
echo "Warning: Continue CLI returned empty output"
cat > code_review.md << 'EOF'
## Code Review Summary
⚠️ Continue CLI returned an empty response. Please check the configuration.
EOF
node actions/general-review/scripts/writeMarkdown.js code_review.md empty_output
fi
else
echo "Error: Continue CLI command failed with exit code $?"
@ -334,34 +263,13 @@ runs:
# Check for specific error patterns
if grep -q "not found\|ENOENT" cli_error.log 2>/dev/null; then
cat > code_review.md << 'EOF'
## Code Review Summary
⚠️ Continue CLI is not properly installed. Please ensure @continuedev/cli is installed globally.
EOF
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
cat > code_review.md << 'EOF'
## Code Review Summary
⚠️ Continue configuration error. Please verify that the assistant exists in Continue Hub.
EOF
node actions/general-review/scripts/writeMarkdown.js code_review.md config_error
elif grep -q "api\|auth" cli_error.log 2>/dev/null; then
cat > code_review.md << 'EOF'
## Code Review Summary
⚠️ Continue API authentication failed. Please check your CONTINUE_API_KEY.
EOF
node actions/general-review/scripts/writeMarkdown.js code_review.md auth_error
else
cat > code_review.md << 'EOF'
## 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
EOF
node actions/general-review/scripts/writeMarkdown.js code_review.md generic_failure
fi
fi

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

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -537,12 +537,19 @@ export class ConfigHandler {
// Track config loading telemetry
const endTime = performance.now();
const duration = endTime - startTime;
void Telemetry.capture("config_reload", {
const profileDescription = this.currentProfile.profileDescription;
const telemetryData: Record<string, any> = {
duration,
reason,
totalConfigLoads: this.totalConfigReloads,
configLoadInterrupted,
});
profileType: profileDescription.profileType,
isPersonalOrg: this.currentOrg?.id === this.PERSONAL_ORG_DESC.id,
errorCount: errors.length,
};
void Telemetry.capture("config_reload", telemetryData);
return {
config,

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

@ -61,7 +61,7 @@ import { localPathToUri } from "../util/pathToUri";
import { loadJsonMcpConfigs } from "../context/mcp/json/loadJsonMcpConfigs";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import { PolicySingleton } from "../control-plane/PolicySingleton";
import { getBaseToolDefinitions } from "../tools";
import { getBaseToolDefinitions, serializeTool } from "../tools";
import { resolveRelativePathInDir } from "../util/ideUtils";
import { getWorkspaceRcConfigs } from "./json/loadRcConfigs";
import { loadConfigContextProviders } from "./loadContextProviders";
@ -671,7 +671,7 @@ async function finalToBrowserConfig(
experimental: final.experimental,
rules: final.rules,
docs: final.docs,
tools: final.tools,
tools: final.tools.map(serializeTool),
mcpServerStatuses: final.mcpServerStatuses,
tabAutocompleteOptions: final.tabAutocompleteOptions,
usePlatform: await useHub(ide.getIdeSettings()),

View file

@ -12,13 +12,12 @@ import { getGlobalFolderWithName } from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
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") ||
uri.endsWith("AGENTS.md") ||
uri.endsWith("AGENT.md") ||
uri.endsWith("CLAUDE.md") ||
!!SUPPORTED_AGENT_FILES.find((file) => uri.endsWith(`/${file}`)) ||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
(uri.includes(".continue") &&
(uri.endsWith(".yaml") ||

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,12 +3,13 @@ import {
markdownToRule,
} from "@continuedev/config-yaml";
import { IDE, RuleWithSource } from "../..";
import { findUriInDirs, joinPathsToUri } from "../../util/uri";
import { PROMPTS_DIR_NAME, RULES_DIR_NAME } from "../../promptFiles";
import { joinPathsToUri } from "../../util/uri";
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
export const SUPPORTED_AGENT_FILES = ["AGENTS.md", "AGENT.md", "CLAUDE.md"];
/**
* Loads rules from markdown files in the .continue/rules directory
* Loads rules from markdown files in the .continue/rules and .continue/prompts directories
* and agent files (AGENTS.md, AGENT.md, CLAUDE.md) at workspace root
*/
export async function loadMarkdownRules(ide: IDE): Promise<{
@ -25,66 +26,73 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
let agentFileFound = false;
for (const fileName of SUPPORTED_AGENT_FILES) {
try {
const agentFilePath = joinPathsToUri(workspaceDir, fileName);
const agentContent = await ide.readFile(agentFilePath);
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;
}
const rule = markdownToRule(agentContent, {
uriType: "file",
fileUri: agentFilePath,
});
rules.push({
...rule,
source: "agent-file",
ruleFile: agentFilePath,
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(
ide,
{ includeGlobal: true, includeWorkspace: true, fileExtType: "markdown" },
"rules",
);
// Load markdown files from both .continue/rules and .continue/prompts
const dirsToCheck = [RULES_DIR_NAME, PROMPTS_DIR_NAME];
// Filter to just .md files
const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md"));
for (const dirName of dirsToCheck) {
try {
const markdownFiles = await getAllDotContinueDefinitionFiles(
ide,
{
includeGlobal: true,
includeWorkspace: true,
fileExtType: "markdown",
},
dirName,
);
// 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,
});
rules.push({ ...rule, source: "rules-block", ruleFile: file.path });
} catch (e) {
errors.push({
fatal: false,
message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`,
});
// Filter to just .md files
const mdFiles = markdownFiles.filter((file) => file.path.endsWith(".md"));
// Process each markdown file
for (const file of mdFiles) {
try {
const rule = markdownToRule(file.content, {
uriType: "file",
fileUri: file.path,
});
rules.push({ ...rule, source: "rules-block", sourceFile: file.path });
} catch (e) {
errors.push({
fatal: false,
message: `Failed to parse markdown rule file ${file.path}: ${e instanceof Error ? e.message : e}`,
});
}
}
} catch (e) {
errors.push({
fatal: false,
message: `Error loading markdown rule files from ${dirName}: ${e instanceof Error ? e.message : e}`,
});
}
} catch (e) {
errors.push({
fatal: false,
message: `Error loading markdown rule files: ${e instanceof Error ? e.message : e}`,
});
}
return { rules, errors };

View file

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

View file

@ -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";
@ -171,6 +172,8 @@ export default async function doLoadConfig(options: {
}
}
newConfig.slashCommands.push(initSlashCommand);
const proxyContextProvider = newConfig.contextProviders?.find(
(cp) => cp.description.title === "continue-proxy",
);
@ -210,6 +213,13 @@ export default async function doLoadConfig(options: {
newConfig.mcpServerStatuses = serializableStatuses;
for (const server of mcpServerStatuses) {
server.errors.forEach((error) => {
// MCP errors will also show as config loading errors
errors.push({
fatal: false,
message: error,
});
});
if (server.status === "connected") {
const serverTools: Tool[] = server.tools.map((tool) => ({
displayTitle: server.name + " " + tool.name,

View file

@ -78,8 +78,9 @@ declare global {
export interface ILLM extends LLMOptions {
get providerName(): string;
uniqueId: string;
lastRequestId?: string;
model: string;
title?: string;

View file

@ -7,6 +7,7 @@ import {
} 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<
@ -114,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;
@ -156,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

@ -25,7 +25,7 @@ export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
globs: rule.globs,
name: rule.name,
description: rule.description,
ruleFile: rule.sourceFile,
sourceFile: rule.sourceFile,
alwaysApply: rule.alwaysApply,
invokable: rule.invokable ?? false,
};
@ -48,27 +48,28 @@ export function convertYamlMcpConfigToInternalMcpOptions(
if ("command" in config) {
const { args, command, cwd, env, type } = config;
const stdioOptions: InternalStdioMcpOptions = {
...shared,
type,
command,
args,
cwd,
env,
...shared,
};
return stdioOptions;
}
// HTTP/SSE
const { type, url, requestOptions } = config;
const { type, url, apiKey, requestOptions } = config;
const httpSseConfig:
| InternalStreamableHttpMcpOptions
| InternalSseMcpOptions = {
...shared,
type,
url,
apiKey,
requestOptions: mergeConfigYamlRequestOptions(
requestOptions,
globalRequestOptions,
),
...shared,
};
return httpSseConfig;
}

View file

@ -1,4 +1,7 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { fileURLToPath } from "url";
import {
SSEClientTransport,
SseError,
@ -6,7 +9,6 @@ import {
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { Agent as HttpsAgent } from "https";
import {
IDE,
@ -22,6 +24,7 @@ import {
MCPServerStatus,
MCPTool,
} from "../..";
import { resolveRelativePathInDir } from "../../util/ideUtils";
import { getEnvPathFromUserShell } from "../../util/shellPath";
import { getOauthToken } from "./MCPOauth";
@ -38,6 +41,8 @@ const WINDOWS_BATCH_COMMANDS = [
"bunx",
];
const COMMONS_ENV_VARS = ["HOME", "USER", "USERPROFILE", "LOGNAME", "USERNAME"];
function is401Error(error: unknown) {
return (
(error instanceof SseError && error.code === 401) ||
@ -88,11 +93,11 @@ class MCPConnection {
this.abortController = new AbortController();
}
async disconnect() {
this.status = "not-connected";
async disconnect(disable = false) {
this.abortController.abort();
await this.client.close();
await this.transport.close();
this.status = disable ? "disabled" : "not-connected";
}
getStatus(): MCPServerStatus {
@ -110,6 +115,9 @@ class MCPConnection {
}
async connectClient(forceRefresh: boolean, externalSignal: AbortSignal) {
if (this.status === "disabled") {
return;
}
if (!forceRefresh) {
// Already connected
if (this.status === "connected") {
@ -408,6 +416,44 @@ class MCPConnection {
};
}
/**
* Resolves the current working directory of the current workspace.
* @param cwd The cwd parameter provided by user.
* @returns Current working directory (user-provided cwd or workspace root).
*/
private async resolveCwd(cwd?: string) {
if (!cwd) {
return this.resolveWorkspaceCwd(undefined);
}
if (cwd.startsWith("file://")) {
return fileURLToPath(cwd);
}
// Return cwd if cwd is an absolute path.
if (cwd.charAt(0) === "/") {
return cwd;
}
return this.resolveWorkspaceCwd(cwd);
}
private async resolveWorkspaceCwd(cwd: string | undefined) {
const IDE = this.extras?.ide;
if (IDE) {
const target = cwd ?? ".";
const resolved = await resolveRelativePathInDir(target, IDE);
if (resolved) {
if (resolved.startsWith("file://")) {
return fileURLToPath(resolved);
}
return resolved;
}
return resolved;
}
return cwd;
}
private constructWebsocketTransport(
options: InternalWebsocketMcpOptions,
): WebSocketClientTransport {
@ -422,6 +468,12 @@ class MCPConnection {
? new HttpsAgent({ rejectUnauthorized: false })
: undefined;
// Merge apiKey into headers if provided
const headers = {
...options.requestOptions?.headers,
...(options.apiKey && { Authorization: `Bearer ${options.apiKey}` }),
};
return new SSEClientTransport(new URL(options.url), {
eventSourceInit: {
fetch: (input, init) =>
@ -429,13 +481,13 @@ class MCPConnection {
...init,
headers: {
...init?.headers,
...options.requestOptions?.headers,
...headers,
},
...(sseAgent && { agent: sseAgent }),
}),
},
requestInit: {
headers: options.requestOptions?.headers,
headers,
...(sseAgent && { agent: sseAgent }),
},
});
@ -450,9 +502,15 @@ class MCPConnection {
? new HttpsAgent({ rejectUnauthorized: false })
: undefined;
// Merge apiKey into headers if provided
const headers = {
...requestOptions?.headers,
...(options.apiKey && { Authorization: `Bearer ${options.apiKey}` }),
};
return new StreamableHTTPClientTransport(new URL(url), {
requestInit: {
headers: requestOptions?.headers,
headers,
...(streamableAgent && { agent: streamableAgent }),
},
});
@ -461,7 +519,16 @@ class MCPConnection {
private async constructStdioTransport(
options: InternalStdioMcpOptions,
): Promise<StdioClientTransport> {
const env: Record<string, string> = options.env ? { ...options.env } : {};
const commonEnvVars: Record<string, string> = Object.fromEntries(
COMMONS_ENV_VARS.filter((key) => process.env[key] !== undefined).map(
(key) => [key, process.env[key] as string],
),
);
const env = {
...commonEnvVars,
...(options.env ?? {}),
};
if (process.env.PATH !== undefined) {
// Set the initial PATH from process.env
@ -485,11 +552,13 @@ class MCPConnection {
options.args || [],
);
const cwd = await this.resolveCwd(options.cwd);
const transport = new StdioClientTransport({
command,
args,
env,
cwd: options.cwd,
cwd,
stderr: "pipe",
});

View file

@ -5,6 +5,7 @@ import {
InternalStdioMcpOptions,
InternalWebsocketMcpOptions,
} from "../..";
import * as ideUtils from "../../util/ideUtils";
import MCPConnection from "./MCPConnection";
// Mock the shell path utility
@ -145,6 +146,37 @@ describe("MCPConnection", () => {
});
});
describe("resolveCwd", () => {
const baseOptions = {
name: "test-mcp",
id: "test-id",
type: "stdio" as const,
command: "test-cmd",
args: [],
};
it("should return absolute cwd unchanged", async () => {
const conn = new MCPConnection(baseOptions);
await expect((conn as any).resolveCwd("/tmp/project")).resolves.toBe(
"/tmp/project",
);
});
it("should resolve relative cwd using IDE workspace", async () => {
const ide = {} as any;
const mockResolve = vi
.spyOn(ideUtils, "resolveRelativePathInDir")
.mockResolvedValue("file:///workspace/src");
const conn = new MCPConnection(baseOptions, { ide });
await expect((conn as any).resolveCwd("src")).resolves.toBe(
"/workspace/src",
);
expect(mockResolve).toHaveBeenCalledWith("src", ide);
});
});
describe("connectClient", () => {
const options: InternalStdioMcpOptions = {
name: "test-mcp",

View file

@ -8,7 +8,6 @@ export class MCPManagerSingleton {
public onConnectionsRefreshed?: () => void;
public connections: Map<string, MCPConnection> = new Map();
private disconnectedServers: string[] = [];
private abortController: AbortController = new AbortController();
@ -21,16 +20,20 @@ export class MCPManagerSingleton {
return MCPManagerSingleton.instance;
}
addDisconnectedServer(serverId: string) {
this.disconnectedServers.push(serverId);
}
removeDisconnectedServer(serverId: string) {
this.disconnectedServers = this.disconnectedServers.filter(
(server) => server !== serverId,
);
}
getDisconnectedServers() {
return this.disconnectedServers;
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 {
@ -47,15 +50,6 @@ export class MCPManagerSingleton {
return this.connections.get(id);
}
async removeConnection(id: string) {
const connection = this.connections.get(id);
if (connection) {
await connection.client.close();
}
this.connections.delete(id);
}
async shutdown() {
if (this.connections.size > 0) {
await Promise.allSettled(
@ -169,19 +163,9 @@ export class MCPManagerSingleton {
}),
(async () => {
await Promise.all(
Array.from(this.connections.values())
.filter(
(connection) =>
!this.disconnectedServers.some(
(s) => s === connection.options.id,
),
)
.map(async (connection) => {
await connection.connectClient(
force,
this.abortController.signal,
);
}),
Array.from(this.connections.values()).map(async (connection) => {
await connection.connectClient(force, this.abortController.signal);
}),
);
if (this.onConnectionsRefreshed) {
this.onConnectionsRefreshed();

View file

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

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

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

@ -63,7 +63,10 @@ import {
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";
@ -80,6 +83,7 @@ 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";
@ -410,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) => {
@ -483,20 +495,10 @@ export class Core {
on("mcp/reloadServer", async (msg) => {
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
MCPManagerSingleton.getInstance().removeDisconnectedServer(msg.data.id);
});
on("mcp/disconnectServer", async (msg) => {
const mcpConnection = MCPManagerSingleton.getInstance().getConnection(
msg.data.id,
);
if (!mcpConnection)
throw new Error(`MCP connection with id ${msg.data.id} not found`);
MCPManagerSingleton.getInstance().addDisconnectedServer(msg.data.id);
await mcpConnection.disconnect();
await this.configHandler.refreshAll("MCP Servers disconnected");
});
on("mcp/getDisconnectedServers", async (_msg) => {
return MCPManagerSingleton.getInstance().getDisconnectedServers();
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;
@ -825,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);
});
@ -929,7 +930,7 @@ export class Core {
});
on("files/closed", async ({ data }) => {
console.log("deleteChain called from files/closed");
console.debug("deleteChain called from files/closed");
await NextEditProvider.getInstance().deleteChain();
try {
@ -1104,7 +1105,6 @@ export class Core {
const tool = config.tools.find((t) => t.function.name === toolName);
if (!tool) {
// Tool not found, return base policy
return { policy: basePolicy };
}
@ -1114,17 +1114,47 @@ export class Core {
displayValue = args.command as string;
}
// If tool has evaluateToolCallPolicy function, use it
if (tool.evaluateToolCallPolicy) {
const evaluatedPolicy = tool.evaluateToolCallPolicy(basePolicy, args);
return { policy: evaluatedPolicy, displayValue };
}
// Otherwise return base policy unchanged
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);
});

View file

@ -7,22 +7,23 @@ export const FOUND_MULTIPLE_FIND_STRINGS_ERROR =
* Validates a single edit operation
*/
export function validateSingleEdit(
oldString: string,
newString: string,
oldString: unknown,
newString: unknown,
replaceAll: unknown,
index?: number,
): void {
): { oldString: string; newString: string; replaceAll?: boolean } {
const context = index !== undefined ? `edit at index ${index}: ` : "";
if (!oldString && oldString !== "") {
if (oldString === undefined || typeof oldString !== "string") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingOldString,
`${context}old_string is required`,
`${context}string old_string is required`,
);
}
if (newString === undefined) {
if (newString === undefined || typeof newString !== "string") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingNewString,
`${context}new_string is required`,
`${context}string new_string is required`,
);
}
if (oldString === newString) {
@ -31,6 +32,13 @@ export function validateSingleEdit(
`${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({

View file

@ -6,39 +6,69 @@ describe("validateSingleEdit", () => {
describe("valid inputs", () => {
it("should not throw for valid non-empty strings", () => {
expect(() => {
validateSingleEdit("old", "new");
validateSingleEdit("old", "new", undefined);
}).not.toThrow();
});
it("should allow empty old_string for file creation", () => {
expect(() => {
validateSingleEdit("", "new content");
validateSingleEdit("", "new content", undefined);
}).not.toThrow();
});
it("should allow empty new_string for deletion", () => {
expect(() => {
validateSingleEdit("delete me", "");
validateSingleEdit("delete me", "", undefined);
}).not.toThrow();
});
it("should allow multiline strings", () => {
expect(() => {
validateSingleEdit("line1\nline2", "newline1\nnewline2");
validateSingleEdit("line1\nline2", "newline1\nnewline2", undefined);
}).not.toThrow();
});
it("should allow special characters", () => {
expect(() => {
validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g");
validateSingleEdit("/[a-z]+/g", "/[A-Z]+/g", undefined);
}).not.toThrow();
});
it("should allow replaceAll as true", () => {
expect(() => {
validateSingleEdit("old", "new", true);
}).not.toThrow();
});
it("should allow replaceAll as false", () => {
expect(() => {
validateSingleEdit("old", "new", false);
}).not.toThrow();
});
it("should return validated values including replaceAll", () => {
const result = validateSingleEdit("old", "new", true);
expect(result).toEqual({
oldString: "old",
newString: "new",
replaceAll: true,
});
});
it("should return validated values with replaceAll undefined", () => {
const result = validateSingleEdit("old", "new", undefined);
expect(result).toEqual({
oldString: "old",
newString: "new",
replaceAll: undefined,
});
});
});
describe("invalid inputs", () => {
it("should throw error when old_string is null", () => {
expect(() => {
validateSingleEdit(null as any, "new");
validateSingleEdit(null as any, "new", undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
@ -48,7 +78,7 @@ describe("validateSingleEdit", () => {
it("should throw error when old_string is undefined", () => {
expect(() => {
validateSingleEdit(undefined as any, "new");
validateSingleEdit(undefined as any, "new", undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
@ -58,7 +88,7 @@ describe("validateSingleEdit", () => {
it("should throw error when new_string is undefined", () => {
expect(() => {
validateSingleEdit("old", undefined as any);
validateSingleEdit("old", undefined as any, undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingNewString,
@ -68,7 +98,7 @@ describe("validateSingleEdit", () => {
it("should throw error when old_string and new_string are identical", () => {
expect(() => {
validateSingleEdit("same", "same");
validateSingleEdit("same", "same", undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
@ -78,19 +108,49 @@ describe("validateSingleEdit", () => {
it("should throw error when both are empty strings", () => {
expect(() => {
validateSingleEdit("", "");
validateSingleEdit("", "", undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
}),
);
});
it("should throw error when replaceAll is not a boolean", () => {
expect(() => {
validateSingleEdit("old", "new", "invalid" as any);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll,
}),
);
});
it("should throw error when replaceAll is null", () => {
expect(() => {
validateSingleEdit("old", "new", null as any);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll,
}),
);
});
it("should throw error when replaceAll is a number", () => {
expect(() => {
validateSingleEdit("old", "new", 1 as any);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll,
}),
);
});
});
describe("error messages with context", () => {
it("should include edit number in error messages when index provided", () => {
expect(() => {
validateSingleEdit(null as any, "new", 2);
validateSingleEdit(null as any, "new", undefined, 2);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingOldString,
@ -100,7 +160,7 @@ describe("validateSingleEdit", () => {
it("should include edit number for new_string errors", () => {
expect(() => {
validateSingleEdit("old", undefined as any, 0);
validateSingleEdit("old", undefined as any, undefined, 0);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceMissingNewString,
@ -110,7 +170,7 @@ describe("validateSingleEdit", () => {
it("should include edit number for identical strings error", () => {
expect(() => {
validateSingleEdit("same", "same", 4);
validateSingleEdit("same", "same", undefined, 4);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,
@ -118,9 +178,19 @@ describe("validateSingleEdit", () => {
);
});
it("should include edit number for replaceAll validation error", () => {
expect(() => {
validateSingleEdit("old", "new", "invalid" as any, 3);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceInvalidReplaceAll,
}),
);
});
it("should not include context when index not provided", () => {
expect(() => {
validateSingleEdit("same", "same");
validateSingleEdit("same", "same", undefined);
}).toThrowError(
expect.objectContaining({
reason: ContinueErrorReason.FindAndReplaceIdenticalOldAndNewStrings,

View file

@ -2,26 +2,30 @@ import { EditOperation } from "../../tools/definitions/multiEdit";
import { ContinueError, ContinueErrorReason } from "../../util/errors";
import { validateSingleEdit } from "./findAndReplaceUtils";
export interface MultiEditValidationResult {
edits: EditOperation[];
}
/**
* Validates multi-edit arguments and all edits in a single pass
* @param args - The arguments object containing the edits array
* @returns Validated edits array
* @throws ContinueError if validation fails
*/
export function validateMultiEdit(args: any): MultiEditValidationResult {
const { edits } = args;
export function validateMultiEdit(args: unknown): {
edits: EditOperation[];
} {
if (typeof args !== "object" || !args || !("edits" in args)) {
throw new ContinueError(
ContinueErrorReason.MultiEditEditsArrayRequired,
"invalid multi-edit args",
);
}
// Validate that edits is a non-empty array
if (!edits || !Array.isArray(edits)) {
if (!Array.isArray(args.edits)) {
throw new ContinueError(
ContinueErrorReason.MultiEditEditsArrayRequired,
"edits array is required",
);
}
const { edits } = args;
if (edits.length === 0) {
throw new ContinueError(
@ -35,7 +39,7 @@ export function validateMultiEdit(args: any): MultiEditValidationResult {
const edit = edits[i];
// Use existing single edit validation
validateSingleEdit(edit.old_string, edit.new_string, i);
validateSingleEdit(edit.old_string, edit.new_string, edit.replace_all, i);
// Only the first edit can have empty old_string (for insertion at beginning)
if (i > 0 && edit.old_string === "") {

View file

@ -0,0 +1,23 @@
import { IDE } from "../..";
import { ContinueError, ContinueErrorReason } from "../../util/errors";
import { resolveRelativePathInDir } from "../../util/ideUtils";
export async function validateSearchAndReplaceFilepath(
filepath: unknown,
ide: IDE,
) {
if (!filepath || typeof filepath !== "string") {
throw new ContinueError(
ContinueErrorReason.FindAndReplaceMissingFilepath,
"filepath (string) is required",
);
}
const resolvedFilepath = await resolveRelativePathInDir(filepath, ide);
if (!resolvedFilepath) {
throw new ContinueError(
ContinueErrorReason.FileNotFound,
`File ${filepath} does not exist`,
);
}
return resolvedFilepath;
}

33
core/index.d.ts vendored
View file

@ -99,6 +99,8 @@ export interface ILLM
autocompleteOptions?: Partial<TabAutocompleteOptions>;
lastRequestId?: string;
complete(
prompt: string,
signal: AbortSignal,
@ -476,6 +478,7 @@ interface ToolCallState {
toolCall: ToolCall;
status: ToolStatus;
parsedArgs: any;
processedArgs?: Record<string, any>; // Added in preprocesing step
output?: ContextItem[];
tool?: Tool;
}
@ -918,7 +921,8 @@ export interface SlashCommand extends SlashCommandDescription {
export interface SlashCommandWithSource extends SlashCommandDescription {
run?: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>; // Optional - only needed for legacy
source: SlashCommandSource;
promptFile?: string;
sourceFile?: string;
slug?: string;
overrideSystemMessage?: string;
}
@ -936,7 +940,8 @@ export type SlashCommandSource =
export interface SlashCommandDescWithSource extends SlashCommandDescription {
isLegacy: boolean; // Maps to if slashcommand.run exists
source: SlashCommandSource;
promptFile?: string;
sourceFile?: string;
slug?: string;
mcpServerName?: string;
mcpArgs?: MCPPromptArgs;
}
@ -1080,7 +1085,6 @@ export interface Tool {
parameters?: Record<string, any>;
strict?: boolean | null;
};
displayTitle: string;
wouldLikeTo?: string;
isCurrently?: string;
@ -1097,6 +1101,12 @@ export interface Tool {
};
defaultToolPolicy?: ToolPolicy;
toolCallIcon?: string;
preprocessArgs?: (
args: Record<string, unknown>,
extras: {
ide: IDE;
},
) => Promise<Record<string, unknown>>;
evaluateToolCallPolicy?: (
basePolicy: ToolPolicy,
parsedArgs: Record<string, unknown>,
@ -1273,6 +1283,7 @@ export type TransportOptions =
| StreamableHTTPOptions;
export type MCPConnectionStatus =
| "disabled"
| "connecting"
| "connected"
| "error"
@ -1339,11 +1350,13 @@ export type InternalStdioMcpOptions = BaseInternalMCPOptions & {
export type InternalStreamableHttpMcpOptions = BaseInternalMCPOptions & {
type?: "streamable-http";
url: string;
apiKey?: string;
};
export type InternalSseMcpOptions = BaseInternalMCPOptions & {
type?: "sse";
url: string;
apiKey?: string;
};
export type InternalWebsocketMcpOptions = BaseInternalMCPOptions & {
@ -1776,7 +1789,7 @@ export interface BrowserSerializedContinueConfig {
experimental?: ExperimentalConfig;
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
tools: Tool[];
tools: Omit<Tool, "preprocessArgs", "evaluatePolicy">[];
mcpServerStatuses: MCPServerStatus[];
rules: RuleWithSource[];
usePlatform: boolean;
@ -1849,7 +1862,7 @@ export interface RuleWithSource {
regex?: string | string[];
rule: string;
description?: string;
ruleFile?: string;
sourceFile?: string;
alwaysApply?: boolean;
invokable?: boolean;
}
@ -1865,6 +1878,16 @@ export interface CompiledMessagesResult {
contextPercentage: number;
}
export interface AddToChatPayload {
data: AddToChatPayloadItem[];
}
interface AddToChatPayloadItem {
type: "file" | "folder";
fullPath: string;
name: string;
}
export interface MessageOption {
precompiled: boolean;
}

View file

@ -20,7 +20,7 @@ The indexing process does the following:
All indexes must be returned by `getIndexesToBuild` in [`CodebaseIndexer.ts`](./CodebaseIndexer.ts) if they are to be used.
`CodeSnippetsIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file
`CodeSnippetsCodebaseIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file
`FullTextSearchCodebaseIndex`: creates a full-text search index using SQLite FTS5
`ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbIndex`
`LanceDbIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB.

View file

@ -193,12 +193,15 @@ export abstract class BaseLLM implements ILLM {
isFromAutoDetect?: boolean;
lastRequestId: string | undefined;
private _llmOptions: LLMOptions;
protected openaiAdapter?: BaseLlmApi;
constructor(_options: LLMOptions) {
this._llmOptions = _options;
this.lastRequestId = undefined;
// Set default options
const options = {
@ -594,6 +597,7 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
): AsyncGenerator<string> {
this.lastRequestId = undefined;
const { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
const interaction = logEnabled
@ -623,6 +627,9 @@ export abstract class BaseLLM implements ILLM {
signal,
);
for await (const chunk of stream) {
if (!this.lastRequestId && typeof (chunk as any).id === "string") {
this.lastRequestId = (chunk as any).id;
}
const result = fromChatCompletionChunk(chunk);
if (result) {
const content = renderChatMessage(result);
@ -706,6 +713,7 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
) {
this.lastRequestId = undefined;
const { completionOptions, logEnabled, raw } =
this._parseCompletionOptions(options);
const interaction = logEnabled
@ -745,6 +753,7 @@ export abstract class BaseLLM implements ILLM {
{ ...toCompleteBody(prompt, completionOptions), stream: false },
signal,
);
this.lastRequestId = response.id ?? this.lastRequestId;
completion = response.choices[0]?.text ?? "";
yield completion;
} else {
@ -756,6 +765,9 @@ export abstract class BaseLLM implements ILLM {
},
signal,
)) {
if (!this.lastRequestId && typeof (chunk as any).id === "string") {
this.lastRequestId = (chunk as any).id;
}
const content = chunk.choices[0]?.text ?? "";
completion += content;
interaction?.logItem({
@ -835,6 +847,7 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
) {
this.lastRequestId = undefined;
const { completionOptions, logEnabled, raw } =
this._parseCompletionOptions(options);
const interaction = logEnabled
@ -876,6 +889,7 @@ export abstract class BaseLLM implements ILLM {
},
signal,
);
this.lastRequestId = result.id ?? this.lastRequestId;
completion = result.choices[0].text;
} else {
completion = await this._complete(prompt, signal, completionOptions);
@ -985,6 +999,7 @@ export abstract class BaseLLM implements ILLM {
options: LLMFullCompletionOptions = {},
messageOptions?: MessageOption,
): AsyncGenerator<ChatMessage, PromptLog> {
this.lastRequestId = undefined;
let { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
const interaction = logEnabled
@ -1054,6 +1069,7 @@ export abstract class BaseLLM implements ILLM {
{ ...body, stream: false },
signal,
);
this.lastRequestId = response.id ?? this.lastRequestId;
const msg = fromChatResponse(response);
yield msg;
completion = this._formatChatMessage(msg);
@ -1071,6 +1087,12 @@ export abstract class BaseLLM implements ILLM {
signal,
);
for await (const chunk of stream) {
if (
!this.lastRequestId &&
typeof (chunk as any).id === "string"
) {
this.lastRequestId = (chunk as any).id;
}
const result = fromChatCompletionChunk(chunk);
if (result) {
completion += this._formatChatMessage(result);

View file

@ -1,3 +1,4 @@
import FormData from "form-data";
import {
ChatMessage,
CompletionOptions,
@ -6,48 +7,169 @@ import {
} from "../../index.js";
import { BaseLLM } from "../index.js";
// Extended options for AskSage
interface AskSageCompletionOptions extends CompletionOptions {
mode?: "chat" | "deep_agent";
limitReferences?: 0 | 1;
persona?: number;
systemPrompt?: string;
askSageTools?: AskSageTool[];
enabledMcpTools?: string[];
toolsToExecute?: string[];
askSageToolChoice?: ToolChoice;
reasoningEffort?: "low" | "medium" | "high";
deepAgentId?: number;
streaming?: boolean;
file?: unknown;
}
const DEFAULT_API_URL = "https://api.asksage.ai/server";
const DEFAULT_USER_API_URL = "https://api.asksage.ai/user";
const TOKEN_TTL = 3600000; // 1 hour in milliseconds
interface AskSageTool {
type: string;
function: {
name: string;
description?: string;
parameters?: Record<string, unknown>;
};
}
type ToolChoice =
| "auto"
| "none"
| { type: "function"; function: { name: string } };
interface AskSageRequestArgs {
model?: string;
temperature?: number;
mode?: "chat" | "deep_agent";
message?: string | { user: string; message: string }[];
live?: 0 | 1 | 2;
dataset?: string | string[];
limit_references?: 0 | 1;
persona?: number;
system_prompt?: string;
tools?: AskSageTool[];
enabled_mcp_tools?: string[];
tools_to_execute?: string[];
tool_choice?: ToolChoice;
reasoning_effort?: "low" | "medium" | "high";
deep_agent_id?: number;
streaming?: boolean;
file?: unknown;
}
interface AskSageResponse {
text?: string;
answer?: string;
message?: string;
status?: number | string;
response?: unknown;
choices?: Array<{
message?: {
content?: string;
};
}>;
}
interface TokenResponse {
status: number | string;
response: {
access_token: string;
};
}
class Asksage extends BaseLLM {
static providerName = "askSage";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.asksage.ai/server/",
apiBase: DEFAULT_API_URL,
model: "gpt-4o",
};
private static modelConversion: { [key: string]: string } = {
"gpt-4o-gov": "gpt-4o-gov", // Works
"gpt-4o-mini-gov": "gpt-4o-mini-gov",
"gpt4-gov": "gpt4-gov", // Works
"gpt-gov": "gpt-gov", // Works
"gpt-4o": "gpt-4o", // Works
"gpt-4o-mini": "gpt-4o-mini", // Works
gpt4: "gpt4", // Works
"gpt4-32k": "gpt4-32k",
"gpt-o1": "gpt-o1", // Works
"gpt-o1-mini": "gpt-o1-mini", // Works
"gpt-o3-mini": "gpt-o3-mini", // Stub
"gpt-3.5-turbo": "gpt35-16k", // Works
"aws-bedrock-claude-35-sonnet-gov": "aws-bedrock-claude-35-sonnet-gov", // Works
"claude-3-5-sonnet-latest": "claude-35-sonnet", // Works
"claude-3-opus-20240229": "claude-3-opus", // Works
"claude-3-sonnet-20240229": "claude-3-sonnet", // Works
"grok-beta": "xai-grok",
"groq-llama33": "groq-llama33",
"groq-70b": "groq-70b",
"mistral-large-latest": "mistral-large", // Works
"llama3-70b": "llma3", // Works
"gemini-1.5-pro-latest": "google-gemini-pro", // Works
};
private sessionTokenPromise: Promise<string> | null = null;
private tokenTimestamp: number = 0;
private email?: string;
private userApiUrl: string;
constructor(options: LLMOptions) {
super(options);
this.apiVersion = options.apiVersion ?? "v1.2.4";
this.email = process.env.ASKSAGE_EMAIL;
this.userApiUrl = process.env.ASKSAGE_USER_API_URL || DEFAULT_USER_API_URL;
}
protected _convertModelName(model: string): string {
console.log("Converting model:", model);
const convertedModel = Asksage.modelConversion[model] ?? model;
console.log("Converted model:", convertedModel);
return convertedModel;
private async getSessionToken(): Promise<string> {
if (!this.apiKey) {
throw new Error(
"AskSage adapter: missing ASKSAGE_API_KEY. Provide it in your environment variables or .env file.",
);
}
// If no email, use API key directly
if (!this.email || this.email.length === 0) {
return this.apiKey;
}
const url = this.userApiUrl.replace(/\/$/, "") + "/get-token-with-api-key";
const res = await this.fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: this.email, api_key: this.apiKey }),
});
const data = (await res.json()) as TokenResponse;
if (parseInt(String(data.status)) !== 200) {
throw new Error("Error getting access token: " + JSON.stringify(data));
}
return data.response.access_token;
}
private async getToken(): Promise<string> {
// Check if token needs refresh
if (
!this.sessionTokenPromise ||
Date.now() - this.tokenTimestamp > TOKEN_TTL
) {
this.sessionTokenPromise = this.getSessionToken();
this.tokenTimestamp = Date.now();
}
return this.sessionTokenPromise;
}
private isFileLike(val: unknown): boolean {
return (
val !== null &&
val !== undefined &&
((typeof File !== "undefined" && val instanceof File) ||
(typeof Buffer !== "undefined" && val instanceof Buffer) ||
(typeof val === "object" &&
("path" in val || "name" in val || "type" in val)))
);
}
private toFormData(args: AskSageRequestArgs): FormData {
const form = new FormData();
for (const [key, value] of Object.entries(args)) {
if (value === undefined || value === null) continue;
if (key === "file" && value) {
if (Buffer.isBuffer(value)) {
form.append("file", value, "file");
} else if (typeof value === "string") {
form.append("file", value);
} else {
form.append("file", value as Buffer);
}
} else if (Array.isArray(value) || typeof value === "object") {
form.append(key, JSON.stringify(value));
} else {
form.append(key, String(value));
}
}
return form;
}
protected _convertMessage(message: ChatMessage) {
@ -63,43 +185,63 @@ class Asksage extends BaseLLM {
};
}
protected _convertArgs(options: any, messages: ChatMessage[]) {
let formattedMessage: any;
protected _convertArgs(
options: AskSageCompletionOptions,
messages: ChatMessage[],
): AskSageRequestArgs {
let formattedMessage: string | { user: string; message: string }[];
if (messages.length === 1) {
formattedMessage = messages[0].content;
formattedMessage = messages[0].content as string;
} else {
formattedMessage = messages.map(this._convertMessage);
}
const args: any = {
const args: AskSageRequestArgs = {
message: formattedMessage,
persona: options.persona ?? "default",
dataset: options.dataset ?? "none",
limit_references: options.limitReferences ?? 0,
model: options.model,
temperature: options.temperature ?? 0.0,
live: options.live ?? 0,
model: this._convertModelName(options.model),
mode: "chat", // Always use chat mode
limit_references: 0, // Always use 0
persona: options.persona as number | undefined,
system_prompt:
options.systemPrompt ??
process.env.ASKSAGE_SYSTEM_PROMPT ??
"You are an expert software developer. You give helpful and concise responses.",
tools: options.tools,
tool_choice: options.toolChoice,
tools: options.askSageTools,
// enabled_mcp_tools: options.enabledMcpTools as string[] | undefined,
// tools_to_execute: options.toolsToExecute as string[] | undefined,
tool_choice: options.askSageToolChoice,
reasoning_effort: options.reasoningEffort as
| "low"
| "medium"
| "high"
| undefined,
deep_agent_id: options.deepAgentId as number | undefined,
streaming: options.streaming as boolean | undefined,
file: options.file,
};
// Remove undefined values
Object.keys(args).forEach(
(key) => args[key] === undefined && delete args[key],
(key) =>
args[key as keyof AskSageRequestArgs] === undefined &&
delete args[key as keyof AskSageRequestArgs],
);
return args;
}
protected _getHeaders() {
protected async _getHeaders(
hasFile: boolean = false,
): Promise<Record<string, string>> {
const token = await this.getToken();
const headers: Record<string, string> = {
"Content-Type": "application/json",
accept: "application/json",
"x-access-tokens": token,
};
if (this.apiKey) {
headers["x-access-tokens"] = this.apiKey;
if (!hasFile) {
headers["Content-Type"] = "application/json";
}
return headers;
@ -125,21 +267,66 @@ class Asksage extends BaseLLM {
}
const messages: ChatMessage[] = [{ role: "user", content: prompt }];
const args = this._convertArgs(options, messages);
const hasFile = this.isFileLike(args.file);
const endpoint = hasFile ? "query_with_file" : "query";
const response = await this.fetch(this._getEndpoint("query"), {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify(args),
});
try {
let response;
if (hasFile) {
const form = this.toFormData(args);
const headers = await this._getHeaders(true);
response = await this.fetch(this._getEndpoint(endpoint), {
method: "POST",
headers: {
...headers,
...form.getHeaders(),
},
body: form as unknown as BodyInit,
signal,
});
} else {
const headers = await this._getHeaders(false);
response = await this.fetch(this._getEndpoint(endpoint), {
method: "POST",
headers,
body: JSON.stringify(args),
signal,
});
}
if (response.status === 499) {
return ""; // Aborted by user
if (response.status === 499) {
return ""; // Aborted by user
}
if (!response.ok) {
const errText = await response.text();
// Clear token cache on 401
if (response.status === 401) {
this.sessionTokenPromise = null;
this.tokenTimestamp = 0;
}
throw new Error(
`AskSage API error: ${response.status} ${response.statusText}: ${errText}`,
);
}
const data = (await response.json()) as AskSageResponse;
return (
data.text ||
data.answer ||
data.message ||
data.choices?.[0]?.message?.content ||
""
);
} catch (error) {
if (error instanceof Error) {
throw new Error(`AskSage client error: ${error.message}`);
}
throw error;
}
const data = await response.json();
return data.message;
}
protected async *_streamComplete(
@ -157,30 +344,74 @@ class Asksage extends BaseLLM {
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const args = this._convertArgs(options, messages);
const hasFile = this.isFileLike(args.file);
const endpoint = hasFile ? "query_with_file" : "query";
const response = await this.fetch(this._getEndpoint("query"), {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify(args),
signal,
});
try {
let response;
if (hasFile) {
const form = this.toFormData(args);
const headers = await this._getHeaders(true);
response = await this.fetch(this._getEndpoint(endpoint), {
method: "POST",
headers: {
...headers,
...form.getHeaders(),
},
body: form as unknown as BodyInit,
signal,
});
} else {
const headers = await this._getHeaders(false);
response = await this.fetch(this._getEndpoint(endpoint), {
method: "POST",
headers,
body: JSON.stringify(args),
signal,
});
}
if (response.status === 499) {
return; // Aborted by user
if (response.status === 499) {
return; // Aborted by user
}
if (!response.ok) {
const errText = await response.text();
// Clear token cache on 401
if (response.status === 401) {
this.sessionTokenPromise = null;
this.tokenTimestamp = 0;
}
throw new Error(
`AskSage API error: ${response.status} ${response.statusText}: ${errText}`,
);
}
const data = (await response.json()) as AskSageResponse;
const assistantMessage: ChatMessage = {
role: "assistant",
content:
data.text ||
data.answer ||
data.message ||
data.choices?.[0]?.message?.content ||
"",
};
yield assistantMessage;
} catch (error) {
if (error instanceof Error) {
throw new Error(`AskSage client error: ${error.message}`);
}
throw error;
}
const data = await response.json();
const assistantMessage: ChatMessage = {
role: "assistant",
content: data.message,
};
yield assistantMessage;
}
async listModels(): Promise<string[]> {
return Object.keys(Asksage.modelConversion);
return [];
}
}

View file

@ -44,7 +44,7 @@ describe("alwaysApply Behavior", () => {
alwaysApply: true,
globs: "**/*.tsx", // Should be ignored since alwaysApply is true
source: "rules-block",
ruleFile: ".continue/rules.md",
sourceFile: ".continue/rules.md",
};
// Test with no file context
@ -83,7 +83,7 @@ describe("alwaysApply Behavior", () => {
alwaysApply: false,
globs: "**/*.tsx",
source: "rules-block",
ruleFile: ".continue/rules.md",
sourceFile: ".continue/rules.md",
};
// Rule with alwaysApply: false and no globs
@ -93,7 +93,7 @@ describe("alwaysApply Behavior", () => {
alwaysApply: false,
// No globs
source: "rules-block",
ruleFile: ".continue/rules.md",
sourceFile: ".continue/rules.md",
};
// Test with no file context
@ -131,7 +131,7 @@ describe("alwaysApply Behavior", () => {
name: "Default No Globs Rule",
rule: "Default rule with no globs",
source: "rules-block",
ruleFile: ".continue/rules.md",
sourceFile: ".continue/rules.md",
// No alwaysApply, no globs
};
@ -141,7 +141,7 @@ describe("alwaysApply Behavior", () => {
rule: "Default rule with globs",
globs: "**/*.tsx",
source: "rules-block",
ruleFile: ".continue/rules.md",
sourceFile: ".continue/rules.md",
// No alwaysApply, with globs
};

View file

@ -15,7 +15,7 @@ describe("Rule application with alwaysApply", () => {
rule: "This rule should always be applied",
alwaysApply: true,
source: "rules-block",
ruleFile: ".continue/always-apply.md",
sourceFile: ".continue/always-apply.md",
};
// Create a colocated rule in a nested directory
@ -23,7 +23,7 @@ describe("Rule application with alwaysApply", () => {
name: "Nested Directory Rule",
rule: "This rule applies to files in the nested directory",
source: "rules-block",
ruleFile: "nested-folder/rules.md",
sourceFile: "nested-folder/rules.md",
};
it("should apply alwaysApply rules even with no file references", () => {
@ -145,7 +145,7 @@ describe("Rule application with alwaysApply", () => {
rule: "This rule has alwaysApply: true but is blocked by rulePolicies",
alwaysApply: true,
source: "rules-block",
ruleFile: "src/some/path.md",
sourceFile: "src/some/path.md",
};
// Message with no code blocks or file references

View file

@ -8,7 +8,7 @@ describe("File Path Protocol Matching", () => {
name: "Rule with file:// protocol",
rule: "This is a test rule",
source: "rules-block",
ruleFile: "file:///Users/user/project/nested-folder/rules.md",
sourceFile: "file:///Users/user/project/nested-folder/rules.md",
};
it("should match relative paths with file:// protocol paths", () => {

View file

@ -132,7 +132,7 @@ const isFileInDirectory = (
* Checks if a rule is a root-level rule (.continue directory or no file path)
*/
const isRootLevelRule = (rule: RuleWithSource): boolean => {
return !rule.ruleFile || rule.ruleFile.includes(".continue/"); // ruleFile path is absolute - hence we need to check for it in between
return !rule.sourceFile || rule.sourceFile.includes(".continue/"); // sourceFile path is absolute - hence we need to check for it in between
};
/**
@ -230,8 +230,8 @@ export const shouldApplyRule = (
const isRootRule = isRootLevelRule(rule);
// For non-root rules, we need to check if any files are in the rule's directory
if (!isRootRule && rule.ruleFile) {
const ruleDirectory = getCleanUriPath(rule.ruleFile);
if (!isRootRule && rule.sourceFile) {
const ruleDirectory = getCleanUriPath(rule.sourceFile);
const lastSlashIndex = ruleDirectory.lastIndexOf("/");
const ruleDirPath =
lastSlashIndex !== -1 ? ruleDirectory.substring(0, lastSlashIndex) : "";
@ -325,7 +325,7 @@ export const getApplicableRules = (
};
export function getRuleId(rule: RuleWithSource): string {
return rule.slug ?? rule.ruleFile ?? rule.name ?? rule.source;
return rule.slug ?? rule.sourceFile ?? rule.name ?? rule.source;
}
export const getSystemMessageWithRules = ({

View file

@ -20,7 +20,7 @@ describe("Rule colocation glob matching", () => {
name: "Components Rule",
rule: "Use functional components with hooks",
source: "rules-block",
ruleFile: "src/components/rules.md",
sourceFile: "src/components/rules.md",
// No explicit globs - should only apply to files in src/components/ directory
};
@ -43,7 +43,7 @@ describe("Rule colocation glob matching", () => {
rule: "Use TypeScript with React components",
globs: "**/*.tsx", // Only .tsx files
source: "rules-block",
ruleFile: "src/components/rules.md",
sourceFile: "src/components/rules.md",
// Should only apply to .tsx files in src/components/ directory
};
@ -69,7 +69,7 @@ describe("Rule colocation glob matching", () => {
name: "Root Rule",
rule: "Follow project standards",
source: "rules-block",
ruleFile: "/path/to/repo/.continue/rules.md",
sourceFile: "/path/to/repo/.continue/rules.md",
// No restriction, should apply to all files
};
@ -89,7 +89,7 @@ describe("Rule colocation glob matching", () => {
rule: "Follow these guidelines always",
alwaysApply: true,
source: "rules-block",
ruleFile: "src/specific/rules.md",
sourceFile: "src/specific/rules.md",
// Should apply to all files regardless of directory
};
@ -107,7 +107,7 @@ describe("Rule colocation glob matching", () => {
rule: "This rule should never apply",
alwaysApply: false,
source: "rules-block",
ruleFile: "src/specific/rules.md",
sourceFile: "src/specific/rules.md",
// Should never apply since alwaysApply is false and there are no globs
};
@ -121,7 +121,7 @@ describe("Rule colocation glob matching", () => {
rule: "Apply to TS files but not test files",
globs: ["**/*.ts", "!**/*.test.ts", "!**/*.spec.ts"],
source: "rules-block",
ruleFile: "src/utils/rules.md",
sourceFile: "src/utils/rules.md",
// Should only apply to non-test TS files in src/utils/
};
@ -147,7 +147,7 @@ describe("Rule policies", () => {
name: "Components Rule",
rule: "Use functional components with hooks",
source: "rules-block",
ruleFile: "src/components/rules.md",
sourceFile: "src/components/rules.md",
};
const testFiles = ["src/components/Button.tsx"];
@ -167,7 +167,7 @@ describe("Rule policies", () => {
rule: "This rule would normally always apply",
alwaysApply: true,
source: "rules-block",
ruleFile: "src/components/rules.md",
sourceFile: "src/components/rules.md",
};
const offPolicies: RulePolicies = {
@ -212,7 +212,7 @@ describe("Rule policies", () => {
name: "Root Rule",
rule: "Follow project standards",
source: "rules-block",
ruleFile: "/my/project/.continue/rules.md",
sourceFile: "/my/project/.continue/rules.md",
};
// Off policy should override even global rules
@ -238,7 +238,7 @@ describe("Rule policies", () => {
alwaysApply: true,
globs: "**/*.ts",
source: "rules-block",
ruleFile: "src/utils/rules.md",
sourceFile: "src/utils/rules.md",
};
// Off policy should win over everything
@ -261,7 +261,7 @@ describe("Content pattern matching", () => {
rule: "Follow React component standards",
regex: "export (function|const) \\w+.*\\(",
source: "rules-block",
ruleFile: "src/components/rules.md",
sourceFile: "src/components/rules.md",
};
// File that matches the pattern
@ -293,7 +293,7 @@ describe("Content pattern matching", () => {
rule: "Apply to functions or classes",
regex: ["function\\s+\\w+", "class\\s+\\w+"],
source: "rules-block",
ruleFile: "src/utils/rules.md",
sourceFile: "src/utils/rules.md",
};
const filePath = "src/utils/helper.ts";
@ -332,7 +332,7 @@ describe("Content pattern matching", () => {
globs: "**/*.ts",
regex: "class\\s+\\w+",
source: "rules-block",
ruleFile: "src/models/rules.md",
sourceFile: "src/models/rules.md",
};
const tsFilePath = "src/models/User.ts";
@ -371,7 +371,7 @@ describe("Content pattern matching", () => {
rule: "Use arrow functions for better this binding",
regex: "const\\s+\\w+\\s*=\\s*\\(",
source: "rules-block",
ruleFile: "src/utils/rules.md",
sourceFile: "src/utils/rules.md",
};
// Message with code block containing a matching pattern
@ -433,7 +433,7 @@ describe("Content pattern matching", () => {
rule: "This rule has an invalid regex pattern",
regex: "([unclosed parenthesis",
source: "rules-block",
ruleFile: "src/utils/rules.md",
sourceFile: "src/utils/rules.md",
};
const filePath = "src/utils/helper.ts";
@ -454,7 +454,7 @@ describe("Content pattern matching", () => {
rule: "Apply only to model files with interfaces",
regex: "interface\\s+\\w+",
source: "rules-block",
ruleFile: "src/models/rules.md",
sourceFile: "src/models/rules.md",
};
// File in the correct directory with matching content

View file

@ -8,7 +8,7 @@ describe("Implicit global rules application", () => {
name: "Implicit Global Rule",
rule: "This rule should be applied to all messages (implicit global)",
source: "rules-block",
ruleFile: ".continue/global-rule.md",
sourceFile: ".continue/global-rule.md",
// No alwaysApply specified
// No globs specified
};
@ -19,7 +19,7 @@ describe("Implicit global rules application", () => {
rule: "This rule should always be applied (explicit global)",
alwaysApply: true,
source: "rules-block",
ruleFile: ".continue/explicit-global.md",
sourceFile: ".continue/explicit-global.md",
};
// Create a colocated rule in a nested directory
@ -27,7 +27,7 @@ describe("Implicit global rules application", () => {
name: "Nested Directory Rule",
rule: "This rule applies to files in the nested directory",
source: "rules-block",
ruleFile: "nested-folder/rules.md",
sourceFile: "nested-folder/rules.md",
};
it("should apply rules with no alwaysApply and no globs to all messages, even with no file references", () => {
@ -63,7 +63,7 @@ describe("Implicit global rules application", () => {
name: "Root No Globs Rule",
rule: "This is a root-level rule with no globs",
source: "rules-block",
ruleFile: ".continue/rules.md",
sourceFile: ".continue/rules.md",
// No alwaysApply, no globs
};
@ -119,7 +119,7 @@ describe("Implicit global rules application", () => {
name: "Assistant Guidelines",
rule: "SOLID Design Principles - Coding Assistant Guidelines",
source: "rules-block",
ruleFile: ".continue/rules.md",
sourceFile: ".continue/rules.md",
// No alwaysApply, no globs - should still apply
};

View file

@ -13,7 +13,7 @@ describe("Nested directory rules application", () => {
name: "Nested Folder Rule",
rule: "HELLO WORLD THIS IS A RULE",
source: "rules-block",
ruleFile: "manual-testing-sandbox/nested-folder/rules.md",
sourceFile: "manual-testing-sandbox/nested-folder/rules.md",
// No globs specified
};
@ -22,7 +22,7 @@ describe("Nested directory rules application", () => {
name: "Global Rule",
rule: "SOLID Design Principles - Coding Agent Guidelines",
source: "rules-block",
ruleFile: ".continue/rules.md",
sourceFile: ".continue/rules.md",
};
it("should apply nested directory rules to files in that directory", () => {
@ -103,7 +103,7 @@ describe("Nested directory rules application", () => {
rule: "Follow Python best practices for src directory",
globs: "**/*.py", // This should only match .py files in src/ and subdirectories
source: "rules-block",
ruleFile: "src/rules.md",
sourceFile: "src/rules.md",
};
// A rule in utils/ that targets *.py files
@ -112,7 +112,7 @@ describe("Nested directory rules application", () => {
rule: "Follow Python best practices for utils directory",
globs: "**/*.py", // This should only match .py files in utils/ and subdirectories
source: "rules-block",
ruleFile: "utils/rules.md",
sourceFile: "utils/rules.md",
};
// A file in src/

View file

@ -10,7 +10,7 @@ describe("Rule colocation - glob pattern matching", () => {
name: "General Rule",
rule: "Follow coding standards",
source: "colocated-markdown",
ruleFile: "src/rules.md",
sourceFile: "src/rules.md",
},
// Redux-specific rule with specific directory/file type pattern
@ -19,7 +19,7 @@ describe("Rule colocation - glob pattern matching", () => {
rule: "Use Redux Toolkit",
globs: "src/redux/**/*.{ts,tsx}",
source: "colocated-markdown",
ruleFile: "src/redux/rules.md",
sourceFile: "src/redux/rules.md",
},
// Component-specific rule with array of globs
@ -28,7 +28,7 @@ describe("Rule colocation - glob pattern matching", () => {
rule: "Use functional components",
globs: ["src/components/**/*.tsx", "src/components/**/*.jsx"],
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
sourceFile: "src/components/rules.md",
},
// Rule with explicit alwaysApply: true
@ -38,7 +38,7 @@ describe("Rule colocation - glob pattern matching", () => {
alwaysApply: true,
globs: "src/specific/**/*.ts", // Should be ignored since alwaysApply is true
source: "colocated-markdown",
ruleFile: ".continue/rules.md",
sourceFile: ".continue/rules.md",
},
// Rule with explicit alwaysApply: false
@ -48,7 +48,7 @@ describe("Rule colocation - glob pattern matching", () => {
alwaysApply: false,
// No globs, so should never apply
source: "colocated-markdown",
ruleFile: ".continue/rules.md",
sourceFile: ".continue/rules.md",
},
// Rule with explicit alwaysApply: false but with globs
@ -58,7 +58,7 @@ describe("Rule colocation - glob pattern matching", () => {
alwaysApply: false,
globs: "src/utils/**/*.ts",
source: "colocated-markdown",
ruleFile: "src/utils/rules.md",
sourceFile: "src/utils/rules.md",
},
};
@ -128,7 +128,7 @@ describe("Rule colocation - glob pattern matching", () => {
// Fix: Specify the exact path prefix to restrict to this directory structure
globs: "src/features/auth/utils/**/*.ts",
source: "colocated-markdown",
ruleFile: "src/features/auth/utils/rules.md",
sourceFile: "src/features/auth/utils/rules.md",
};
it("should apply nested rules to files in the same directory and subdirectories", () => {
@ -158,7 +158,7 @@ describe("Rule colocation - glob pattern matching", () => {
// Testing with standard pattern instead
globs: "src/**/[!.]*.ts",
source: "colocated-markdown",
ruleFile: "src/rules.md",
sourceFile: "src/rules.md",
};
it("should apply to matching files that are not excluded", () => {
@ -175,7 +175,7 @@ describe("Rule colocation - glob pattern matching", () => {
globs: ["src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.spec.ts"],
alwaysApply: false,
source: "colocated-markdown",
ruleFile: "src/rules.md",
sourceFile: "src/rules.md",
};
// Using alwaysApply:false with a more specific test

View file

@ -27,14 +27,14 @@ export function getRuleSourceDisplayName(rule: RuleWithSource): string {
case "model-options-chat":
return "Base System Chat Message";
case "agent-file":
if (rule.ruleFile) {
return getLastNPathParts(rule.ruleFile, 2);
if (rule.sourceFile) {
return getLastNPathParts(rule.sourceFile, 2);
} else {
return "Agent file";
}
case "colocated-markdown":
if (rule.ruleFile) {
return getLastNPathParts(rule.ruleFile, 2);
if (rule.sourceFile) {
return getLastNPathParts(rule.sourceFile, 2);
} else {
return "rules.md";
}

View file

@ -41,7 +41,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
it("should return true for Gemini models", () => {
expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-pro")).toBe(true);
expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-1.5-pro")).toBe(
expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-2.5-pro")).toBe(
true,
);
});
@ -139,7 +139,6 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
it("should return true for all Gemini models", () => {
expect(supportsFn("gemini-pro")).toBe(true);
expect(supportsFn("gemini-1.5-pro")).toBe(true);
expect(supportsFn("gemini-ultra")).toBe(true);
});
@ -150,7 +149,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
it("should handle case insensitivity", () => {
expect(supportsFn("GEMINI-pro")).toBe(true);
expect(supportsFn("Gemini-1.5-Pro")).toBe(true);
expect(supportsFn("Gemini-2.5-Pro")).toBe(true);
});
});

View file

@ -1,5 +1,7 @@
import { COUNT_COMPLETION_REJECTED_AFTER } from "../util/parameters";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import { getControlPlaneEnvSync } from "../control-plane/env";
import { DataLogger } from "../data/log";
import { Telemetry } from "../util/posthog";
import { NextEditOutcome } from "./types";
@ -121,6 +123,7 @@ export class NextEditLoggingService {
clearTimeout(this._logRejectionTimeouts.get(completionId)!);
this._logRejectionTimeouts.delete(completionId);
}
if (this._outcomes.has(completionId)) {
this._outcomes.delete(completionId);
}
@ -185,44 +188,15 @@ export class NextEditLoggingService {
this._logRejectionTimeouts.delete(completionId);
}
// If we have the full outcome, log it as aborted.
// Only log if the completion was displayed to the user.
// This aligns with Autocomplete behavior and prevents logging
// of cancelled requests that never reached the user.
if (this._outcomes.has(completionId)) {
const outcome = this._outcomes.get(completionId)!;
outcome.accepted = false;
// outcome.accepted = false;
outcome.aborted = true;
this.logNextEditOutcome(outcome);
this._outcomes.delete(completionId);
} else {
// Log minimal abort event for requests that never got displayed.
const pendingData = this._pendingCompletions.get(completionId);
const minimalAbortOutcome: Partial<NextEditOutcome> = {
completionId,
accepted: false,
aborted: true,
timestamp: Date.now(),
uniqueId: completionId,
elapsed: pendingData ? Date.now() - pendingData.startTime : 0,
modelName: pendingData?.modelName || "unknown",
modelProvider: pendingData?.modelProvider || "unknown",
fileUri: pendingData?.filepath || "unknown",
// Empty/default values for fields we don't have.
completion: "",
prompt: "",
userEdits: "",
userExcerpts: "",
originalEditableRange: "",
workspaceDirUri: "",
cursorPosition: { line: -1, character: -1 },
finalCursorPosition: { line: -1, character: -1 },
editableRegionStartLine: -1,
editableRegionEndLine: -1,
diffLines: [],
completionOptions: {},
};
this.logNextEditOutcome(minimalAbortOutcome as NextEditOutcome);
}
// Clean up.
@ -243,6 +217,35 @@ export class NextEditLoggingService {
});
// const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
if (outcome.requestId && outcome.accepted !== undefined) {
void this.logAcceptReject(outcome.requestId, outcome.accepted);
}
void Telemetry.capture("nextEditOutcome", outcome, true);
}
private async logAcceptReject(
requestId: string,
accepted: boolean,
): Promise<void> {
try {
if (!Telemetry.client) {
return;
}
const controlPlaneEnv = getControlPlaneEnvSync("production");
const resp = await fetchwithRequestOptions(
new URL("model-proxy/v1/feedback", controlPlaneEnv.CONTROL_PLANE_URL),
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
requestId,
accepted,
}),
},
);
} catch (error) {}
}
}

View file

@ -140,7 +140,7 @@ export class PrefetchQueue {
const count = Math.min(3, this.processedQueue.length);
const firstThree = this.processedQueue.slice(0, count);
firstThree.forEach((item, index) => {
console.log(
console.debug(
`Item ${index + 1}: ${item.location.range.start.line} to ${item.location.range.end.line}`,
);
});

View file

@ -8,6 +8,7 @@ import { ContextRetrievalService } from "../autocomplete/context/ContextRetrieva
import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js";
import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js";
import { postprocessCompletion } from "../autocomplete/postprocessing/index.js";
import { shouldPrefilter } from "../autocomplete/prefiltering/index.js";
import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js";
import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js";
@ -415,6 +416,7 @@ export class NextEditProvider {
filePath: helper.filepath,
diffType: DiffFormatType.Unified,
contextLines: 3,
workspaceDir: workspaceDirs[0], // Use first workspace directory
}),
};
@ -468,33 +470,53 @@ export class NextEditProvider {
}
// Extract completion using model-specific logic.
const nextCompletion = this.modelProvider.extractCompletion(msg.content);
let nextCompletion = this.modelProvider.extractCompletion(msg.content);
// Postprocess the completion (same as autocomplete).
const postprocessed = postprocessCompletion({
completion: nextCompletion,
llm,
prefix: helper.prunedPrefix,
suffix: helper.prunedSuffix,
});
// Return early if postprocessing filtered out the completion.
if (!postprocessed) {
return undefined;
}
nextCompletion = postprocessed;
let outcome: NextEditOutcome | undefined;
// Handle based on diff type.
const profileType =
this.configHandler.currentProfile?.profileDescription.profileType;
if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
outcome = await this.modelProvider.handlePartialFileDiff(
outcome = await this.modelProvider.handlePartialFileDiff({
helper,
editableRegionStartLine,
editableRegionEndLine,
startTime,
llm,
nextCompletion,
this.promptMetadata!,
this.ide,
);
promptMetadata: this.promptMetadata!,
ide: this.ide,
profileType,
});
} else {
outcome = await this.modelProvider.handleFullFileDiff(
outcome = await this.modelProvider.handleFullFileDiff({
helper,
editableRegionStartLine,
editableRegionEndLine,
startTime,
llm,
nextCompletion,
this.promptMetadata!,
this.ide,
);
promptMetadata: this.promptMetadata!,
ide: this.ide,
profileType,
});
}
if (outcome) {

View file

@ -1,4 +1,5 @@
import { createPatch } from "diff";
import { getUriPathBasename } from "../../util/uri";
export enum DiffFormatType {
Unified = "unified",
@ -18,6 +19,7 @@ export interface CreateDiffArgs {
filePath: string;
diffType: DiffFormatType;
contextLines: number;
workspaceDir?: string;
}
export const createDiff = ({
@ -26,6 +28,7 @@ export const createDiff = ({
filePath,
diffType,
contextLines,
workspaceDir,
}: CreateDiffArgs) => {
switch (diffType) {
case DiffFormatType.Unified:
@ -34,6 +37,7 @@ export const createDiff = ({
afterContent,
filePath,
contextLines,
workspaceDir,
);
case DiffFormatType.TokenLineDiff:
return createTokenLineDiff(beforeContent, afterContent, filePath);
@ -46,6 +50,7 @@ const createUnifiedDiff = (
afterContent: string,
filePath: string,
contextLines: number,
workspaceDir?: string,
) => {
const normalizedBefore = beforeContent.endsWith("\n")
? beforeContent
@ -54,12 +59,21 @@ const createUnifiedDiff = (
? afterContent
: afterContent + "\n";
// Use relative path if workspace directory is provided
let displayPath = filePath;
if (workspaceDir && filePath.startsWith(workspaceDir)) {
displayPath = filePath.slice(workspaceDir.length).replace(/^[\/]/, "");
} else if (workspaceDir) {
// Fallback to just the basename if we can't determine relative path
displayPath = getUriPathBasename(filePath);
}
const patch = createPatch(
filePath,
displayPath,
normalizedBefore,
normalizedAfter,
"before",
"after",
undefined,
undefined,
{ context: contextLines },
);

View file

@ -127,6 +127,72 @@ describe("diffFormatting", () => {
expect(result).toContain("@@ -4,5 +4,5 @@");
});
it("should use relative path when workspaceDir is provided", () => {
const args: CreateDiffArgs = {
beforeContent,
afterContent,
filePath: "file:///workspace/project/src/test.js",
diffType: DiffFormatType.Unified,
contextLines: 3,
workspaceDir: "file:///workspace/project",
};
const result = createDiff(args);
expect(result).toContain("--- src/test.js");
expect(result).toContain("+++ src/test.js");
expect(result).not.toContain("file://");
expect(result).not.toContain("/workspace/project");
});
it("should handle workspaceDir with trailing slash", () => {
const args: CreateDiffArgs = {
beforeContent,
afterContent,
filePath: "file:///workspace/project/src/test.js",
diffType: DiffFormatType.Unified,
contextLines: 3,
workspaceDir: "file:///workspace/project/",
};
const result = createDiff(args);
expect(result).toContain("--- src/test.js");
expect(result).toContain("+++ src/test.js");
});
it("should fallback to basename when path not in workspace", () => {
const args: CreateDiffArgs = {
beforeContent,
afterContent,
filePath: "file:///other/location/test.js",
diffType: DiffFormatType.Unified,
contextLines: 3,
workspaceDir: "file:///workspace/project",
};
const result = createDiff(args);
expect(result).toContain("--- test.js");
expect(result).toContain("+++ test.js");
});
it("should use full path when no workspaceDir provided", () => {
const fullPath = "file:///workspace/project/src/test.js";
const args: CreateDiffArgs = {
beforeContent,
afterContent,
filePath: fullPath,
diffType: DiffFormatType.Unified,
contextLines: 3,
};
const result = createDiff(args);
expect(result).toContain(`--- ${fullPath}`);
expect(result).toContain(`+++ ${fullPath}`);
});
});
describe("createBeforeAfterDiff", () => {

View file

@ -140,6 +140,7 @@ export const processNextEditData = async ({
filePath: filePath,
diffType: DiffFormatType.Unified,
contextLines: 25, // storing many context lines for downstream trimming
workspaceDir: workspaceDir,
}),
fileUri: filePath,
workspaceUri: workspaceDir,

View file

@ -14,16 +14,6 @@ export const processSmallEdit = async (
getDefsFromLspFunction: GetLspDefinitionsFunction,
ide: IDE,
) => {
NextEditProvider.getInstance().addDiffToContext(
createDiff({
beforeContent: beforeAfterdiff.beforeContent,
afterContent: beforeAfterdiff.afterContent,
filePath: beforeAfterdiff.filePath,
diffType: DiffFormatType.Unified,
contextLines: 5, // NOTE: This can change depending on experiments!
}),
);
// Get the current context data from the most recent message
const currentData = (EditAggregator.getInstance() as any)
.latestContextData || {
@ -33,6 +23,17 @@ export const processSmallEdit = async (
recentlyVisitedRanges: [],
};
NextEditProvider.getInstance().addDiffToContext(
createDiff({
beforeContent: beforeAfterdiff.beforeContent,
afterContent: beforeAfterdiff.afterContent,
filePath: beforeAfterdiff.filePath,
diffType: DiffFormatType.Unified,
contextLines: 3, // NOTE: This can change depending on experiments!
workspaceDir: currentData.workspaceDir,
}),
);
void processNextEditData({
filePath: beforeAfterdiff.filePath,
beforeContent: beforeAfterdiff.beforeContent,

View file

@ -47,16 +47,28 @@ export abstract class BaseNextEditModelProvider {
};
// Methods that can be used as default fallback.
public async handlePartialFileDiff(
helper: HelperVars,
editableRegionStartLine: number,
editableRegionEndLine: number,
startTime: number,
llm: ILLM,
nextCompletion: string,
promptMetadata: PromptMetadata,
ide: IDE,
): Promise<NextEditOutcome> {
public async handlePartialFileDiff(params: {
helper: HelperVars;
editableRegionStartLine: number;
editableRegionEndLine: number;
startTime: number;
llm: ILLM;
nextCompletion: string;
promptMetadata: PromptMetadata;
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<NextEditOutcome> {
const {
helper,
editableRegionStartLine,
editableRegionEndLine,
startTime,
llm,
nextCompletion,
promptMetadata,
ide,
profileType,
} = params;
const oldEditRangeSlice = helper.fileContents
.split("\n")
.slice(editableRegionStartLine, editableRegionEndLine + 1)
@ -83,21 +95,34 @@ export abstract class BaseNextEditModelProvider {
originalEditableRange: oldEditRangeSlice,
diffLines: [],
ide,
profileType,
});
return outcome;
}
public async handleFullFileDiff(
helper: HelperVars,
editableRegionStartLine: number,
editableRegionEndLine: number,
startTime: number,
llm: ILLM,
nextCompletion: string,
promptMetadata: PromptMetadata,
ide: IDE,
): Promise<NextEditOutcome | undefined> {
public async handleFullFileDiff(params: {
helper: HelperVars;
editableRegionStartLine: number;
editableRegionEndLine: number;
startTime: number;
llm: ILLM;
nextCompletion: string;
promptMetadata: PromptMetadata;
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<NextEditOutcome | undefined> {
const {
helper,
editableRegionStartLine,
editableRegionEndLine,
startTime,
llm,
nextCompletion,
promptMetadata,
ide,
profileType,
} = params;
const fileSlice = helper.fileLines
.slice(editableRegionStartLine, editableRegionEndLine + 1)
.join("\n");
@ -111,7 +136,7 @@ export abstract class BaseNextEditModelProvider {
const currentLine = helper.pos.line;
const prefetchQueue = PrefetchQueue.getInstance();
const cursorLocalDiffGroup = await this.processDiffGroups(
const cursorLocalDiffGroup = await this.processDiffGroups({
diffGroups,
currentLine,
helper,
@ -120,19 +145,21 @@ export abstract class BaseNextEditModelProvider {
prefetchQueue,
promptMetadata,
ide,
);
profileType,
});
if (cursorLocalDiffGroup) {
return await this.createOutcomeFromDiffGroup(
cursorLocalDiffGroup,
return await this.createOutcomeFromDiffGroup({
diffGroup: cursorLocalDiffGroup,
helper,
startTime,
llm,
helper.input.completionId,
true,
completionId: helper.input.completionId,
isCurrentCursorGroup: true,
promptMetadata,
ide,
);
profileType,
});
}
return undefined;
@ -141,23 +168,35 @@ export abstract class BaseNextEditModelProvider {
/**
* Process diff groups and find the one containing the cursor.
*/
private async processDiffGroups(
diffGroups: DiffGroup[],
currentLine: number,
helper: HelperVars,
startTime: number,
llm: ILLM,
prefetchQueue: PrefetchQueue,
promptMetadata: PromptMetadata,
ide: IDE,
): Promise<DiffGroup | undefined> {
private async processDiffGroups(params: {
diffGroups: DiffGroup[];
currentLine: number;
helper: HelperVars;
startTime: number;
llm: ILLM;
prefetchQueue: PrefetchQueue;
promptMetadata: PromptMetadata;
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<DiffGroup | undefined> {
const {
diffGroups,
currentLine,
helper,
startTime,
llm,
prefetchQueue,
promptMetadata,
ide,
profileType,
} = params;
let cursorGroup: DiffGroup | undefined;
for (const group of diffGroups) {
if (currentLine >= group.startLine && currentLine <= group.endLine) {
cursorGroup = group;
} else {
await this.addDiffGroupToPrefetchQueue(
await this.addDiffGroupToPrefetchQueue({
group,
helper,
startTime,
@ -165,22 +204,34 @@ export abstract class BaseNextEditModelProvider {
prefetchQueue,
promptMetadata,
ide,
);
profileType,
});
}
}
return cursorGroup;
}
private async addDiffGroupToPrefetchQueue(
group: DiffGroup,
helper: HelperVars,
startTime: number,
llm: ILLM,
prefetchQueue: PrefetchQueue,
promptMetadata: PromptMetadata,
ide: IDE,
): Promise<void> {
private async addDiffGroupToPrefetchQueue(params: {
group: DiffGroup;
helper: HelperVars;
startTime: number;
llm: ILLM;
prefetchQueue: PrefetchQueue;
promptMetadata: PromptMetadata;
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<void> {
const {
group,
helper,
startTime,
llm,
prefetchQueue,
promptMetadata,
ide,
profileType,
} = params;
// Extract lines that are not old.
const groupContent = group.lines
.filter((l) => l.type !== "old")
@ -223,6 +274,7 @@ export abstract class BaseNextEditModelProvider {
completionId: uuidv4(), // Generate a new ID for this prefetched item.
diffLines: group.lines,
ide,
profileType,
});
prefetchQueue.enqueueProcessed({
@ -231,16 +283,28 @@ export abstract class BaseNextEditModelProvider {
});
}
private async createOutcomeFromDiffGroup(
diffGroup: DiffGroup,
helper: HelperVars,
startTime: number,
llm: ILLM,
completionId: string,
isCurrentCursorGroup: boolean,
promptMetadata: PromptMetadata,
ide: IDE,
): Promise<NextEditOutcome> {
private async createOutcomeFromDiffGroup(params: {
diffGroup: DiffGroup;
helper: HelperVars;
startTime: number;
llm: ILLM;
completionId: string;
isCurrentCursorGroup: boolean;
promptMetadata: PromptMetadata;
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<NextEditOutcome> {
const {
diffGroup,
helper,
startTime,
llm,
completionId,
isCurrentCursorGroup,
promptMetadata,
ide,
profileType,
} = params;
const groupContent = diffGroup.lines
.filter((l) => l.type !== "old")
.map((l) => l.line)
@ -278,6 +342,7 @@ export abstract class BaseNextEditModelProvider {
completionId,
diffLines: diffGroup.lines,
ide,
profileType,
});
return outcomeNext;
@ -299,6 +364,7 @@ export abstract class BaseNextEditModelProvider {
completionId?: string;
diffLines: DiffLine[];
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<NextEditOutcome> {
return {
elapsed: Date.now() - outcomeCtx.startTime,
@ -309,6 +375,7 @@ export abstract class BaseNextEditModelProvider {
outcomeCtx.completionId || outcomeCtx.helper.input.completionId,
gitRepo: await outcomeCtx.ide.getRepoName(outcomeCtx.helper.filepath),
uniqueId: await outcomeCtx.ide.getUniqueId(),
requestId: outcomeCtx.llm.lastRequestId,
timestamp: Date.now(),
fileUri: outcomeCtx.helper.filepath,
workspaceDirUri:
@ -324,6 +391,7 @@ export abstract class BaseNextEditModelProvider {
editableRegionStartLine: outcomeCtx.editableRegionStartLine,
editableRegionEndLine: outcomeCtx.editableRegionEndLine,
diffLines: outcomeCtx.diffLines,
profileType: outcomeCtx.profileType,
...outcomeCtx.helper.options,
};
}

View file

@ -50,6 +50,7 @@ export interface NextEditOutcome extends TabAutocompleteOptions {
completionId: string;
gitRepo?: string;
uniqueId: string;
requestId?: string;
timestamp: number;
// New for Next Edit.
@ -67,6 +68,7 @@ export interface NextEditOutcome extends TabAutocompleteOptions {
editableRegionStartLine: number;
editableRegionEndLine: number;
diffLines: DiffLine[];
profileType?: "local" | "platform" | "control-plane";
}
export interface PromptMetadata {

View file

@ -1,86 +1,15 @@
import { DEFAULT_PROMPTS_FOLDER_V1 } from ".";
import path from "path";
import {
DEFAULT_PROMPTS_FOLDER_V1,
DEFAULT_PROMPTS_FOLDER_V2,
DEFAULT_RULES_FOLDER,
RULES_DIR_NAME,
} from ".";
import { IDE } from "..";
import { walkDir } from "../indexing/walkDir";
import { readAllGlobalPromptFiles } from "../util/paths";
import { getContinueGlobalPath, readAllGlobalPromptFiles } from "../util/paths";
import { joinPathsToUri } from "../util/uri";
// The hardcoded init prompt content
const INIT_PROMPT_CONTENT = `name: Init
description: Initialize Codebase
---
You are an expert development assistant. Your task is to create a comprehensive CONTINUE.md project guide for the user's codebase to help them and their team better understand and work with the project.
## Step 1: Check Required Tools
First, verify that you have access to the necessary tools:
- builtin_file_glob_search: To discover project files
- builtin_read_file: To analyze file contents
- builtin_ls: To explore directory structure
- builtin_create_new_file: To generate the CONTINUE.md file
If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding.
## Step 2: Project Analysis
Analyze the project structure and key files to understand:
- The programming languages and frameworks used
- The overall architecture and organization
- Key components and their responsibilities
- Important configuration files
- Build/deployment system
## Step 3: Generate CONTINUE.md
Create a comprehensive CONTINUE.md file in the .continue/rules/ directory with the following sections:
1. **Project Overview**
- Brief description of the project's purpose
- Key technologies used
- High-level architecture
2. **Getting Started**
- Prerequisites (required software, dependencies)
- Installation instructions
- Basic usage examples
- Running tests
3. **Project Structure**
- Overview of main directories and their purpose
- Key files and their roles
- Important configuration files
4. **Development Workflow**
- Coding standards or conventions
- Testing approach
- Build and deployment process
- Contribution guidelines
5. **Key Concepts**
- Domain-specific terminology
- Core abstractions
- Design patterns used
6. **Common Tasks**
- Step-by-step guides for frequent development tasks
- Examples of common operations
7. **Troubleshooting**
- Common issues and their solutions
- Debugging tips
8. **References**
- Links to relevant documentation
- Important resources
Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification.
## Step 4: Finalize
After creating the .continue/rules/CONTINUE.md file, provide a summary of what you've created and remind the user to:
1. Review and edit the file as needed
2. Commit it to their repository to share with their team
3. Explain that Continue will automatically load this file into context when working with the project
Also inform the user that they can create additional rules.md files in subdirectories for more specific documentation related to those components.`;
export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
export async function getPromptFilesFromDir(
ide: IDE,
dir: string,
@ -115,7 +44,7 @@ export async function getAllPromptFiles(
const workspaceDirs = await ide.getWorkspaceDirs();
let promptFiles: { path: string; content: string }[] = [];
let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2];
let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2, DEFAULT_RULES_FOLDER];
if (checkV1DefaultFolder) {
dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1);
}
@ -131,20 +60,16 @@ export async function getAllPromptFiles(
await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir)))
).flat();
// Also read from ~/.continue/.prompts
// Also read from ~/.continue/prompts and ~/.continue/rules
promptFiles.push(...readAllGlobalPromptFiles());
// Add hardcoded init prompt
promptFiles.push({
path: "builtin:/init.prompt",
content: INIT_PROMPT_CONTENT,
});
const promptFilesFromRulesDirectory = readAllGlobalPromptFiles(
path.join(getContinueGlobalPath(), RULES_DIR_NAME),
);
promptFiles.push(...promptFilesFromRulesDirectory);
return await Promise.all(
promptFiles.map(async (file) => {
if (file.path.startsWith("builtin:")) {
return file;
}
const content = await ide.readFile(file.path);
return { path: file.path, content };
}),

View file

@ -2,6 +2,11 @@ import { ContextProviderName } from "..";
export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts";
export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
export const DEFAULT_RULES_FOLDER = ".continue/rules";
// Subdirectory names (without .continue/ prefix)
export const RULES_DIR_NAME = "rules";
export const PROMPTS_DIR_NAME = "prompts";
export const SUPPORTED_PROMPT_CONTEXT_PROVIDERS: ContextProviderName[] = [
"file",

View file

@ -0,0 +1,86 @@
import { SlashCommandWithSource } from "..";
import { RULES_MARKDOWN_FILENAME } from "../llm/rules/constants";
import { BuiltInToolNames } from "../tools/builtIn";
const initFilename = "CONTINUE.md";
// Prompt for init slash command
export const INIT_PROMPT_CONTENT = `
You are an expert development assistant. Your task is to create a comprehensive ${initFilename} project guide for the user's codebase to help them and their team better understand and work with the project.
## Step 1: Check Required Tools
First, verify that you have access to the necessary tools:
- ${BuiltInToolNames.FileGlobSearch}: To discover project files
- ${BuiltInToolNames.ReadFile}: To analyze file contents
- ${BuiltInToolNames.LSTool}: To explore directory structure
- ${BuiltInToolNames.CreateNewFile}: To generate the ${initFilename} file
If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding.
## Step 2: Project Analysis
Analyze the project structure and key files to understand:
- The programming languages and frameworks used
- The overall architecture and organization
- Key components and their responsibilities
- Important configuration files
- Build/deployment system
## Step 3: Generate ${initFilename}
Create a comprehensive ${initFilename} file in the .continue/rules/ directory with the following sections:
1. **Project Overview**
- Brief description of the project's purpose
- Key technologies used
- High-level architecture
2. **Getting Started**
- Prerequisites (required software, dependencies)
- Installation instructions
- Basic usage examples
- Running tests
3. **Project Structure**
- Overview of main directories and their purpose
- Key files and their roles
- Important configuration files
4. **Development Workflow**
- Coding standards or conventions
- Testing approach
- Build and deployment process
- Contribution guidelines
5. **Key Concepts**
- Domain-specific terminology
- Core abstractions
- Design patterns used
6. **Common Tasks**
- Step-by-step guides for frequent development tasks
- Examples of common operations
7. **Troubleshooting**
- Common issues and their solutions
- Debugging tips
8. **References**
- Links to relevant documentation
- Important resources
Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification.
## Step 4: Finalize
After creating the .continue/rules/${initFilename} file, provide a summary of what you've created and remind the user to:
1. Review and edit the file as needed
2. Commit it to their repository to share with their team
3. Explain that Continue will automatically load this file into context when working with the project
Also inform the user that they can create additional ${RULES_MARKDOWN_FILENAME} files in subdirectories for more specific documentation related to those components.
`.trim();
export const initSlashCommand: SlashCommandWithSource = {
name: "Init",
description: "Initialize Codebase",
source: "built-in",
prompt: INIT_PROMPT_CONTENT,
};

View file

@ -54,6 +54,7 @@ import {
} from "../control-plane/client";
import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue";
import { NextEditOutcome } from "../nextEdit/types";
import { ContinueErrorReason } from "../util/errors";
export enum OnboardingModes {
API_KEY = "API Key",
@ -93,6 +94,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
void,
];
"config/addLocalWorkspaceBlock": [{ blockType: BlockType }, void];
"config/addGlobalRule": [undefined, void];
"config/newPromptFile": [undefined, void];
"config/newAssistantFile": [undefined, void];
"config/ideSettingsUpdate": [IdeSettings, void];
@ -117,10 +119,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
),
void,
];
"config/openProfile": [
{ profileId: string | undefined; element?: { sourceFile?: string } },
void,
];
"config/openProfile": [{ profileId: string | undefined }, void];
"config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema];
"config/updateSelectedModel": [
{
@ -147,8 +146,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
void,
];
"mcp/disconnectServer": [{ id: string }, void];
"mcp/getDisconnectedServers": [undefined, string[]];
"mcp/setServerEnabled": [{ id: string; enabled: boolean }, void];
"mcp/getPrompt": [
{
serverName: string;
@ -318,6 +316,14 @@ export type ToCoreFromIdeOrWebviewProtocol = {
{ toolName: string; basePolicy: ToolPolicy; args: Record<string, unknown> },
{ policy: ToolPolicy; displayValue?: string },
];
"tools/preprocessArgs": [
{ toolName: string; args: Record<string, unknown> },
{
preprocessedArgs?: Record<string, unknown>;
errorReason?: ContinueErrorReason;
errorMessage?: string;
},
];
"clipboardCache/add": [{ content: string }, void];
"controlPlane/openUrl": [{ path: string; orgSlug?: string }, void];
"controlPlane/getEnvironment": [undefined, ControlPlaneEnv];

View file

@ -3,6 +3,7 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
import {
AcceptOrRejectDiffPayload,
AddToChatPayload,
ApplyState,
ApplyToFilePayload,
HighlightedCodePayload,
@ -78,4 +79,5 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
exitEditMode: [undefined, void];
focusEdit: [undefined, void];
generateRule: [undefined, void];
addToChat: [AddToChatPayload, void];
};

View file

@ -22,6 +22,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"config/newAssistantFile",
"config/ideSettingsUpdate",
"config/addLocalWorkspaceBlock",
"config/addGlobalRule",
"config/getSerializedProfileInfo",
"config/deleteModel",
"config/refreshProfiles",
@ -32,8 +33,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"mcp/getPrompt",
"mcp/startAuthentication",
"mcp/removeAuthentication",
"mcp/disconnectServer",
"mcp/getDisconnectedServers",
"mcp/setServerEnabled",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
@ -82,6 +82,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"didChangeSelectedOrg",
"tools/call",
"tools/evaluatePolicy",
"tools/preprocessArgs",
"controlPlane/getEnvironment",
"controlPlane/getFreeTrialStatus",
"controlPlane/getModelsAddOnUpgradeUrl",

View file

@ -1,2 +1,4 @@
export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output";
export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call.";
export const ERRORED_TOOL_CALL_OUTPUT_MESSAGE =
"There was an error calling the tool.";

View file

@ -1,4 +1,7 @@
import { Tool } from "../..";
import { validateMultiEdit } from "../../edit/searchAndReplace/multiEditValidation";
import { executeMultiFindAndReplace } from "../../edit/searchAndReplace/performReplace";
import { validateSearchAndReplaceFilepath } from "../../edit/searchAndReplace/validateArgs";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile";
@ -107,4 +110,24 @@ WARNINGS:
],
},
defaultToolPolicy: "allowedWithPermission",
preprocessArgs: async (args, extras) => {
const { edits } = validateMultiEdit(args);
const fileUri = await validateSearchAndReplaceFilepath(
args.filepath,
extras.ide,
);
const editingFileContents = await extras.ide.readFile(fileUri);
const newFileContents = executeMultiFindAndReplace(
editingFileContents,
edits,
);
return {
...args,
fileUri,
editingFileContents,
newFileContents,
};
},
};

View file

@ -10,7 +10,7 @@ describe("getRequestRuleDescription", () => {
source: "default-chat",
rule: "Always use semicolons",
alwaysApply: true,
ruleFile: "/path/to/rule1.md",
sourceFile: "/path/to/rule1.md",
},
{
name: "Rule with Globs",
@ -18,7 +18,7 @@ describe("getRequestRuleDescription", () => {
source: "rules-block",
rule: "Use TypeScript",
globs: "**/*.ts",
ruleFile: "/path/to/rule2.md",
sourceFile: "/path/to/rule2.md",
},
];
@ -38,7 +38,7 @@ describe("getRequestRuleDescription", () => {
source: "rules-block",
rule: "Use consistent formatting",
alwaysApply: false,
ruleFile: "/path/to/agent-rule1.md",
sourceFile: "/path/to/agent-rule1.md",
},
{
name: "Agent Rule 2",
@ -46,7 +46,7 @@ describe("getRequestRuleDescription", () => {
source: "default-agent",
rule: "Follow naming conventions",
alwaysApply: false,
ruleFile: "/path/to/agent-rule2.md",
sourceFile: "/path/to/agent-rule2.md",
},
// These should be filtered out
{
@ -55,7 +55,7 @@ describe("getRequestRuleDescription", () => {
source: "default-chat",
rule: "Always use semicolons",
alwaysApply: true,
ruleFile: "/path/to/rule1.md",
sourceFile: "/path/to/rule1.md",
},
{
name: "Rule with Globs",
@ -63,7 +63,7 @@ describe("getRequestRuleDescription", () => {
source: "rules-block",
rule: "Use TypeScript",
globs: "**/*.ts",
ruleFile: "/path/to/rule2.md",
sourceFile: "/path/to/rule2.md",
},
];
@ -84,7 +84,7 @@ describe("getRequestRuleDescription", () => {
source: "rules-block",
rule: "Some rule content",
alwaysApply: false,
ruleFile: "/path/to/no-desc-rule.md",
sourceFile: "/path/to/no-desc-rule.md",
},
];
@ -104,7 +104,7 @@ describe("getRequestRuleDescription", () => {
source: "rules-block",
rule: "Some rule content",
alwaysApply: false,
ruleFile: "/path/to/no-name-rule.md",
sourceFile: "/path/to/no-name-rule.md",
},
];
@ -117,7 +117,7 @@ describe("getRequestRuleDescription", () => {
expect(result).toBe(expected);
});
it("should handle rules with missing ruleFile", () => {
it("should handle rules with missing sourceFile", () => {
const rules: RuleWithSource[] = [
{
name: "Rule Without File",
@ -144,7 +144,7 @@ describe("getRequestRuleDescription", () => {
description: "This should be filtered out",
source: "rules-block",
rule: "Some rule",
ruleFile: "/path/to/rule.md",
sourceFile: "/path/to/rule.md",
// alwaysApply is undefined, which is truthy in the filter condition
},
{
@ -153,7 +153,7 @@ describe("getRequestRuleDescription", () => {
source: "rules-block",
rule: "Some rule",
alwaysApply: false,
ruleFile: "/path/to/valid-rule.md",
sourceFile: "/path/to/valid-rule.md",
},
];
@ -175,7 +175,7 @@ describe("getRequestRuleDescription", () => {
rule: "Some rule",
alwaysApply: false,
globs: "**/*.ts",
ruleFile: "/path/to/rule1.md",
sourceFile: "/path/to/rule1.md",
},
{
name: "Rule with array globs",
@ -184,7 +184,7 @@ describe("getRequestRuleDescription", () => {
rule: "Some rule",
alwaysApply: false,
globs: ["**/*.ts", "**/*.js"],
ruleFile: "/path/to/rule2.md",
sourceFile: "/path/to/rule2.md",
},
{
name: "Valid Agent Rule",
@ -192,7 +192,7 @@ describe("getRequestRuleDescription", () => {
source: "rules-block",
rule: "Some rule",
alwaysApply: false,
ruleFile: "/path/to/valid-rule.md",
sourceFile: "/path/to/valid-rule.md",
},
];
@ -224,7 +224,7 @@ describe("getRequestRuleDescription", () => {
source: "rules-block",
rule: "Follow this guideline",
alwaysApply: false,
ruleFile: "/path/to/single-rule.md",
sourceFile: "/path/to/single-rule.md",
},
];

View file

@ -1,4 +1,7 @@
import { Tool } from "../..";
import { validateSingleEdit } from "../../edit/searchAndReplace/findAndReplaceUtils";
import { executeFindAndReplace } from "../../edit/searchAndReplace/performReplace";
import { validateSearchAndReplaceFilepath } from "../../edit/searchAndReplace/validateArgs";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile";
@ -70,4 +73,31 @@ WARNINGS:
],
},
defaultToolPolicy: "allowedWithPermission",
preprocessArgs: async (args, extras) => {
const { oldString, newString, replaceAll } = validateSingleEdit(
args.old_string,
args.new_string,
args.replace_all,
);
const fileUri = await validateSearchAndReplaceFilepath(
args.filepath,
extras.ide,
);
const editingFileContents = await extras.ide.readFile(fileUri);
const newFileContents = executeFindAndReplace(
editingFileContents,
oldString,
newString,
replaceAll ?? false,
0,
);
return {
...args,
fileUri,
editingFileContents,
newFileContents,
};
},
};

View file

@ -7,7 +7,7 @@ export const requestRuleImpl: ToolImpl = async (args, extras) => {
// Find the rule by name in the config
const rule = extras.config.rules.find((r) => r.name === name);
if (!rule || !rule.ruleFile) {
if (!rule || !rule.sourceFile) {
throw new Error(`Rule with name "${name}" not found or has no file path`);
}
@ -18,7 +18,7 @@ export const requestRuleImpl: ToolImpl = async (args, extras) => {
content: rule.rule,
uri: {
type: "file",
value: rule.ruleFile,
value: rule.sourceFile,
},
},
];

View file

@ -51,3 +51,8 @@ export const getConfigDependentToolDefinitions = (
return tools;
};
export function serializeTool(tool: Tool) {
const { preprocessArgs, evaluateToolCallPolicy, ...rest } = tool;
return rest;
}

View file

@ -30,6 +30,7 @@ export type GlobalContextType = {
selectedModelsByProfileId: {
[profileId: string]: GlobalContextModelSelections;
};
cliSelectedModel?: string; // CLI-specific model selection for unauthenticated users
/**
* This is needed to handle the case where a JetBrains user has created

View file

@ -27,6 +27,7 @@ export enum ContinueErrorReason {
FindAndReplaceMissingOldString = "find_and_replace_missing_old_string",
FindAndReplaceNonFirstEmptyOldString = "find_and_replace_non_first_empty_old_string",
FindAndReplaceMissingNewString = "find_and_replace_missing_new_string",
FindAndReplaceInvalidReplaceAll = "find_and_replace_invalid_replace_all",
FindAndReplaceOldStringNotFound = "find_and_replace_old_string_not_found",
FindAndReplaceMultipleOccurrences = "find_and_replace_multiple_occurrences",
FindAndReplaceMissingFilepath = "find_and_replace_missing_filepath",
@ -48,6 +49,6 @@ export enum ContinueErrorReason {
ParentDirectoryNotFound = "parent_directory_not_found",
// Other
Unspecified = "unspecified",
Unknown = "unknown",
Unspecified = "unspecified", // I.e. a known error but no specific code for it
Unknown = "unknown", // I.e. an unexpected error
}

318
docs/CONTRIBUTING.mdx Normal file
View file

@ -0,0 +1,318 @@
---
title: "Contributing to Continue Documentation"
sidebarTitle: "Docs Contributions"
description: "Welcome to the Continue documentation! We're excited that you want to contribute. This guide will help you get started with our documentation workflow and tools."
---
## 🚀 Quick Start
### Prerequisites
1. **Node.js** (v20 or higher)
2. **Git** for version control
3. **GitHub CLI** - Install from [cli.github.com](https://cli.github.com/)
### Setup Steps
1. **Fork and clone the repository**
```bash
# Fork the repository (this will also clone it locally)
gh repo fork continuedev/continue
cd continue/docs
```
2. **Install dependencies**
```bash
npm install
```
3. **Start the local development server**
```bash
npm run dev
```
Your docs will be available at `http://localhost:3000`
## 💬 Creating Discussions and Issues
Before creating any issues, we ask that you start with a GitHub Discussion. This helps us organize feedback and determine the best path forward.
### Starting a Discussion
<Steps>
<Step title="Go to GitHub Discussions">
Visit the [Continue GitHub Discussions](https://github.com/continuedev/continue/discussions) page.
</Step>
<Step title="Choose the right category">
Select the **Docs** category for documentation improvements, corrections, or suggestions.
</Step>
<Step title="Provide detailed information">
Include the following in your discussion:
- Clear description of the issue or suggestion
- Steps to reproduce (if applicable)
- Expected vs. actual behavior
- Screenshots or code examples when helpful
- Your environment (OS, IDE, Continue version)
</Step>
</Steps>
### Issue Escalation Process
<Info>
**Important**: All issues should start as discussions. The Continue team will determine if and when a discussion should be escalated to a GitHub issue.
</Info>
The Continue team will review discussions and may:
- Provide a solution or clarification directly in the discussion
- Ask for additional information or testing
- Convert the discussion to an issue if it requires code changes or is a confirmed bug
- Close the discussion if it's resolved or not actionable
### When Discussions Become Issues
A discussion will typically be converted to an issue when:
- A bug in the documentation is confirmed
- A new feature or significant documentation change is approved
- Community consensus supports the proposed change
- Technical implementation is required
## 🤖 AI-Powered Documentation with Continue
We strongly encourage using Continue's AI assistance to maintain consistency and quality in our documentation. Here are three ways to set this up:
### Option 1: Use the Pre-Built Documentation Agent (Recommended)
The easiest way to get started is using our pre-configured documentation agent:
<Steps>
<Step title="Install the agent from Continue Hub">
Visit [the Docs Assistant - Mintlify in the Hub](https://hub.continue.dev/continuedev/docs-mintlify) and click "Install" to add it to your Continue setup. This agent comes pre-configured with all our documentation standards.
<Info>
Learn more about Continue Agents in our [agent documentation](/guides/understanding-agents).
</Info>
</Step>
<Step title="Use the agent">
<Tabs>
<Tab title="Command Line">
```bash
# Install the Continue CLI if you haven't already
npm install -g @continuedev/cli
# Use the agent from the command line
cn "Create a new guide for using the Continue CLI with Linear" --config continuedev/docs-mintlify
```
</Tab>
<Tab title="IDE">
1. Open Continue in your IDE
2. Select the "Docs Assistant - Mintlify" agent from the model dropdown
3. Ask it to help you create or edit documentation
Example prompts:
- "Create a new guide for using the Continue CLI with Linear"
- "Update the getting-started guide with the new installation process"
- "Format this documentation according to Mintlify standards"
</Tab>
</Tabs>
</Step>
</Steps>
<Tip>
You can also remix this agent to customize it for your specific needs. Learn how to create your own remix in our [remix agent documentation](/hub/agents/create-an-agent#how-to-remix-an-agent).
</Tip>
### Option 2: Create Your Own Custom Agent
If you want more control or customization, you can create your own documentation agent:
<Steps>
<Step title="Create a new agent">
Follow our [agent creation guide](/hub/agents/create-an-agent) to set up your own agent.
</Step>
<Step title="Add the Continue Docs MCP">
Install from Continue Hub: https://hub.continue.dev/continuedev/continue-docs-mcp
This MCP provides context about Continue's documentation structure and standards.
</Step>
<Step title="Add Mintlify formatting rules">
Install from Continue Hub: https://hub.continue.dev/mintlify/technical-writing-rule
This rule ensures proper Mintlify component formatting.
</Step>
<Step title="Use your custom agent">
<Tabs>
<Tab title="Command Line">
```bash
# Install the Continue CLI if you haven't already
npm install -g @continuedev/cli
# Use your agent from the command line
cn --config your-org/your-agent-name "Create a new guide for API authentication"
```
</Tab>
<Tab title="IDE">
1. Open Continue in your IDE
2. Select your custom agent from the model dropdown
3. Ask it to help you create or edit documentation
Example prompts:
- "Help me format this documentation according to Mintlify standards"
- "Create a troubleshooting section for this feature"
</Tab>
</Tabs>
</Step>
</Steps>
## 📝 Documentation Standards
### Mintlify Component Guidelines
When using Mintlify components, follow these formatting rules:
#### Cards and Info Boxes
```mdx
<Card title="Best Practice" icon="lightbulb">
Always include blank lines and proper indentation:
- Use 2-space indentation
- Add blank lines after opening tags
- Format lists as bullet points
</Card>
```
#### Warning and Note Components
```mdx
<Warning>
Important information should be formatted clearly:
- Each point on its own line
- Consistent indentation
- Clear, concise language
</Warning>
```
### Writing Style
1. **Be concise**: Get to the point quickly
2. **Use examples**: Show, don't just tell
3. **Include code blocks**: Provide working examples
4. **Add visuals**: Screenshots and diagrams help understanding
5. **Test your changes**: Ensure all links and code examples work
<Warning>
If you are creating a new guide, please test the steps yourself to ensure accuracy.
</Warning>
## 🔧 Common Tasks
### Adding a New Guide
1. Create a new `.mdx` file in the guides directory
2. Add frontmatter:
```mdx
---
title: "Your Guide Title"
description: "Brief description of what this guide covers"
---
```
3. Use the Continue agent to help format your content
4. Update `docs.json` to include your new page in the navigation
<Tip>
We have both guides and cookbooks. Use guides for step-by-step instructions and cookbooks for creating agents for the CLI.
</Tip>
### Updating Existing Documentation
1. Use the Continue agent with prompts like:
- "Update the installation guide with the new npm package"
- "Add a troubleshooting section for connection issues"
2. The agent will maintain consistent formatting automatically
### Adding Code Examples
Use language-specific code blocks:
````mdx
```typescript
// Your TypeScript code here
const example = "Hello, Continue!";
```
````
## 🐛 Testing Your Changes
1. **Local preview**: In the docs directory, run `npm run dev` and check your changes
2. **Link validation**: Ensure all internal and external links work
3. **Format check**: Use the Continue agent to validate Mintlify formatting
4. **Build test**: Run `npm run build` to ensure no build errors
## 📤 Submitting Your Contribution
1. **Create a feature branch**
```bash
git checkout -b docs/your-feature-name
```
2. **Commit your changes**
```bash
git add .
git commit -m "docs: describe your changes"
```
3. **Push and create a Pull Request**
```bash
# Push to your fork and create a PR
git push origin docs/your-feature-name
gh pr create --web
```
<Tip>
The `gh pr create` command will automatically:
- Push your branch to your fork
- Create a pull request to the main repository
- Allow you to add a title, description, and reference issues
- Open the PR in your browser if using `--web`
</Tip>
## 💡 Tips for Success
- **Use the Continue agent**: It knows our documentation standards and will save you time
- **Preview frequently**: Check your changes in the local dev server
- **Ask questions**: Open an issue or discussion if you need clarification
- **Small PRs are better**: Focus on one topic or fix per PR
- **Update examples**: Ensure code examples reflect the latest API
## 🆘 Getting Help
- **Start a Discussion**: Use [GitHub Discussions](https://github.com/continuedev/continue/discussions) for documentation issues, suggestions, or questions
- **Continue agent questions**: Check the [Continue Hub page](https://hub.continue.dev/continuedev/docs-mintlify)
- **Discord community**: Join our Discord for real-time help
- **Existing docs**: Review similar pages for formatting examples
---
Thank you for contributing to Continue! Your efforts help make our documentation better for everyone. To learn more about contibuting to other parts of the project, check out our [main CONTRIBUTING guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md) 🎉

4
docs/cli/guides.mdx Normal file
View file

@ -0,0 +1,4 @@
---
title: "Guides"
url: "/guides/overview#mcp-integration-cookbooks"
---

View file

@ -15,4 +15,28 @@ By implementing rules, you transform the AI from a generic coding agent into a k
Your agent detects rules and applies the specified rules while in [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) modes.
## Where to Manage Rules
<Columns cols={2}>
<Card title="Local Rules (.continue/rules)" icon="folder">
- Create files in `.continue/rules` folder
- Automatically appear with Hub assistants
- Edit directly in your file system
- Version controlled alongside your code
- Best for project-specific rules (e.g., "remember to generate migrations after modifying the db")
</Card>
<Card title="Hub Rules" icon="cloud">
- Manage on [Continue Hub](https://hub.continue.dev)
- Reference in config.yaml with `uses:`
- Share with team and community
- Easy to include in multiple agents
- Best for organization-wide rules (e.g., "always use X library for Y task")
</Card>
</Columns>
<Info>
**Quick Setup**: Start with local rules for immediate use, then promote commonly used rules to the Hub for sharing and reuse.
</Info>
Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details.

View file

@ -0,0 +1,190 @@
---
title: Settings
description: Configure Continue through VS Code's streamlined settings interface
---
<img
src="/images/continue-settings-card-layout.png"
alt="Continue Settings Panel - Card-based Layout"
/>
The new settings experience introduces a **card-based layout** that reduces visual clutter while maintaining powerful functionality. Every setting is more discoverable and easier to modify, whether you're on an ultrawide monitor or a small laptop screen.
## Quick Access
<CardGroup cols={3}>
<Card title="Settings Icon" icon="gear">
Click the gear in the Continue sidebar
</Card>
<Card title="VS Code Settings" icon="sliders">
File → Preferences → Settings → Extensions → Continue
</Card>
<Card title="Config File" icon="code">
Edit `config.yml` directly for advanced options
</Card>
</CardGroup>
<Tip>
Use the toolbar buttons for quick access to specific settings: - **Rules**
(pencil icon) - Custom coding preferences - **Tools** (wrench icon) - Manage
integrations - **Models** (cube icon) - Configure AI providers
</Tip>
## Core Settings
<Tabs>
<Tab title="Interface">
<AccordionGroup>
<Accordion title="Display Options" icon="display">
| Setting | Description |
|---------|-------------|
| Session Tabs | Manage multiple chat sessions |
| Code Wrapping | Auto-wrap long code lines |
| Markdown Display | Show raw markdown vs rendered |
| Chat Scrollbar | Toggle scrollbar visibility |
</Accordion>
<Accordion title="Behavior" icon="wand-magic-sparkles">
| Setting | Description |
|---------|-------------|
| Auto-accept Diffs | Apply code changes automatically |
| Tool Rejection | Continue after tool rejection |
| Auto-naming | Generate session titles automatically |
</Accordion>
</AccordionGroup>
</Tab>
<Tab title="Autocomplete">
Configure code completions:
<img
src="/images/autocomplete-settings.png"
alt="Continue Autocomplete Settings"
/>
<Note>
Autocomplete models need to be added to your agent to enable selecting an autocomplete model. If none is available, you will be linked to the docs showing recommended models. See our [model recommendations](/customize/model-roles/autocomplete) for the best autocomplete models.
</Note>
<img
src="/images/autocomplete-model-selection.png"
alt="Autocomplete Model Selection"
/>
<Info>
To better understand how to set up agents and models, see our [Understanding Agents guide](/guides/understanding-agents).
</Info>
</Tab>
<Tab title="Indexing">
Control how Continue understands your codebase:
<img
src="/images/indexing-settings.png"
alt="Continue Indexing Settings"
/>
<Steps>
<Step title="Enable Indexing">
Toggle codebase indexing in the settings panel
</Step>
<Step title="Monitor Progress">
Watch real-time status in the UI
</Step>
<Step title="Verify Coverage">
Check which files are indexed via the status indicator
</Step>
</Steps>
<Note>
Indexing enables Continue to understand your entire codebase structure, significantly improving context awareness and suggestions.
</Note>
</Tab>
<Tab title="Experimental">
<Warning>
These features are in beta and may change or have stability issues.
</Warning>
| Feature | Purpose |
|---------|---------|
| Add Current File by Default | The currently open file is added as context in every new conversation |
| Enable experimental tools | Enables access to experimental tools that are still in development |
| Only use system message tools | Continue will not attempt to use native tool calling and will only use system message tools |
| @Codebase: use tool calling only | @codebase context provider will only use tool calling for code retrieval |
| Stream after tool rejection | Streaming will continue after the tool call is rejected |
</Tab>
</Tabs>
## Model & Assistant Selection
<img
src="/images/assistant-selector-dropdown.png"
alt="New assistant dropdown with cleaner icons and improved organization display"
/>
The refined assistant selector features:
- **Organization badges** for easy provider identification
- **Smart error handling** that sorts problematic configurations while keeping them selectable
- **Keyboard navigation** for quick model switching
## Privacy & Data
<CardGroup cols={3}>
<Card title="Local Processing" icon="lock">
All code analysis happens locally unless explicitly shared
</Card>
<Card title="Telemetry Control" icon="chart-line">
Opt in/out of anonymous usage statistics
</Card>
<Card title="Session Management" icon="database">
Sessions auto-save and restore between IDE restarts
</Card>
</CardGroup>
## Troubleshooting
<AccordionGroup>
<Accordion title="Model Connection Issues" icon="plug">
- Verify API keys in `config.yml` - Check network connectivity - Confirm
endpoint URLs are correct
</Accordion>
<Accordion title="Tool Loading Failures" icon="wrench">
- Review MCP server configurations - Check tool permissions - Verify tool
dependencies are installed
</Accordion>
<Accordion title="Indexing Problems" icon="magnifying-glass">
- Check file permissions
- Review `.gitignore` patterns
- Verify sufficient disk space
</Accordion>
</AccordionGroup>
<Info>
Still having issues? Check our comprehensive [troubleshooting
guide](/troubleshooting) or visit the [FAQs](/faqs) for more solutions.
</Info>
## Next Steps
<CardGroup cols={2}>
<Card title="Configure Models" icon="robot" href="/customization/models">
Set up your AI providers
</Card>
<Card title="Add Tools" icon="wrench" href="/customization/mcp-tools">
Extend Continue with MCP tools
</Card>
<Card title="Custom Rules" icon="pencil" href="/customization/rules">
Define coding preferences
</Card>
<Card title="Prompts" icon="message" href="/customization/prompts">
Customize AI behavior
</Card>
</CardGroup>

View file

@ -30,8 +30,8 @@ explore available MCP server blocks
Below is a quick example of setting up a new MCP server for use in your agent:
1. Create a folder called `.continue/mcpServers` at the top level of your workspace
2. Add a file called `playwright-mcp.yaml` to this folder.
3. Write the following contents to `playwright-mcp.yaml` and save.
2. Add a file called `playwright-mcp.yaml` to this folder
3. Write the following contents and save
```yaml title=".continue/mcpServers/playwright-mcp.yaml"
name: Playwright mcpServer
@ -60,6 +60,14 @@ You can set up an MCP server to search the Continue documentation directly from
For complete setup instructions, troubleshooting, and usage examples, see the [Continue MCP Reference](/reference/continue-mcp).
## Using JSON MCP Format from Claude, Cursor, Cline, etc
<Info>
If you're coming from another tool that uses JSON MCP format configuration files (like Claude Desktop, Cursor, or Cline), you can copy those JSON config files directly into your `.continue/mcpServers/` directory (note the plural "Servers") and Continue will automatically pick them up.
For example, place your JSON MCP config file at `.continue/mcpServers/mcp.json` in your workspace.
</Info>
## How to Configure MCP Servers
To set up your own MCP server, read the [MCP
@ -68,38 +76,21 @@ quickstart](https://modelcontextprotocol.io/quickstart) and then [create an
block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add a local MCP
server block to your [config file](./configuration.md):
<Tabs>
<Tab title="YAML">
```yaml title="config.yaml"
mcpServers:
- name: SQLite MCP
command: npx
args:
- "-y"
- "mcp-sqlite"
- "/path/to/your/database.db"
```yaml title="config.yaml"
# ...
mcpServers:
- name: SQLite MCP
command: npx
args:
- "-y"
- "mcp-sqlite"
- "/path/to/your/database.db"
# ...
```
````
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"experimental": {
"modelContextProtocolServers": [
{
"transport": {
"type": "stdio",
"command": "uvx",
"args": ["mcp-server-sqlite", "--db-path", "/path/to/your/database.db"]
}
}
]
}
}
````
</Tab>
</Tabs>
<Note>
When creating a standalone block file in `.continue/mcpServers/`, remember to include the required metadata fields (`name`, `version`, `schema`) as shown in the Quick Start example above.
</Note>
### How to Configure MCP Server Properties
@ -120,10 +111,12 @@ MCP now supports remote server connections through HTTP-based transports, expand
For real-time streaming communication, use the SSE transport:
```yaml
# ...
mcpServers:
- name: Name
type: sse
url: https://....
# ...
```
#### How to Use Standard Input/Output (`stdio`)
@ -131,6 +124,7 @@ mcpServers:
For local MCP servers that communicate via standard input and output:
```yaml
# ...
mcpServers:
- name: Name
type: stdio
@ -138,6 +132,7 @@ mcpServers:
args:
- "@modelcontextprotocol/server-sqlite"
- "/path/to/your/database.db"
# ...
```
#### How to Use Streamable HTTP Transport
@ -145,10 +140,12 @@ mcpServers:
For standard HTTP-based communication with streaming capabilities:
```yaml
# ...
mcpServers:
- name: Name
type: streamable-http
url: https://....
# ...
```
These remote transport options allow you to connect to MCP servers hosted on remote infrastructure, enabling more flexible deployment architectures and shared server resources across multiple clients.
@ -161,6 +158,7 @@ With some MCP servers you will need to use API keys or other secrets. You can le
as well as access hosted secrets in the Continue Hub. To leverage Hub secrets, you can use the `inputs` property in your MCP env block instead of `secrets`.
```yaml
# ...
mcpServers:
- name: Supabase MCP
command: npx
@ -178,4 +176,5 @@ mcpServers:
- "@modelcontextprotocol/server-github"
env:
GITHUB_PERSONAL_ACCESS_TOKEN: ${{ secrets.GITHUB_PERSONAL_ACCESS_TOKEN }}
# ...
```

View file

@ -20,6 +20,42 @@ You can view the current rules by clicking the pen icon above the main toolbar:
To form the system message, rules are joined with new lines, in the order they appear in the toolbar. This includes the base chat system message ([see below](#how-to-customize-chat-system-message)).
## Understanding Hub vs Local Rules Integration
<Warning>
**Important:** Rules created in different locations behave differently and have different synchronization patterns.
</Warning>
Continue supports two types of rules with different behaviors:
<Columns cols={2}>
<Card title="Local Rules" icon="folder">
- **Location**: `.continue/rules` folder in your workspace
- **Visibility**: Automatically visible when using Hub assistants
- **Creation**: Add rules button in VSCode or manual file creation
- **File Management**: Creates actual `.md` files you can edit directly
</Card>
<Card title="Hub Rules" icon="cloud">
- **Location**: Stored on Continue Hub, referenced in config.yaml
- **Visibility**: Only appear when referenced in assistant configuration
- **Creation**: Created directly on Hub or copied from local rules
- **File Management**: No local files created, managed through Hub interface
</Card>
</Columns>
### How Rules Are Applied
When using Continue, rules are loaded in this order:
1. **Hub assistant rules** (if using a Hub-based assistant)
2. **Referenced Hub rules** (via `uses:` in config.yaml)
3. **Local workspace rules** (from `.continue/rules` folder)
4. **Global rules** (from `~/.continue/rules` folder)
<Info>
**TL;DR**: Local rules show up automatically when using Hub assistants. Hub rules show up automatically when referenced in your config.
</Info>
## Quick Start: How to Create Your First Rule File
Below is a quick example of setting up a new rule file:
@ -42,6 +78,8 @@ Now test your rules by asking a question about a file in chat.
## How to Create Rules Blocks
### Creating Local Rules
Rules can be added locally using the "Add Rules" button while viewing the Local Agent's rules.
![add local rules button](/images/add-local-rules.png)
@ -50,12 +88,44 @@ Rules can be added locally using the "Add Rules" button while viewing the Local
**Automatically create local rule blocks**: When in Agent mode, you can prompt the agent to create a rule for you using the `create_rule_block` tool if enabled.
For example, you can say "Create a rule for this", and a rule will be created for you in `.continue/rules` based on your conversation.
</Info>
Rules can also be added to an Agent on the Continue Hub.
### Creating Hub Rules
Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub.
Rules can also be created and managed on the Continue Hub:
1. **Browse existing rules**: [Explore available rules](https://hub.continue.dev)
2. **Create new rules**: [Create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub
3. **Copy from local rules**: Copy/paste content from your `.continue/rules` files to create Hub rules
### Working Between Hub and Local Rules
<Tabs>
<Tab title="Hub to VSCode">
To use Hub rules in your local setup:
1. Reference them in your `config.yaml`:
```yaml
rules:
- uses: username/my-hub-rule
```
2. The rule will automatically appear in your rules toolbar
3. **Note**: No local file is created - the rule exists only on the Hub
</Tab>
<Tab title="VSCode to Hub">
To move local rules to the Hub:
1. Copy the content from your `.continue/rules/rule-name.md` file
2. Go to [Create new rule](https://hub.continue.dev/new?type=block&blockType=rules)
3. Paste the content and configure the rule
4. Optionally, remove the local file and reference the Hub rule in your config
<Warning>
**Current Limitation**: There's no automatic sync from local to Hub. You must manually copy/paste rule content.
</Warning>
</Tab>
</Tabs>
### How to Configure Rule Properties and Syntax
@ -150,6 +220,42 @@ globs: ["**/*.ts", "**/*.tsx"]
- modularize components into smaller, reusable pieces
```
## Troubleshooting Rules
### Issue: Rules Created in Different Places Don't Sync
**Problem**: You created rules in the Hub but don't see them in VSCode, or vice versa.
**Solution**:
- **Hub rules** only appear when referenced in your config.yaml using the `uses:` syntax
- **Local rules** automatically appear when using Hub assistants
- There's currently no automatic bidirectional sync
### Issue: "Edit" Links Point to Wrong Location
**Problem**: When you click "Edit" on a rule in VSCode, it tries to open the Hub even though the rule is local, or shows an incorrect URL.
**Root Cause**: This happens when you have a mix of local and Hub rules, and Continue can't properly determine where each rule originates.
**Workaround**:
1. **For local rules**: Navigate directly to `.continue/rules/` folder and edit the `.md` file
2. **For Hub rules**: Go directly to your assistant page on [Continue Hub](https://hub.continue.dev) and edit from there
3. Keep track of which rules are local vs Hub-based to avoid confusion
<Info>
**Known Issue**: This link accuracy problem is tracked in [Linear issue CON-3084](https://linear.app/continue/issue/CON-3084) and will be fixed in a future update.
</Info>
### Issue: Rules Don't Appear in Assistant
**Problem**: Your rules exist but don't show up in the rules toolbar.
**Check These**:
1. **File location**: Ensure local rules are in `.continue/rules/` (not `.continue/rule/`)
2. **File format**: Rules should be `.md` files with proper YAML frontmatter
3. **Config reference**: Hub rules must be referenced in `config.yaml`
4. **Assistant type**: Ensure you're using the correct assistant (local vs Hub)
### How to Customize Chat System Message
Continue includes a simple default system message for [Agent](../../features/agent/quick-start) and [Chat](../../features/chat/quick-start) requests, to help the model provide reliable codeblock formats in its output.

View file

@ -1,18 +1,34 @@
---
title: "AskSage"
description: "Configure AskSage with Continue to access a wide range of models including government-compliant versions of GPT and Claude models, supporting chat and edit functionalities"
title: "Ask Sage"
slug: ../asksage
---
<Tip>
**Discover Ask Sage models [here](https://hub.continue.dev/?q=Ask%20Sage)**
</Tip>
<Info>
To get an Ask Sage API key login to the Ask Sage platform (If you don't have
an account, you can create one [here](https://chat.asksage.ai/)) and follow
the instructions in the Ask Sage Docs: [Ask Sage API
Key](https://docs.asksage.ai/docs/api-documentation/api-documentation.html)
You can get an API key from the [Ask Sage](https://www.asksage.ai/).
</Info>
## Configuration
To use the Ask Sage models, you can use the following
## Overview
Ask Sage provides secure, government-compliant access to LLMs. This guide explains how to set up and configure Ask Sage models, including support for DoD certificates.
## 1. Prerequisites
- **Ask Sage Account:**
Sign up or log in at [Ask Sage Platform](https://chat.asksage.ai/).
- **API Key:**
Follow the [API Key Documentation](https://docs.asksage.ai/docs/api-documentation/api-documentation.html) to generate your key.
## 2. Configuration
Add your Ask Sage model to your Continue configuration file.
<Tabs>
<Tab title="YAML">
@ -42,53 +58,66 @@ To use the Ask Sage models, you can use the following
</Tab>
</Tabs>
The `apiBase` will be listed on the Ask Sage platform when you generate an `API key`. You will see context as shown below:
## 3. Using DoD Certificates
> Server API for query/training etc.:
>
> - Documentation: https://app.swaggerhub.com/apis-docs/NICOLASCHAILLAN_1/server_ask-sage_api/1.0
> - URL for this API is: https://api.asksage.ai/server/
For secure environments, specify your DoD CA bundle path:
## Usage
Currently, the setup for the models provided by Ask Sage is to support the following two functionalities provided by Continue.Dev:
<Tabs>
<Tab title="YAML">
```yaml title="config.yaml"
models:
- name: GPT-4 gov
provider: askSage
model: gpt4-gov
apiBase: https://api.asksage.ai/server/
apiKey: <YOUR_ASK_SAGE_API_KEY>
requestOptions:
caBundlePath: /path/to/dod/certificates
```
</Tab>
<Tab title="JSON">
```json title="config.json"
{
"models": [
{
"title": "GPT-4 gov",
"provider": "askSage",
"model": "gpt4-gov",
"apiBase": "https://api.asksage.ai/server/",
"apiKey": "<YOUR_ASK_SAGE_API_KEY>",
"requestOptions": {
"caBundlePath": "/path/to/dod/certificates"
}
}
]
}
```
</Tab>
</Tabs>
- `Chat` to understand and iterate on code in the sidebar
- `Edit` to modify code without leaving your current file
Replace `/path/to/dod/certificates` with your actual CA bundle file path.
More models, functionalities and documentation will be added in the future for Ask Sage Integration.
---
> We recommend to utilize the `OpenAI` or `Anthropic` models for the best performance and results for the `Chat` and `Edit` functionalities.
## 4. Final Steps
## Ask Sage Documentation
- Save your configuration file.
- Restart Continue to apply changes.
Ask Sage documentation is not available with Continue.Dev, so if you have any questions or need help with Ask Sage type `@ask` and select the `Ask Sage` option in the chat. Then procced to ask your question about Ask Sage.
Your Ask Sage model will now be available in Continue.
## Current Models From Ask Sage Supported
## 5. Usage
The current Models available provided by Ask Sage are:
Supported features:
- **Chat:** Interact and iterate on code in the sidebar.
- **Edit:** Modify code in place.
## 6. Support
- Refer to [Ask Sage Docs](https://docs.asksage.ai/docs/api-documentation/api-documentation.html) for more details.
- Email the Ask Sage support team for assistance at support@asksage.ai.
---
| Index | Model | Added |
| ----- | --------------------- | ----- |
| 1 | GPT-4 Gov | ✅ |
| 2 | GPT-4o Gov | ✅ |
| 3 | GPT-4o-mini Gov | ✅ |
| 4 | GPT-3.5-Turbo Gov | ✅ |
| 5 | GPT-4o | ✅ |
| 6 | GPT-4o-mini | ✅ |
| 7 | GPT-4 | ✅ |
| 8 | GPT-4-32K | ✅ |
| 9 | GPT-o1 | ✅ |
| 10 | GPT-o1-mini | ✅ |
| 10 | GPT-o3-mini | ✅ |
| 11 | GPT-3.5-turbo | ✅ |
| 12 | Claude 3.5 Sonnet Gov | ✅ |
| 13 | Claude 3 Opus | ✅ |
| 14 | Claude 3 Sonet | ✅ |
| 15 | Claude 3.5 Sonnet | ✅ |
| 16 | Grok (xAI) | ✅ |
| 17 | Groq Llama 3.3 | ✅ |
| 18 | Groq 70B | ✅ |
| 19 | Gemini Pro | ✅ |
| 20 | llama 3 | ✅ |
| 21 | Mistral Large | ✅ |

View file

@ -90,7 +90,7 @@ If you are using an OpenAI API compatible providers, you can change the `apiBase
### How to Force Legacy Completions Endpoint Usage
To force usage of `chat/completions` instead of `completions` endpoint you can set:
To force usage of `completions` instead of `chat/completions` endpoint you can set:
<Tabs>
<Tab title="YAML">

View file

@ -2,6 +2,10 @@
"$schema": "https://mintlify.com/docs.json",
"theme": "mint",
"name": "Continue",
"banner": {
"content": "Continue CLI v1.4.49 is live 🚀 Learn how you can [leverage the CLI with our MCP Cookbooks](/guides/overview#mcp-integration-cookbooks)",
"dismissable": true
},
"colors": {
"primary": "#6b7280",
"light": "#ffffff",
@ -26,7 +30,12 @@
{
"group": "CLI",
"icon": "terminal",
"pages": ["cli/overview", "cli/install", "cli/quick-start"]
"pages": [
"cli/overview",
"cli/install",
"cli/quick-start",
"cli/guides"
]
},
{
"group": "Features",
@ -88,13 +97,14 @@
"customization/models",
"customization/mcp-tools",
"customization/rules",
"customization/prompts"
"customization/prompts",
"customization/settings"
]
},
{
"group": "Help",
"icon": "book-open",
"pages": ["faqs", "troubleshooting"]
"pages": ["faqs", "troubleshooting", "CONTRIBUTING"]
}
]
},
@ -129,6 +139,7 @@
{
"group": "More Providers",
"pages": [
"customize/model-providers/more/asksage",
"customize/model-providers/more/deepseek",
"customize/model-providers/more/deepinfra",
"customize/model-providers/more/groq",
@ -185,7 +196,7 @@
"pages": [
"hub/introduction",
{
"group": "agents",
"group": "Agents",
"icon": "robot",
"pages": [
"hub/agents/intro",
@ -221,6 +232,11 @@
"hub/secrets/secret-resolution"
]
},
{
"group": "Workflows",
"icon": "cloud",
"pages": ["hub/workflows/intro"]
},
"hub/sharing",
"hub/source-control"
]
@ -246,7 +262,8 @@
"guides/instinct",
"guides/running-continue-without-internet",
"guides/custom-code-rag",
"guides/how-to-self-host-a-model"
"guides/how-to-self-host-a-model",
"guides/notion-continue-guide"
]
},
{
@ -254,8 +271,14 @@
"icon": "book-open-cover",
"pages": [
"guides/posthog-github-continuous-ai",
"guides/continue-docs-mcp-cookbook",
"guides/github-mcp-continue-cookbook",
"guides/sanity-mcp-continue-cookbook",
"guides/sentry-mcp-error-monitoring",
"guides/snyk-mcp-continue-cookbook",
"guides/netlify-mcp-continuous-deployment"
"guides/dlt-mcp-continue-cookbook",
"guides/netlify-mcp-continuous-deployment",
"guides/chrome-devtools-mcp-performance"
]
}
]
@ -317,7 +340,7 @@
"navbar": {
"links": [
{
"label": "Explore",
"label": "🚀 Get Started",
"href": "https://hub.continue.dev/"
}
],

View file

@ -0,0 +1,798 @@
---
title: "Chrome DevTools Performance Optimization Cookbook"
description: "Measure and optimize web performance with Chrome DevTools MCP, automated performance traces, and Core Web Vitals monitoring using Continue."
sidebarTitle: "Chrome DevTools MCP for Performance"
---
<Card title="Debug Performance Like a Pro" icon="gauge-high">
Use AI to automatically trace performance, analyze Core Web Vitals, diagnose bottlenecks, and get actionable optimization suggestions directly from Chrome DevTools
</Card>
<Info>
**Did You Know?** Chrome DevTools MCP brings the full power of browser debugging to your AI workflow:
- [Performance Traces](https://developer.chrome.com/docs/devtools/performance) with automated analysis
- [Network Request Monitoring](https://developer.chrome.com/docs/devtools/network) for bottleneck detection
- [Console Debugging](https://developer.chrome.com/docs/devtools/console) with error pattern recognition
- [CPU & Network Throttling](https://developer.chrome.com/docs/devtools/performance/reference#throttling) to simulate real-world conditions
- [Performance Insights](https://developer.chrome.com/docs/devtools/performance-insights) with AI-powered analysis
- [Screenshot Debugging](https://developer.chrome.com/docs/devtools/device-mode) for visual regression detection
This guide shows you how to leverage these features through natural language with Continue CLI!
</Info>
## What You'll Learn
This cookbook teaches you to:
- Run automated [performance traces](https://developer.chrome.com/docs/devtools/performance) to capture runtime metrics
- Analyze [Core Web Vitals](https://web.dev/vitals/) (LCP, FID, CLS, INP) and performance insights
- Diagnose performance bottlenecks using network and console analysis
- Test performance under different network and CPU conditions with [throttling](https://developer.chrome.com/docs/devtools/performance/reference#throttling)
- Automate visual regression testing with [screenshots](https://developer.chrome.com/docs/devtools/device-mode)
## Prerequisites
- Chrome browser installed
- Web project with a running development server (or deployed URL)
- Node.js 20+ installed
- [Continue CLI](https://docs.continue.dev/guides/cli) (`npm i -g @continuedev/cli`)
- [Chrome DevTools MCP](https://hub.continue.dev) configured
## Quick Setup
For all options, first:
<Steps>
<Step title="Install Continue CLI">
```bash
npm i -g @continuedev/cli
```
</Step>
</Steps>
## Chrome DevTools MCP Workflow Options
<Card title="Fastest Path to Success" icon="rocket">
Skip the manual setup and use our pre-built Chrome DevTools agent that includes
optimized prompts, rules, and the Chrome DevTools MCP for more consistent results.
</Card>
After completing **Quick Setup** above, you have two paths to get started:
<Tabs>
<Tab title="⚡ Quick Start (Recommended)">
**Perfect for:** Immediate results with optimized prompts and built-in performance analysis
<Steps>
<Step title="Add the Pre-Built Agent">
Visit the [Chrome DevTools Continuous Agent](https://hub.continue.dev/continuedev/chrome-dev-continuous) on Continue Hub and click **"Install Agent"** or run:
```bash
cn --config continuedev/chrome-dev-continuous
```
This agent includes:
- **Optimized prompts** for performance analysis and debugging
- **Built-in rules** for consistent formatting and error handling
- **[Chrome DevTools MCP](https://hub.continue.dev/google/chrome-devtools-mcp)** for reliable browser automation
</Step>
<Step title="Run Performance Analysis">
In the TUI that opens, type:
```
Analyze performance of http://localhost:3000 and provide optimization recommendations
```
That's it! The agent handles Chrome automation automatically.
</Step>
</Steps>
<Info>
**Why Use the Agent?** Results are more consistent and debugging is easier thanks to the Chrome DevTools MCP integration and pre-tested prompts.
</Info>
</Tab>
<Tab title="🛠️ Manual Setup">
<Steps>
<Step title="Add Chrome DevTools MCP to Your Assistant">
Visit the [Chrome DevTools MCP](https://hub.continue.dev/google/chrome-devtools-mcp) on Continue Hub and add it to your assistant, or add this to your configuration:
```yaml
name: Chrome DevTools MCP
version: 0.0.1
schema: v1
mcpServers:
- name: Chrome DevTools MCP
command: npx
args:
- chrome-devtools-mcp@latest
```
The MCP will automatically launch Chrome and connect to DevTools when needed.
</Step>
<Step title="Verify Setup">
Test the connection:
**TUI Mode Prompt:**
```
Open web.dev and take a screenshot
```
</Step>
<Step title="Run Performance Analysis">
Navigate to your project directory:
**TUI Mode Prompt:**
```
Navigate to http://localhost:3000 and record a performance trace. Analyze LCP, FID, and CLS.
```
</Step>
</Steps>
<Info>
**Manual Setup**: While you can configure the MCP manually, the pre-built agent provides optimized prompts and better error handling for performance analysis workflows.
</Info>
</Tab>
</Tabs>
<Accordion title="Agent Requirements">
To use the pre-built agent, you need either:
- **Continue CLI Pro Plan** with the models add-on, OR
- **Your own API keys** added to Continue Hub secrets
- **Chrome browser** installed on your system
- **Node.js 20+** to run the MCP via npx
The agent will automatically detect and use your configuration.
</Accordion>
---
## Performance Measurement Workflows
The Chrome DevTools MCP enables natural language performance analysis. Here are workflows adapted from real-world use cases:
### Quick Performance Checks
<Card title="Verify Code Changes" icon="check">
**TUI Mode Prompt:**
```
Verify in the browser that your change works as expected.
```
</Card>
<Card title="Debug Broken Images" icon="image">
**TUI Mode Prompt:**
```
A few images on localhost:8080 are not loading. What's happening?
```
</Card>
<Card title="Debug Form Submission Issues" icon="rectangle-list">
**TUI Mode Prompt:**
```
Why does submitting the form fail after entering an email address?
```
</Card>
<Card title="Debug Layout Issues" icon="layer-group">
**TUI Mode Prompt:**
```
The page on localhost:8080 looks strange and off. Check what's happening there.
```
</Card>
<Card title="Performance Optimization" icon="gauge-high">
**TUI Mode Prompt:**
```
Localhost:8080 is loading slowly. Make it load faster.
```
</Card>
<Card title="Check Core Web Vitals" icon="chart-line">
**TUI Mode Prompt:**
```
Please check the LCP of web.dev.
```
</Card>
---
## Performance Analysis Recipes
Now you can use natural language prompts to analyze web performance. The Continue agent automatically calls the appropriate Chrome DevTools MCP tools.
<Info>
**Where to run these workflows:**
- **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs
- **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts
- **CLI (headless mode)**: Use `cn -p "your prompt"` for headless commands
**Test in Plan Mode First**: Before running performance measurements, test your prompts in plan mode (see the [Plan Mode Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes). This shows you what the agent will do without executing it.
</Info>
### Step 1: Baseline Performance Trace
Establish your current performance baseline:
**TUI Mode Prompt:**
```
Navigate to http://localhost:3000 and record a performance trace with page reload. Analyze the trace and show me the LCP, FID, CLS, and total blocking time.
```
<Info>
Chrome DevTools Performance Panel automatically tracks:
- **Core Web Vitals**: LCP, FID, CLS, INP
- **Loading Performance**: DOMContentLoaded, Load events, First Paint
- **Runtime Performance**: JavaScript execution time, layout shifts, paint events
- **Resource Usage**: Memory consumption, CPU utilization
</Info>
### Step 2: Analyze Performance Insights
Deep dive into specific performance issues:
**TUI Mode Prompt:**
```
Record a performance trace for http://localhost:3000 and analyze all Performance Insights. For each insight found, provide detailed information about:
- The specific issue (e.g., DocumentLatency, SlowCSS)
- Root cause analysis
- Affected resources or code
- Recommended optimizations
- Expected impact on Core Web Vitals
```
<Info>
**Performance Insights**: Chrome DevTools automatically detects common performance issues like:
- **Render Blocking Resources**: CSS and JavaScript that delay first paint
- **Layout Shifts**: Elements that move during page load
- **Long Tasks**: JavaScript execution blocking the main thread
- **Slow Network Requests**: Resources taking too long to load
- **Unused CSS/JavaScript**: Dead code increasing bundle size
</Info>
### Step 3: Network Performance Analysis
Identify slow network requests and optimization opportunities:
**TUI Mode Prompt:**
```
Navigate to https://my-site.com and:
1. List all network requests made during page load
2. Identify the 5 slowest requests and their sizes
3. Find any requests over 1MB
4. Detect render-blocking resources
5. Check for inefficient caching (missing cache headers)
6. Suggest specific optimizations for each issue found
```
### Step 4: Throttling Performance Tests
Test performance under real-world network and CPU conditions:
**TUI Mode Prompt:**
```
Test my site's performance under different conditions:
1. Navigate to http://localhost:3000
2. Emulate 4x CPU slowdown and Fast 3G network
3. Record a performance trace with reload
4. Analyze LCP and Total Blocking Time
5. Take a screenshot when page is fully loaded
Then repeat the test with:
- Slow 3G network + 6x CPU slowdown
- Offline network (to test service worker)
Compare results and identify which conditions cause the worst performance degradation."
```
<Info>
**Available Network Presets**:
- No throttling
- Fast 3G (1.6 Mbps down, 0.75 Mbps up)
- Slow 3G (400 Kbps down, 400 Kbps up)
- Offline
**CPU Throttling**: 4x, 6x, or custom slowdown to simulate low-end devices
</Info>
### Step 5: JavaScript Performance Analysis
Identify expensive JavaScript operations:
**TUI Mode Prompt:**
```
Record a performance trace for http://localhost:3000 and:
1. Identify all long tasks (>50ms) blocking the main thread
2. Find the specific JavaScript functions causing these tasks
3. Measure total JavaScript execution time
4. Detect unused JavaScript being loaded
5. Show the call stack for the longest task
6. Recommend code splitting or lazy loading opportunities"
```
## Automated Performance Monitoring
### Step 6: Core Web Vitals Dashboard
Create automated monitoring for Core Web Vitals:
**TUI Mode Prompt:**
```
Create a performance monitoring script that:
1. Opens my site at http://localhost:3000
2. Records a performance trace with reload
3. Extracts Core Web Vitals (LCP, FID, CLS, INP)
4. Checks console for JavaScript errors
5. Takes a screenshot
6. Saves results to performance-report.json with format:
{
'timestamp': 'ISO date',
'lcp': number,
'fid': number,
'cls': number,
'inp': number,
'errors': array,
'screenshot': 'path'
}
Save this as scripts/performance-monitor.js that I can run regularly"
```
### Step 7: Visual Regression Detection
Detect unintended visual changes:
**TUI Mode Prompt:**
```
Set up visual regression testing:
1. Navigate to http://localhost:3000
2. Take full-page screenshots at:
- Desktop viewport (1920x1080)
- Tablet viewport (768x1024)
- Mobile viewport (375x667)
3. Save screenshots to screenshots/baseline/
4. Create a script to compare future screenshots against baseline
5. Highlight any pixel differences over 5%
6. Generate a visual diff report"
```
### Step 8: Performance Budget Enforcement
Set and enforce performance budgets:
**TUI Mode Prompt:**
```
Create a performance budget checker that:
Requirements:
- LCP must be < 2.5 seconds
- FID must be < 100ms
- CLS must be < 0.1
- Total JavaScript < 300KB
- Total page size < 1MB
- No console errors
Implementation:
1. Navigate to http://localhost:3000
2. Record performance trace with reload
3. List all network requests and calculate total sizes
4. Check console messages for errors
5. Validate all metrics against budgets
6. Exit with code 1 if any budget is exceeded
7. Generate a detailed report showing pass/fail for each metric
Save as scripts/performance-budget.js for CI/CD integration"
```
## Continuous Performance Testing with GitHub Actions
This example demonstrates a **Continuous AI workflow** where performance validation runs automatically in your CI/CD pipeline using Chrome DevTools MCP in headless mode.
### Add GitHub Secrets
Navigate to **Repository Settings → Secrets and variables → Actions** and add:
- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys)
### Create Workflow File
This workflow automatically validates web performance on pull requests using the Continue CLI in headless mode. It records performance traces, extracts Core Web Vitals, and posts a summary report as a PR comment.
Create `.github/workflows/performance-check.yml` in your repository:
```yaml
name: Performance Check
on:
pull_request:
jobs:
performance:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install Dependencies
run: |
npm install -g @continuedev/cli
npm ci
- name: Build Project
run: npm run build
- name: Start Dev Server
run: |
npm run dev &
npx wait-on http://localhost:3000
- name: Run Performance Tests
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
run: |
cn --config continuedev/chrome-dev-continuous \
-p "Navigate to http://localhost:3000 and:
1. Record performance trace with reload
2. Extract LCP, FID, CLS values
3. List network requests and calculate total bundle size
4. Output results as JSON to performance.json" \
--auto
- name: Check Performance Budgets
run: |
node << 'EOF'
const fs = require('fs');
const perf = JSON.parse(fs.readFileSync('performance.json'));
const budgets = {
lcp: 2.5,
fid: 100,
cls: 0.1,
bundleSize: 300000
};
let failed = false;
const results = [];
if (perf.lcp > budgets.lcp) {
results.push(`❌ LCP: ${perf.lcp}s (budget: ${budgets.lcp}s)`);
failed = true;
} else {
results.push(`✅ LCP: ${perf.lcp}s`);
}
if (perf.fid > budgets.fid) {
results.push(`❌ FID: ${perf.fid}ms (budget: ${budgets.fid}ms)`);
failed = true;
} else {
results.push(`✅ FID: ${perf.fid}ms`);
}
if (perf.cls > budgets.cls) {
results.push(`❌ CLS: ${perf.cls} (budget: ${budgets.cls})`);
failed = true;
} else {
results.push(`✅ CLS: ${perf.cls}`);
}
if (perf.bundleSize > budgets.bundleSize) {
results.push(`❌ Bundle: ${perf.bundleSize}KB (budget: ${budgets.bundleSize}KB)`);
failed = true;
} else {
results.push(`✅ Bundle: ${perf.bundleSize}KB`);
}
console.log(results.join('\n'));
if (failed) {
process.exit(1);
}
EOF
- name: Comment Performance Results
if: always()
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const perf = JSON.parse(fs.readFileSync('performance.json'));
const comment = `## 📊 Performance Report
| Metric | Value | Budget | Status |
|--------|-------|--------|--------|
| LCP | ${perf.lcp}s | 2.5s | ${perf.lcp <= 2.5 ? '✅' : '❌'} |
| FID | ${perf.fid}ms | 100ms | ${perf.fid <= 100 ? '✅' : '❌'} |
| CLS | ${perf.cls} | 0.1 | ${perf.cls <= 0.1 ? '✅' : '❌'} |
| Bundle Size | ${perf.bundleSize}KB | 300KB | ${perf.bundleSize <= 300 ? '✅' : '❌'} |
${perf.lcp > 2.5 || perf.fid > 100 || perf.cls > 0.1 || perf.bundleSize > 300
? '⚠️ **Performance budgets exceeded. Please optimize before merging.**'
: '✅ **All performance budgets met!**'}`;
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: comment
});
```
<Info>
The Chrome DevTools MCP works in headless Chrome environments. Make sure your CI environment has Chrome installed (it's pre-installed on GitHub Actions ubuntu-latest runners).
</Info>
## Advanced Performance Workflows
### Step 9: Competitor Comparison
Compare your site's performance with competitors:
**TUI Mode Prompt:**
```
Compare performance between my site and competitors:
Sites to test:
- http://localhost:3000 (my site)
- https://competitor1.com
- https://competitor2.com
For each site:
1. Navigate to homepage
2. Record performance trace with reload
3. Extract LCP, FID, CLS, Total Blocking Time
4. List network requests and calculate total page size
5. Count JavaScript and CSS files
Create a comparison table showing:
- Site name
- All Core Web Vitals
- Total page size
- Number of requests
- Which site performs best for each metric
Provide specific recommendations for how my site can improve based on what competitors do better."
```
### Step 10: Performance Testing Across Routes
Test performance consistency across your entire site:
**TUI Mode Prompt:**
```
Test performance across all major routes:
Routes to test:
- / (homepage)
- /products
- /products/[id] (pick a sample product)
- /checkout
- /blog
For each route:
1. Navigate to the URL
2. Record performance trace
3. Extract LCP, Total Blocking Time, bundle size
4. Check console for errors
5. Take a screenshot
Generate a report showing:
- Which routes have the worst LCP
- Routes with the most JavaScript errors
- Bundle size variations across routes
- Recommendations for route-specific optimizations"
```
### Step 11: Mobile Performance Analysis
Focus on mobile-specific performance issues:
**TUI Mode Prompt:**
```
Analyze mobile performance for http://localhost:3000:
1. Resize viewport to mobile (375x667)
2. Emulate Slow 3G network + 4x CPU slowdown
3. Record performance trace with reload
4. Analyze Performance Insights for mobile-specific issues
5. Check for:
- Touch target sizes too small
- Horizontal scrolling issues
- Oversized images not optimized for mobile
- Excessive JavaScript on mobile
6. Take mobile screenshot
7. Provide mobile-specific optimization recommendations"
```
## Performance Troubleshooting
### Debug Performance Regressions
Quickly identify what caused a performance regression:
**TUI Mode Prompt:**
```
Debug performance regression on http://localhost:3000:
1. Record performance trace
2. Analyze all Performance Insights
3. List console errors and warnings
4. Check network requests for:
- Failed requests
- Slow requests (>1s)
- Large requests (>500KB)
5. Identify the top 3 performance bottlenecks
6. For each bottleneck, suggest:
- Root cause
- Specific code or resource causing it
- Step-by-step fix
- Expected performance improvement"
```
### Performance Issue Quick Reference
| Issue | Quick Fix Command (in cn TUI) |
| :---- | :---------------------------- |
| Slow LCP | `"Find render-blocking resources and suggest preloading or deferring"` |
| High CLS | `"Detect layout shifts and identify unsized images or dynamic content"` |
| Long Tasks | `"Find JavaScript tasks over 50ms and suggest code splitting"` |
| Large Bundles | `"List all JavaScript files, identify largest ones, suggest lazy loading"` |
| Slow Network | `"Find requests over 500KB and suggest compression or optimization"` |
| Console Errors | `"List all console errors and suggest fixes"` |
## What You've Built
After completing this guide, you have a complete **AI-powered performance analysis system** that:
- ✅ **Uses natural language** — Simple prompts instead of complex DevTools commands
- ✅ **Analyzes automatically** — AI interprets performance traces and suggests fixes
- ✅ **Runs continuously** — Automated validation in CI/CD pipelines
- ✅ **Ensures quality** — Performance checks prevent regressions from shipping
<Card title="Continuous AI" icon="rocket">
Your performance workflow now operates at **[Level 2 Continuous AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** - AI handles routine performance analysis and debugging with human oversight through review and approval of changes.
</Card>
## Chrome DevTools MCP Capabilities
<CardGroup cols={2}>
<Card title="Performance Tracing" icon="chart-line">
**Tools Available**
- `performance_start_trace`: Start recording with auto-reload
- `performance_stop_trace`: Stop and analyze trace
- `performance_analyze_insight`: Deep dive into specific issues
</Card>
<Card title="Network Debugging" icon="network-wired">
**Tools Available**
- `list_network_requests`: See all requests and sizes
- `get_network_request`: Inspect specific request details
- `emulate_network`: Test under various network conditions
</Card>
<Card title="Console Analysis" icon="terminal">
**Tools Available**
- `list_console_messages`: Get all console logs and errors
- `evaluate_script`: Run JavaScript in page context
- Automatic error pattern detection
</Card>
<Card title="Visual Testing" icon="camera">
**Tools Available**
- `take_screenshot`: Capture full or partial page
- `take_snapshot`: Get accessibility tree snapshot
- `resize_page`: Test responsive layouts
</Card>
</CardGroup>
## Performance Best Practices
Key metrics to monitor for optimal web performance:
<CardGroup cols={3}>
<Card title="Core Web Vitals" icon="gauge-high">
- LCP < 2.5s (good)
- FID < 100ms (good)
- CLS < 0.1 (good)
- INP < 200ms (good)
</Card>
<Card title="Loading Performance" icon="bolt">
- Total page size < 1MB
- JavaScript < 300KB
- Time to Interactive < 3.8s
- First Contentful Paint < 1.8s
</Card>
<Card title="Runtime Performance" icon="microchip">
- No long tasks > 50ms
- 60 FPS during interactions
- No memory leaks
- Efficient event listeners
</Card>
</CardGroup>
## Advanced Testing Scenarios
### A/B Test Performance Impact
**TUI Mode Prompt:**
```
Compare performance of two implementations:
1. Test variant A at http://localhost:3000?variant=A
2. Test variant B at http://localhost:3000?variant=B
Run each test 5 times and calculate average LCP, FID, CLS
Determine which variant has better performance and by how much
```
### Lighthouse Score Tracking
**TUI Mode Prompt:**
```
Create a script that runs daily performance audits:
1. Navigate to production site
2. Record performance trace
3. Calculate Lighthouse-style performance score based on:
- FCP (10%)
- SI (10%)
- LCP (25%)
- TTI (10%)
- TBT (30%)
- CLS (15%)
4. Track score over time in performance-history.json
5. Alert if score drops below 90
```
### Performance Regression Detection
**TUI Mode Prompt:**
```
Set up automated regression detection:
1. Record baseline performance for main branch
2. Save baseline metrics to baseline-perf.json
3. On each PR, run performance tests
4. Compare PR metrics with baseline
5. Flag regressions over 10% for any metric
6. Generate visual diff report with screenshots
```
## Next Steps
1. **Analyze your first site** - Try the baseline performance trace on your current project
2. **Debug bottlenecks** - Use the network analysis prompt to fix slow requests
3. **Set up CI pipeline** - Add the GitHub Actions workflow to your repo
4. **Test throttling** - Measure performance under real-world network conditions
5. **Monitor trends** - Track Core Web Vitals over time
## Additional Resources
<CardGroup cols={2}>
<Card title="Chrome DevTools MCP" icon="plug" href="https://github.com/ChromeDevTools/chrome-devtools-mcp">
Official Chrome DevTools MCP repository
</Card>
<Card title="Continue Hub" icon="circle-nodes" href="https://hub.continue.dev">
Explore more MCP integrations
</Card>
<Card title="DevTools Documentation" icon="book" href="https://developer.chrome.com/docs/devtools">
Complete Chrome DevTools documentation
</Card>
<Card title="Web Vitals Guide" icon="gauge-high" href="https://web.dev/vitals/">
Learn about Core Web Vitals
</Card>
</CardGroup>

View file

@ -0,0 +1,542 @@
---
title: "Contributing to Continue with Model Context Protocol (MCP)"
description: "Use the Continue Docs MCP to write cookbooks, guides, and documentation with AI-powered workflows."
sidebarTitle: "Continue Docs MCP Cookbook"
---
<Card title="What You'll Build" icon="book-open-cover">
Master using the Continue Docs MCP to contribute documentation, create cookbooks, and maintain consistency across Continue's docs - all through natural language prompts.
</Card>
## Prerequisites
Before starting, ensure you have:
- Continue account with **Hub access**
- Read: [Contributing to Continue Documentation](/CONTRIBUTING) for setup instructions
- Forked the [continuedev/continue](https://github.com/continuedev/continue) repository
- Node.js 20+ and Continue CLI installed
<Warning>
This cookbook assumes you've read the setup in the [CONTRIBUTING guide](/CONTRIBUTING). If you haven't, start there first.
</Warning>
## Continue Docs MCP Setup
<Card title="Fastest Path to Success" icon="rocket">
Use the pre-built [Docs Assistant - Mintlify agent](https://hub.continue.dev/continuedev/docs-mintlify) that includes the Continue Docs MCP and is ready to use immediately.
</Card>
<Tabs>
<Tab title="⚡ Quick Start (Recommended)">
```bash
# From your Continue docs directory
cn --config continuedev/docs-mintlify
```
This agent includes:
- **Continue Docs MCP** for searching Continue documentation
- **Mintlify formatting rules** for proper component usage
- **Documentation-focused prompts** for common tasks
</Tab>
<Tab title="🛠️ Custom Agent">
If you want to customize, create your own agent and add:
1. [Continue Docs MCP](https://hub.continue.dev/continuedev/continue-docs-mcp)
2. [Mintlify Technical Writing Rule](https://hub.continue.dev/mintlify/technical-writing-rule)
See the [CONTRIBUTING guide](/CONTRIBUTING#option-2-create-your-own-custom-agent) for details.
</Tab>
</Tabs>
---
## What is the Continue Docs MCP?
<Card title="Continue Docs MCP" icon="circle-info">
A Model Context Protocol server built with [Mintlify's MCP generation](https://www.mintlify.com/blog/generate-mcp-servers-for-your-docs) that enables semantic search across Continue documentation. [Learn more →](/reference/continue-mcp)
</Card>
The MCP helps you:
- **Find examples** from existing documentation
- **Maintain consistency** with established patterns
- **Source accurate information** about Continue features
- **Write better documentation** faster
---
## Documentation Workflows with Prompts
### 🆕 Creating a New Cookbook
Cookbooks show how to use Continue CLI with specific tools or services. Here's how to create one using the Continue Docs MCP:
<Steps>
<Step title="Research Existing Cookbooks">
```bash
cn --config continuedev/docs-mintlify
```
**Prompt:**
```
"Show me the structure of existing MCP cookbooks in the Continue docs.
I want to create a cookbook for GitHub MCP."
```
The agent will find examples like the dlt, Snyk, and Sanity cookbooks.
</Step>
<Step title="Source Official Documentation">
**Prompt:**
```
"Using the Continue Docs MCP, find information about how GitHub MCP works.
Then search the web for the official GitHub MCP documentation and combine
both sources to create a cookbook following the same structure as the
dlt cookbook."
```
The agent will:
- Search Continue docs for MCP patterns
- Fetch GitHub MCP official documentation
- Combine both sources
- Generate a cookbook with consistent formatting
</Step>
<Step title="Add to Navigation">
**Prompt:**
```
"Add my new github-mcp-continue-cookbook.mdx to the docs.json navigation
under the Cookbooks section."
```
</Step>
<Step title="Preview and Iterate">
```bash
npm run dev
# Visit http://localhost:3000
```
**Refine with prompts:**
```
"Add more examples to the troubleshooting section"
"Include a CI/CD workflow example using GitHub Actions"
"Add authentication setup using environment variables"
```
</Step>
</Steps>
<Info>
**Pro Tip:** The agent uses the Continue Docs MCP to maintain consistency with existing cookbooks automatically.
</Info>
---
### ✏️ Updating Existing Documentation
<Steps>
<Step title="Find the Documentation">
**Prompt:**
```
"Where is the MCP tools documentation located? Show me the file path."
```
</Step>
<Step title="Make Targeted Updates">
**Prompt:**
```
"Update the MCP tools documentation at docs/customization/mcp-tools.mdx
to include information about the new Slack MCP server. Use the Continue
Docs MCP to find examples of how other MCP servers are documented, then
add a similar section for Slack."
```
</Step>
</Steps>
---
### 📝 Adding New Guides
<Steps>
<Step title="Research Similar Content">
**Prompt:**
```
"I want to create a guide for setting up Continue with Amazon Bedrock.
Search the Continue docs for similar model provider setup guides and
show me the common structure they follow."
```
</Step>
<Step title="Create the Guide">
**Prompt:**
```
"Create a new guide at docs/guides/amazon-bedrock-setup.mdx following
the structure you found. Include:
- Prerequisites
- Step-by-step setup with code examples
- Configuration options
- Troubleshooting common issues
Use the Continue Docs MCP to find accurate information about Continue's
model provider configuration."
```
</Step>
<Step title="Add Navigation Entry">
**Prompt:**
```
"Add this guide to docs.json under the Model Providers section"
```
</Step>
</Steps>
---
## Real-World Cookbook Examples
### Example 1: PostgreSQL MCP Cookbook
**Prompt:**
```
"Create a cookbook for using Continue with PostgreSQL MCP. Follow the same
structure as the dlt cookbook, but customize it for database operations.
Include these sections:
1. Quick start with pre-built agent
2. Manual setup with MCP configuration
3. Common database tasks (schema exploration, query writing, migrations)
4. Troubleshooting database connection issues
Use the Continue Docs MCP to find MCP configuration patterns and search the
web for PostgreSQL MCP documentation."
```
### Example 2: Sentry Error Tracking Cookbook
**Prompt:**
```
"Create a cookbook showing how to use Continue to analyze Sentry errors.
The cookbook should demonstrate:
1. Setting up Sentry MCP integration
2. Querying recent errors
3. Analyzing error patterns with AI
4. Generating fixes for common errors
5. CI/CD integration for automated error analysis
Research the Snyk cookbook structure since it's also about error detection,
and adapt it for Sentry."
```
### Example 3: OpenAPI Documentation Cookbook
**Prompt:**
```
"I want to create a cookbook for using Continue to work with OpenAPI specs.
Show how to:
1. Load OpenAPI specs into Continue's context
2. Generate API client code from specs
3. Create tests based on API endpoints
4. Update documentation when APIs change
Use the Continue Docs MCP to find how context providers work, then combine
that with OpenAPI MCP information."
```
---
## Advanced Prompt Patterns
<CardGroup cols={2}>
<Card title="Multi-Source Research" icon="magnifying-glass">
```bash
"Use the Continue Docs MCP to understand how agents
work in Continue, then search the web for Anthropic's
Computer Use MCP. Create a cookbook showing how to
combine Continue agents with Computer Use for
automated testing."
```
</Card>
<Card title="Cross-Reference Documentation" icon="link">
```bash
"Find all mentions of MCP servers across Continue
documentation. Then create a comprehensive reference
page that links to all MCP-related guides and
configurations."
```
</Card>
<Card title="Consistency Checking" icon="check-double">
```bash
"Review all cookbook files in docs/guides/ and check
if they follow the same structure. List any
inconsistencies and suggest updates to make them
uniform."
```
</Card>
<Card title="Example Extraction" icon="code">
```bash
"Extract all code examples showing MCP server
configuration from the Continue docs. Format them
as a single reference page with explanations for
each pattern."
```
</Card>
</CardGroup>
---
## Testing Your Documentation
### Local Preview
```bash
cd docs
npm run dev
# Visit http://localhost:3000
```
### Validation Prompts
```bash
# Check formatting
"Review this documentation for Mintlify formatting issues and fix any problems"
# Verify links
"Check all links in this file and ensure they point to existing documentation"
# Test code examples
"Verify that all code examples in this cookbook are syntactically correct"
```
---
## Submitting Your Contribution
**Prompt:**
```bash
"Create a pull request with my documentation changes and use the repo's
PR template to write the description"
```
The agent will:
- Create a feature branch
- Stage and commit your changes
- Push to your fork
- Generate a PR description following the template
- Open the PR for review
<Info>
See the full [Contributing Guide](/CONTRIBUTING#submitting-your-contribution) for manual PR submission details.
</Info>
---
## Automated Documentation Checks with GitHub Actions
Add automated documentation checks to your PR workflow using the Continue Docs MCP agent:
```yaml title=".github/workflows/docs-check.yml"
name: Documentation Check
on:
pull_request:
types: [opened, synchronize]
paths:
- 'core/**'
- 'extensions/**'
- 'packages/**'
- 'gui/**'
jobs:
check-docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install Continue CLI
run: npm i -g @continuedev/cli
- name: Analyze Changes for Documentation Needs
id: analyze
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
run: |
echo "🔍 Analyzing code changes for documentation needs..."
# Get changed files
git diff origin/${{ github.base_ref }}..HEAD --name-only > changed_files.txt
# Create detailed diff
git diff origin/${{ github.base_ref }}..HEAD > changes.diff
# Use Continue agent to check if docs need updates
PROMPT="Review these code changes and determine if documentation updates are needed.
Changed files: $(cat changed_files.txt | tr '\n' ' ')
Consider:
- New features or APIs
- Breaking changes
- New configuration options
- Modified CLI commands
- New MCP integrations
If docs updates are needed, specify which files in docs/ should be updated.
If no updates needed, respond with 'NO_DOCS_NEEDED'.
Be specific and concise."
cn --config continuedev/docs-mintlify -p "$PROMPT" --auto > analysis.md || {
echo "⚠️ Analysis failed"
echo "needs_docs=false" >> $GITHUB_OUTPUT
exit 0
}
if grep -q "NO_DOCS_NEEDED" analysis.md; then
echo "needs_docs=false" >> $GITHUB_OUTPUT
else
echo "needs_docs=true" >> $GITHUB_OUTPUT
fi
- name: Post Documentation Recommendation
if: steps.analyze.outputs.needs_docs == 'true'
env:
GH_TOKEN: ${{ github.token }}
run: |
echo "📝 Creating PR comment with documentation recommendations..."
cat > pr-comment.md <<'EOF'
## 📚 Documentation Update Recommended
Based on the code changes in this PR, documentation updates may be needed:
EOF
cat analysis.md >> pr-comment.md
cat >> pr-comment.md <<'EOF'
---
### Next Steps
1. Review the suggested documentation areas above
2. Update relevant files in the `/docs` folder
3. Consider updating:
- API references for interface changes
- Guides for workflow changes
- Configuration docs for new settings
- MCP cookbooks for new integrations
### Resources
- [Contributing to Docs](/CONTRIBUTING)
- [Continue Docs MCP Cookbook](/guides/continue-docs-mcp-cookbook)
*This analysis was generated using the Continue Docs MCP agent.*
EOF
gh pr comment ${{ github.event.pull_request.number }} --body-file pr-comment.md
- name: Add Label
if: steps.analyze.outputs.needs_docs == 'true'
env:
GH_TOKEN: ${{ github.token }}
run: |
gh pr edit ${{ github.event.pull_request.number }} --add-label "docs-needed"
```
<Info>
This workflow uses the Continue Docs MCP agent to analyze code changes and automatically comment on PRs when documentation updates are recommended.
</Info>
---
## Documentation MCP for Other Projects
Want to create documentation MCPs for your own projects? Mintlify makes it easy:
<Steps>
<Step title="Set Up Mintlify Docs">
```bash
npm i -g mintlify
mintlify init
```
</Step>
<Step title="MCP Auto-Generated">
Mintlify automatically generates an MCP server for your documentation, enabling semantic search.
[Learn more about Mintlify MCP generation →](https://www.mintlify.com/blog/generate-mcp-servers-for-your-docs)
</Step>
<Step title="Publish to Continue Hub">
Share your docs MCP on [Continue Hub](https://hub.continue.dev/new?type=mcp) so others can use it with Continue agents.
</Step>
</Steps>
<Info>
The [Continue Docs MCP](/reference/continue-mcp) itself was built this way!
</Info>
---
## Key Prompts Cheat Sheet
| Task | Prompt |
|:-----|:-------|
| **Find structure** | "Show me the structure of existing cookbooks in Continue docs" |
| **Create cookbook** | "Create a cookbook for [tool] MCP following the dlt cookbook structure" |
| **Update docs** | "Update [file] to include information about [feature], using Continue Docs MCP to find examples" |
| **Add navigation** | "Add [file] to docs.json under the [section] section" |
| **Check consistency** | "Review this file for consistency with other Continue documentation" |
| **Fix formatting** | "Review for Mintlify formatting issues and fix any problems" |
| **Extract examples** | "Find all examples of [topic] in Continue docs" |
| **Research feature** | "Use Continue Docs MCP to explain how [feature] works in Continue" |
---
## Resources
### Continue Documentation
- [Contributing Guide](/CONTRIBUTING) - Setup and submission process
- [Continue Docs MCP Reference](/reference/continue-mcp) - MCP server details
- [Understanding Agents](/guides/understanding-agents) - How agents work
### Mintlify
- [MCP Generation Guide](https://www.mintlify.com/blog/generate-mcp-servers-for-your-docs)
- [Mintlify Documentation](https://mintlify.com/docs)
### Community
- [Continue Discord](https://discord.gg/continue) - #documentation channel
- [GitHub Discussions](https://github.com/continuedev/continue/discussions)
---
## Next Steps
<CardGroup cols={2}>
<Card title="Start Contributing" icon="code" href="/CONTRIBUTING">
Set up your environment
</Card>
<Card title="Use Docs Agent" icon="robot" href="https://hub.continue.dev/continuedev/docs-mintlify">
Install pre-built agent
</Card>
<Card title="Browse Cookbooks" icon="book-open" href="/guides/overview">
See cookbook examples
</Card>
<Card title="Join Discord" icon="discord" href="https://discord.gg/continue">
Get help from community
</Card>
</CardGroup>

View file

@ -0,0 +1,484 @@
---
title: "Building Data Pipelines with dlt MCP and Continue"
description: "Set up an AI-powered data engineering workflow that helps you develop, debug, and inspect dlt data pipelines using natural language commands."
sidebarTitle: "dlt Data Pipelines with Continue"
---
<Card title="What You'll Build" icon="database">
An AI-powered data pipeline development system that uses Continue's AI agent with dlt
MCP to inspect pipeline execution, retrieve schemas, analyze datasets, and debug load errors - all through simple natural language prompts
</Card>
## Prerequisites
Before starting, ensure you have:
- Continue account with **Hub access**
- Read: [Understanding Agents — How to get started with Hub agents](/guides/understanding-agents#how-to-get-started-with-hub-agents)
- Python 3.8+ installed locally
- A dlt pipeline project (or create one during this guide)
- Basic understanding of data pipelines
For all options, first:
<Steps>
<Step title="Install Continue CLI">
```bash
npm i -g @continuedev/cli
```
</Step>
<Step title="Install dlt">
```bash
pip install dlt
```
</Step>
</Steps>
<Warning>
To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys).
</Warning>
## dlt MCP Workflow Options
<Card title="🚀 Fastest Path to Success" icon="zap">
Skip the manual setup and use our pre-built [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant) that includes
the dlt MCP and optimized data pipeline workflows for more consistent results. You can [remix this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) to customize it for your specific needs.
</Card>
After ensuring you meet the **Prerequisites** above, you have two paths to get started:
<Tabs>
<Tab title="⚡ Quick Start (Recommended)">
<Steps>
<Step title="Load the Pre-Built Agent">
Navigate to your pipeline project directory and run:
```bash
cn --config dlthub/dlt-assistant
```
This agent includes:
- **dlt MCP** pre-configured and ready to use
- **Pipeline-focused rules** for data engineering best practices
</Step>
<Step title="Run Your First Pipeline Inspection">
Start with a comprehensive pipeline check:
```bash
# TUI mode
Inspect the execution of my dlt pipeline and summarize the load info, including timing and file sizes.
```
That's it! The agent handles everything automatically.
</Step>
</Steps>
<Info>
**Why Use the Agent?** The pre-built [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant) provides consistent pipeline development workflows and handles MCP configuration automatically, making it easier to get started with AI-powered data engineering. You can [remix and customize this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) later to fit your team's specific workflow.
</Info>
</Tab>
<Tab title="🛠️ Manual Setup">
<Steps>
<Step title="Create a New Agent via the Continue Hub">
Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent).
</Step>
<Step title="Connect dlt MCP via Continue Hub">
Visit the [dlt MCP on Continue Hub](https://hub.continue.dev/dlthub/dlt-mcp) and click **Install** to add it to the agent you created in the step above.
This will add dlt MCP to your agent's available tools. The Hub listing automatically configures the MCP command.
<Tip>
**Alternative installation methods:**
1. **Quick CLI install**: `cn --mcp dlthub/dlt-mcp`
2. **Manual configuration**: Add the MCP to your `~/.continue/config.json` under the `mcpServers` section
Once installed, dlt MCP tools become available to your Continue agent for all prompts.
</Tip>
<Info>
The MCP will work with your existing dlt pipelines in your current directory.
</Info>
</Step>
<Step title="Run Your First Pipeline Inspection">
Start with a comprehensive pipeline check:
```bash
# TUI mode
cn
# Then type: Inspect the execution of my dlt pipeline and summarize the load info, including timing and file sizes.
```
</Step>
</Steps>
</Tab>
</Tabs>
<Accordion title="Agent Requirements">
To use the pre-built [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant), you need either:
- **Continue CLI Pro Plan** with the models add-on, OR
- **Your own API keys** added to Continue Hub secrets (same as manual setup)
The agent will automatically detect and use your configuration along with the pre-configured dlt MCP for pipeline operations.
</Accordion>
---
## dlt MCP vs dlt+ MCP
<Card title="Understanding the Difference" icon="info-circle">
**dlt MCP** is focused on local pipeline development and inspection. It provides tools to:
- Inspect pipeline execution and load information
- Retrieve schema metadata from your local pipelines
- Query dataset records from destination databases
- Analyze load errors, timings, and file sizes
**[dlt+ MCP](https://hub.continue.dev/dlthub/dlt-plus-mcp)** extends these capabilities with cloud-based features for production deployments:
- Connect to dlt+ Projects and manage deployments
- Monitor pipeline runs across multiple environments
- Access centralized logging and observability
- Collaborate with team members on pipeline development
For local development and getting started, **[dlt MCP](https://hub.continue.dev/dlthub/dlt-mcp)** is the right choice. Consider **[dlt+ MCP](https://hub.continue.dev/dlthub/dlt-plus-mcp)** when you need production deployment features and team collaboration.
</Card>
---
## Pipeline Development Recipes
Now you can use natural language prompts to develop and debug your dlt pipelines. The Continue agent automatically calls the appropriate dlt MCP tools.
<Info>
You can add prompts to your agent's configuration for easy access in future sessions. Go to your agent in the [Continue Hub](https://hub.continue.dev), click **Edit**, and add prompts under the **Prompts** section.
</Info>
<Info>
**Where to run these workflows:**
- **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs
- **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts
- **CLI (headless mode)**: Use `cn -p "your prompt"` for headless commands
**Test in Plan Mode First**: Before running pipeline operations that might make
changes, test your prompts in plan mode (see the [Plan Mode
Guide](/guides/plan-mode-guide); press **Shift+Tab** to switch modes in TUI/IDE). This
shows you what the agent will do without executing it.
</Info>
<Info>
**About the --auto flag**: The `--auto` flag enables tools to run continuously without manual confirmation. This is essential for headless mode where the agent needs to execute multiple tools automatically to complete tasks like pipeline inspection, schema retrieval, and error analysis.
</Info>
### Pipeline Inspection
<Card title="Inspect Pipeline Execution" icon="magnifying-glass">
Review pipeline execution details including load timing and file sizes.
**TUI Mode Prompt:**
```
Inspect my dlt pipeline execution and provide a summary of the load info.
Show me the timing breakdown and file sizes for each table.
```
**Headless Mode Prompt:**
```bash
cn -p "Inspect my dlt pipeline execution and provide a summary of the load info. Show me the timing breakdown and file sizes for each table." --auto
```
</Card>
### Schema Management
<Card title="Retrieve Schema Metadata" icon="diagram-project">
Get detailed schema information for your pipeline's tables.
**TUI Mode Prompt:**
```
Show me the schema for my users table including all columns,
data types, and any constraints.
```
**Headless Mode Prompt:**
```bash
cn -p "Show me the schema for my users table including all columns, data types, and any constraints." --auto
```
</Card>
### Data Exploration
<Card title="Query Dataset Records" icon="table">
Retrieve and analyze records from your destination database.
**TUI Mode Prompt:**
```
Get the last 10 records from my orders table and show me
the distribution of order statuses.
```
**Headless Mode Prompt:**
```bash
cn -p "Get the last 10 records from my orders table and show me the distribution of order statuses." --auto
```
</Card>
### Error Debugging
<Card title="Analyze Load Errors" icon="triangle-exclamation">
Investigate and understand pipeline load errors.
**TUI Mode Prompt:**
```
Check for any load errors in my last pipeline run. If there are errors,
explain what went wrong and suggest fixes.
```
**Headless Mode Prompt:**
```bash
cn -p "Check for any load errors in my last pipeline run. If there are errors, explain what went wrong and suggest fixes." --auto
```
</Card>
### Pipeline Creation
<Card title="Build New Pipeline" icon="plus">
Create a new dlt pipeline from an API or data source.
**TUI Mode Prompt:**
```
Help me create a new dlt pipeline that loads data from the
JSONPlaceholder API users endpoint into DuckDB.
```
**Headless Mode Prompt:**
```bash
cn -p "Help me create a new dlt pipeline that loads data from the JSONPlaceholder API users endpoint into DuckDB." --auto
```
</Card>
### Schema Evolution
<Card title="Handle Schema Changes" icon="code-branch">
Review and manage schema evolution in your pipelines.
**TUI Mode Prompt:**
```
Check if my pipeline schema has evolved since the last run.
Show me what columns were added or modified.
```
**Headless Mode Prompt:**
```bash
cn -p "Check if my pipeline schema has evolved since the last run. Show me what columns were added or modified." --auto
```
</Card>
## Continuous Data Pipelines with GitHub Actions
This example demonstrates a **Continuous AI workflow** where data pipeline validation runs automatically in your CI/CD pipeline in headless mode using the [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant). Consider [remixing this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) to add your organization's specific validation rules.
### Add GitHub Secrets
Navigate to **Repository Settings → Secrets and variables → Actions** and add:
- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys)
- Any required database credentials for your destination
<Info>
The workflow uses the pre-built [dlt Assistant agent](https://hub.continue.dev/dlthub/dlt-assistant) with `--config dlthub/dlt-assistant`. This agent comes pre-configured with the dlt MCP and optimized rules for pipeline operations. You can [remix this agent](/guides/understanding-agents#how-to-get-started-with-hub-agents) to customize the validation rules and prompts for your specific pipeline requirements.
</Info>
### Create Workflow File
This workflow automatically validates your dlt data pipelines on pull requests using the Continue CLI in [headless mode](/cli/overview#headless-mode%3A-production-automation). It inspects pipeline schemas, checks for errors, and posts a summary report as a PR comment. The workflow can also be triggered manually via `workflow_dispatch`.
Create `.github/workflows/dlt-pipeline-validation.yml` in your repository:
```yaml
name: Data Pipeline Validation with dlt MCP
on:
pull_request:
branches: [main]
workflow_dispatch:
jobs:
validate-pipeline:
runs-on: ubuntu-latest
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: "18"
- name: Install dlt
run: |
pip install dlt
echo "✅ dlt installed"
- name: Install Continue CLI
run: |
npm install -g @continuedev/cli
echo "✅ Continue CLI installed"
- name: Validate Pipeline Schema
run: |
echo "🔍 Validating pipeline schema..."
cn --config dlthub/dlt-assistant \
-p "Inspect the pipeline schema and verify all required tables
and columns are present. Flag any missing or unexpected changes." \
--auto
- name: Check Pipeline Health
run: |
echo "📊 Checking pipeline health..."
cn --config dlthub/dlt-assistant \
-p "Analyze the last pipeline run for errors or warnings.
Report any issues that need attention." \
--auto
- name: Comment Pipeline Report on PR
if: always() && github.event_name == 'pull_request'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
REPORT=$(cn --config dlthub/dlt-assistant \
-p "Generate a concise summary (200 words or less) of:
- Pipeline schemas and row counts
- Any load errors or warnings
- Performance metrics (timing, file sizes)
- Recommended improvements" \
--auto)
gh pr comment ${{ github.event.pull_request.number }} --body "$REPORT"
```
<Info>
The dlt MCP works with your local pipeline state. Make sure your CI environment
has access to the necessary pipeline configuration and credentials.
</Info>
## Pipeline Development Best Practices
Implement automated pipeline quality checks using Continue's rule system. See the [Rules deep dive](/customize/deep-dives/rules) for authoring tips.
<Card title="Schema Validation" icon="check-circle">
```bash
"Before committing pipeline changes, verify the schema
matches expectations and flag any unexpected modifications."
```
</Card>
<Card title="Error Handling" icon="shield-exclamation">
```bash
"When load errors occur, analyze the error details and
suggest specific code fixes to handle the data issues."
```
</Card>
<Card title="Performance Monitoring" icon="gauge-high">
```bash
"Track pipeline execution times and file sizes. Alert if
performance degrades significantly from baseline."
```
</Card>
<Card title="Data Quality" icon="check-double">
```bash
"After each pipeline run, validate row counts and check for
null values in critical columns."
```
</Card>
## Troubleshooting
### Pipeline Not Found
```bash
"Check if there's a dlt pipeline in the current directory.
If not, help me initialize a new pipeline."
```
### Destination Connection Issues
```bash
"Verify the destination connection and credentials for my pipeline.
Test the connection and report any issues."
```
### Schema Inference Problems
<Check>
**Verification Steps:**
- dlt MCP is installed via [Continue Hub](https://hub.continue.dev/dlthub/dlt-mcp)
- Pipeline directory is accessible
- Destination database credentials are configured
- Pipeline has been run at least once
</Check>
## What You've Built
After completing this guide, you have a complete **AI-powered data pipeline development system** that:
✅ Uses natural language — Simple prompts instead of complex pipeline commands
✅ Debugs automatically — AI analyzes errors and suggests fixes
✅ Runs continuously — Automated validation in CI/CD pipelines
✅ Ensures quality — Pipeline checks prevent bad data from shipping
<Card title="Continuous AI" icon="rocket">
Your data pipeline workflow now operates at **[Level 2 Continuous
AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** -
AI handles routine pipeline inspection and debugging with human oversight
through review and approval of changes.
</Card>
## Next Steps
1. **Inspect your first pipeline** - Try the pipeline inspection prompt on your current project
2. **Debug load errors** - Use the error analysis prompt to fix any issues
3. **Set up CI pipeline** - Add the GitHub Actions workflow to your repo
4. **Create new pipelines** - Use AI to scaffold new data sources
5. **Monitor performance** - Track pipeline execution metrics over time
## Additional Resources
<CardGroup cols={2}>
<Card title="dlt Documentation" icon="book" href="https://dlthub.com/docs">
Complete dlt platform documentation
</Card>
<Card title="Continue Hub" icon="plug" href="https://hub.continue.dev">
Explore more MCP integrations and agents
</Card>
<Card
title="dlt Blog: MCP Deep Dive"
icon="newspaper"
href="https://dlthub.com/blog/deep-dive-assistants-mcp-continue"
>
Learn about AI assistants, MCP, and Continue integration
</Card>
<Card
title="MCP Concepts"
icon="puzzle-piece"
href="https://dlthub.com/blog/deep-dive-assistants-mcp-continue"
>
Deep dive into dlt MCP integration
</Card>
</CardGroup>

View file

@ -0,0 +1,376 @@
---
title: "GitHub Issues and PRs with GitHub MCP and Continue"
description: "Use Continue and the GitHub MCP to list, summarize, and act on open issues and recently merged pull requests with natural language prompts."
sidebarTitle: "GitHub Issues with Continue"
---
<Card title="What You'll Build" icon="github">
A GitHub workflow assistant that uses Continue with the GitHub MCP to:
- List, filter, and summarize open issues
- Review and summarize recently merged PRs
- Post comments with AI-generated summaries or checklists
- Automate routine GitHub maintenance with headless CLI runs
</Card>
## Prerequisites
Before starting, ensure you have:
- Continue account with **Hub access**
- Read: [Understanding Agents — How to get started with Hub agents](/guides/understanding-agents#how-to-get-started-with-hub-agents)
- Node.js 22+ installed locally
- A GitHub account and a repository to work with
- A GitHub token with the appropriate scopes:
- For read-only: `repo:read`
- To comment on issues/PRs: `public_repo` for public repos or `repo` for private repos
For all options, first:
<Steps>
<Step title="Install Continue CLI">
```bash
npm i -g @continuedev/cli
```
</Step>
<Step title="Configure GitHub Token">
Add your `GITHUB_TOKEN` to your [Continue Hub agent's environment variables](https://hub.continue.dev/settings).
</Step>
</Steps>
<Warning>
To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys).
For write actions (e.g., posting comments), your token must include the relevant GitHub scopes.
</Warning>
## GitHub MCP Workflow Options
<Card title="🚀 Fastest Path to Success" icon="rocket">
Use the GitHub MCP from Continue Hub for one-click setup, or add it via CLI.
</Card>
After ensuring you meet the **Prerequisites** above, you have two paths to get started:
<Tabs>
<Tab title="⚡ Quick Start (Recommended)">
<Steps>
<Step title="Install GitHub MCP via Continue Hub">
Visit the [Anthropic GitHub MCP](https://hub.continue.dev/anthropic/github-mcp) on Continue Hub and click **Install** to add it to your agent.
The listing provides a pre-configured MCP block; add your `GITHUB_TOKEN` in Hub.
</Step>
<Step title="Launch the Agent">
From your repo root:
```bash
cn --config continuedev/github-manager-ai
```
Now try: "List my open issues labeled bug and summarize priorities."
</Step>
</Steps>
<Info>
You can also attach an MCP to a one-off session: `cn --mcp anthropic/github-mcp`.
</Info>
</Tab>
<Tab title="🛠️ Manual Setup">
<Steps>
<Step title="Create a New Agent on Continue Hub">
Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent).
</Step>
<Step title="Add GitHub MCP">
Install from Hub (recommended) or add YAML manually. Minimal YAML example:
```yaml title="config.yaml"
mcpServers:
- name: GitHub MCP
command: npx
args:
- "-y"
- "@modelcontextprotocol/server-github"
env:
GITHUB_TOKEN: ${env:GITHUB_TOKEN}
connectionTimeout: 30
```
Notes:
- The exact `command`/`args` may differ based on the MCP you choose on Hub. Hub templates prefill these for you.
- Provide `GITHUB_TOKEN` via environment or Hub secrets.
</Step>
<Step title="Test the Connection">
Launch Continue and ask:
```
List the 5 most recently updated open issues in this repository.
```
</Step>
</Steps>
</Tab>
</Tabs>
<Accordion title="Agent Requirements">
To use GitHub MCP with Continue CLI, you need either:
- **Continue CLI Pro Plan** with the models add-on, OR
- **Your own API keys** added to Continue Hub secrets
The agent will automatically detect and use your configuration along with the GitHub MCP for issue and PR operations.
</Accordion>
---
## Issue Workflows
Use natural language to explore, triage, and act on open issues. The agent calls GitHub MCP tools under the hood.
<Info>
**Where to run these workflows:**
- **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs
- **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts
- **CLI (headless mode)**: Use `cn -p "your prompt" --auto` for automation
</Info>
### Triage and Summaries
<Card title="Summarize Open Issues" icon="clipboard-list">
Get a prioritized overview of current open issues.
**TUI Mode Prompt:**
```
List the 20 most recently updated open issues in this repo.
Cluster by label and severity. Summarize top priorities.
```
**Headless Mode Prompt:**
```bash
cn -p "List the 20 most recently updated open issues in this repo. Cluster by label and severity. Summarize top priorities." --auto
```
</Card>
<Card title="Owner/Label Filters" icon="filter">
Narrow by label or assignee.
**TUI Mode Prompt:**
```
Show open issues labeled bug or security, assigned to @me.
Summarize blockers and suggest next steps.
```
**Headless Mode Prompt:**
```bash
cn -p "Show open issues labeled bug or security, assigned to @me. Summarize blockers and suggest next steps." --auto
```
</Card>
### Taking Action
<Card title="Comment on an Issue" icon="comment">
Post an AI-generated status update or checklist.
**TUI Mode Prompt:**
```
Find the issue with the most engagement (comments, reactions) in the last 30 days.
Come up with a triage plan and draft a comment with:
- current hypothesis
- next 2 steps
- owner and ETA
Then post the comment.
```
**Headless Mode Prompt:**
```bash
cn -p "Find the issue with the most engagement in the last 30 days. Come up with a triage plan and draft a comment (hypothesis, next 2 steps, owner, ETA) and post it." --auto
```
<Note>
Requires a token with permission to comment (`public_repo` or `repo`). The agent will confirm before posting unless `--auto` is used.
</Note>
</Card>
<Card title="Find Stale Issues" icon="clock">
Identify issues that need attention.
**TUI Mode Prompt:**
```
Find open issues with no activity in the last 30 days.
Suggest action (close, needs-repro, or prioritize) and draft comments.
```
**Headless Mode Prompt:**
```bash
cn -p "Find open issues with no activity in the last 30 days. Suggest action and draft comments for each." --auto
```
</Card>
---
## Merged PR Workflows
Analyze recently merged PRs for change awareness, release notes, and quality signals.
### Recently Merged Overview
<Card title="Merged PR Digest" icon="code-merge">
Summarize merged PRs over a time window.
**TUI Mode Prompt:**
```
List PRs merged in the last 7 days.
Group by area (label or path). Summarize impact and notable changes.
```
**Headless Mode Prompt:**
```bash
cn -p "List PRs merged in the last 7 days. Group by area (label or path). Summarize impact and notable changes." --auto
```
</Card>
### Release Notes
<Card title="Generate Release Notes" icon="file-lines">
Turn merged PRs into crisp release notes.
**TUI Mode Prompt:**
```
Generate release notes for PRs merged since tag v1.2.0.
Use keep-a-changelog sections and include PR numbers/authors.
```
**Headless Mode Prompt:**
```bash
cn -p "Generate release notes for PRs merged since tag v1.2.0. Use keep-a-changelog sections and include PR numbers/authors." --auto
```
</Card>
### Deep Dives
<Card title="Summarize a PR" icon="magnifying-glass">
Get a human-readable summary of a recently merged PR with active discussion.
**TUI Mode Prompt:**
```
Find the last merged PR with a significant amount of comments.
Summarize the conversation, including goal, key changes,
risk areas, and any follow-ups.
```
**Headless Mode Prompt:**
```bash
cn -p "Find the last merged PR with a significant amount of comments. Summarize the conversation including goal, key changes, risk areas, and follow-ups." --auto
```
</Card>
---
## Automate with GitHub Actions
Run headless commands on a schedule or in PRs to keep teams informed.
### Add GitHub Secrets
Repository Settings → Secrets and variables → Actions:
- `CONTINUE_API_KEY`: From [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys)
- `GITHUB_TOKEN`: A token with permissions to read issues/PRs and post comments
### Example Workflow
Create `.github/workflows/github-mcp-reports.yml`:
```yaml
name: GitHub MCP Reports
on:
schedule:
- cron: "0 13 * * 1" # Mondays 13:00 UTC
workflow_dispatch:
pull_request:
types: [opened, synchronize]
jobs:
report:
runs-on: ubuntu-latest
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "18"
- name: Install Continue CLI
run: npm i -g @continuedev/cli
- name: Weekly Issue Triage Summary
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
run: |
cn --config continuedev/github-manager-ai \
-p "List open issues updated in the last 14 days. Group by label and priority. Propose top 5 actions and include issue links." \
--auto > issue_summary.txt
- name: Post PR Context Comment
if: github.event_name == 'pull_request'
env:
PR_NUMBER: ${{ github.event.pull_request.number }}
run: |
REPORT=$(cn --config continuedev/github-manager-ai \
-p "Summarize the context for PR #${PR_NUMBER}: related open issues, risk areas, and test suggestions. Keep under 200 words." \
--auto)
gh pr comment ${PR_NUMBER} --body "$REPORT"
```
<Info>
Use `continuedev/github-manager-ai` consistently throughout your automation as the recommended agent configuration.
</Info>
---
## Troubleshooting
- **Missing or invalid token:** Ensure `GITHUB_TOKEN` is set and has the required scopes. Try a minimal test: “List 3 open issues in this repo”.
- **Permissions errors on comment:** Your token must include `public_repo` (public) or `repo` (private) to write comments.
- **Rate limiting:** Reduce frequency or filter queries; consider using a PAT distinct from the default Actions token when running in CI.
- **MCP connection timeout:** If using custom YAML, increase `connectionTimeout` or verify the `command`/`args` from the Hub listing.
## What You've Built
After completing this guide, you have a complete **AI-powered GitHub workflow system** that:
- ✅ Uses natural language — Simple prompts for complex GitHub operations
- ✅ Automates issue triage — AI analyzes and summarizes open issues
- ✅ Generates release notes — Automatic PR digests and changelogs
- ✅ Runs continuously — Automated reports via GitHub Actions
<Card title="Continuous AI" icon="rocket">
Your GitHub workflow now operates at **[Level 2 Continuous
AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** -
AI handles routine issue triage and PR summaries with human oversight
through review and approval.
</Card>
## Next Steps
1. **Explore your issues** - Try the issue triage prompts on your repository
2. **Generate release notes** - Use the merged PR prompts to create changelogs
3. **Set up automation** - Add the GitHub Actions workflow to your repo
4. **Customize prompts** - Tailor the prompts to your team's workflow
5. **Monitor progress** - Track issue resolution metrics over time
## Additional Resources
<CardGroup cols={2}>
<Card title="GitHub MCP (Anthropic)" icon="link" href="https://hub.continue.dev/anthropic/github-mcp">
Anthropic GitHub MCP on Continue Hub
</Card>
<Card title="MCP in Continue" icon="book" href="/customize/deep-dives/mcp">
How MCP works with Continue agents
</Card>
<Card title="GitHub Manager AI Agent" icon="robot" href="https://hub.continue.dev/continuedev/github-manager-ai">
Pre-configured agent on Continue Hub
</Card>
<Card title="GitHub MCP Server" icon="link" href="https://github.com/github/github-mcp-server/blob/main/README.md">
Official GitHub MCP server README
</Card>
</CardGroup>

View file

@ -95,7 +95,7 @@ After completing **Quick Setup** above, you have two paths to get started:
</Step>
<Step title="Run Performance Analysis">
Navigate to your project directory and run:
From your project directory, run:
```bash
cn "Analyze my Netlify site's performance and optimize it for better Core Web Vitals."
```

View file

@ -0,0 +1,377 @@
---
title: "Developer & Team Workflows with Notion + Continue CLI"
description: "Use Continue CLI with Notion to generate docs, manage tasks, and automate project workflows – all through natural-language prompts."
sidebarTitle: "Notion with Continue"
---
<Card title="What You'll Build" icon="notion">
A workflow that lets you query, update, and create Notion pages or database
entries from natural-language prompts. Generate PRDs, sprint tasks, meeting
notes, or status reports automatically – perfect for individual developers
and cross-functional teams.
</Card>
## What You'll Learn
This guide teaches you to:
- Use natural language to connect to the Notion API directly with Continue CLI for powerful automation
- Configure Notion API access with proper permissions and security
- Run prompts in both TUI (interactive) and headless modes
- Create automated workflows that generate docs, manage tasks, and sync data
## Prerequisites
Before starting, ensure you have:
- [Continue CLI](https://docs.continue.dev/cli/overview) installed (`npm i -g @continuedev/cli`)
- A [Notion workspace](https://notion.so) with Editor (or higher) access
- Node.js 18+ installed locally
- [Continue account](https://hub.continue.dev) with **Hub access**
<Warning>
**Agent usage requires credits** – create a Continue API key at
[hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys)
and store it as a secret.
</Warning>
<Steps>
<Step title="Install Continue CLI">
```bash
npm i -g @continuedev/cli
```
Verify installation:
```bash
cn --version
```
</Step>
<Step title="Create Notion Integration & Get API Key">
1. Go to **[Notion Integrations](https://www.notion.so/my-integrations)**
2. Click **+ New integration** → give it a name (e.g. "Continue Integration")
3. Select your workspace
4. Under **Content Capabilities**, enable:
- ✅ Read content
- ✅ Update content
- ✅ Insert content
5. Under **Comment Capabilities**, enable:
- ✅ Read comments
- ✅ Insert comments
6. Under **User Capabilities**, select:
- ✅ Read user information including email addresses
7. Click **Submit** and copy the **Internal Integration Secret** (starts with `secret_`)
<Info>
This token is your `NOTION_API_KEY`.
Keep it safe – you won't be able to view it again.
</Info>
8. In Notion, open each database or top-level page you want accessible → **Share** → **Invite** your new integration → **Full access**.
</Step>
<Step title="Configure API Access">
Set your Notion API key as an environment variable in your terminal:
```bash
export NOTION_API_KEY="secret_xxx"
```
<Tip>
Running this command sets your API key for the current terminal session only.
When you close the terminal, the variable won't persist. To test your API key, run the curl command below in the same session.
```bash
curl -H "Authorization: Bearer $NOTION_API_KEY" \
-H "Notion-Version: 2022-06-28" \
https://api.notion.com/v1/databases
```
</Tip>
</Step>
<Step title="Add Workspace Keys to Terminal Session">
Depending on what you want `cn` to accomplish, you'll need to add your Notion workspace keys to the terminal session. The workspace key is your Notion database ID. Run the following command:
```bash
export NOTION_DATABASE_ID="your_database_id"
```
<Tip>
You can find your database ID by:
1. Opening your Notion changelog database
2. Looking at the URL - it will be something like:
https://www.notion.so/your-workspace/DATABASE_ID?v=...
3. The DATABASE_ID is the long string of characters between the last / and the ?
</Tip>
</Step>
</Steps>
## Running Continue AI Agent with Notion API
<Card title="🚀 Choose Your Interface" icon="zap">
Continue CLI offers two powerful modes for Notion automation:
**TUI mode** for interactive workflows and **Headless mode** for automated scripts.
</Card>
<Tabs>
<Tab title="🖥️ TUI Mode (Interactive)">
<Steps>
<Step title="Launch Interactive Mode">
Navigate to your project directory and run:
```bash
cn
```
</Step>
<Step title="Run Your First Prompt">
In the TUI interface, enter:
```
1. Fetch my Notion databases using the Notion API key
and Database ID stored in this terminal session.
2. Look at the last week of Merged GitHub PRs, and create
a changelog entry in Notion summarizing the features and breaking changes.
```
<Tip>
TUI mode lets you review and approve each action before execution,
perfect for learning and debugging.
</Tip>
</Step>
</Steps>
</Tab>
<Tab title="🤖 Headless Mode (Automated)">
<Steps>
<Step title="Run Automated Commands">
Execute prompts directly from the command line:
```bash
cn -p --auto "
1. Fetch my Notion databases using the Notion API key
and Database ID stored in this terminal session.
2. Analyze all merged GitHub PRs from the past week.
3. Extract feature descriptions and breaking changes.
4. Create a technical changelog in Notion with PR links."
```
**Flags explained:**
- `-p`: Run without TUI interface
- `--auto`: Execute without manual approval
<Warning>
Always test prompts in TUI mode first before running
them with `--auto` in production.
</Warning>
</Step>
</Steps>
</Tab>
</Tabs>
<Accordion title="API Connection Notes">
- Environment variable `NOTION_API_KEY` must be set before running Continue CLI
- Continue automatically uses the API key to authenticate with Notion
- No need for manual curl commands - just reference "the API key stored in this session"
- For complex workflows, Continue maintains the API connection throughout
- Consider creating aliases or scripts for frequently used prompts
</Accordion>
---
## Quick Start Example
Working example that demonstrates the power of Continue with Notion API:
<Card title="📊 Weekly Sprint Summary" icon="chart-line">
**This exact command has been tested and works:**
```bash
# Weekly Sprint Summary
cn -p --auto "
1. Fetch Notion Sprint database
2. Analyze completed tasks vs planned
3. Generate sprint retrospective page
4. Add velocity metrics and burndown chart"
```
**What this does:**
1. Connects to your Notion workspace using the API key
2. Analyzes your sprint data
3. Calculates completion metrics
4. Creates a comprehensive retrospective with visualizations
</Card>
## Example Prompts & Workflows
With the Notion API configured, you can use natural language prompts to automate your workspace. Here are examples for both TUI and headless modes:
<CardGroup cols={1}>
<Card title="API Documentation" icon="code">
**TUI Mode:**
```bash
cn "
1. Fetch my Notion databases using the API key and secrets stored in this session
2. Generate API documentation for all endpoints
in src/api/routes with request/response schemas
3. Create a page in Technical Docs database
"
```
**Headless Mode:**
```bash
cn -p --auto "Fetch my Notion databases using the API key and secrets stored in this session. Generate API docs
for src/api/routes and save to Notion in Technical Docs database"
```
</Card>
<Card title="Sprint Planning from Code" icon="list-checks">
**Headless Mode (Automated):**
```bash
cn -p --auto "
1. Fetch my Notion databases using the API key stored in this session
2. Scan codebase for TODO and FIXME comments
3. Create tasks in my Notion Engineering Backlog database
4. Include file paths and complexity estimates"
```
</Card>
<Card title="Changelog from PRs" icon="rocket">
```bash
cn -p --auto "
1. Fetch my Notion databases using the API key stored in this session
2. Analyze all merged GitHub PRs from past month
3. In my Notion Launch Database, review the Launch Template.
4. Create an October Launch doc in Notion with a week of launches and materials based on the Launch documents based on the PR analysis and launch documents."
```
</Card>
<Card title="Daily Standup Automation" icon="comments">
```bash
cn -p --auto "
1. Fetch my Tasks database from Notion using the API key
2. Find tasks completed yesterday
3. Find tasks in progress
4. Create standup note with: completed,
in-progress, and blockers sections"
```
</Card>
</CardGroup>
## Advanced Workflows
<CardGroup cols={1}>
<Card title="Notion + GitHub" icon="github">
```bash
cn -p --auto "
1. Connect to Notion using the API key in this session
2. Get merged PRs from last 7 days using GitHub
3. Extract feature descriptions and changes
4. Create formatted changelog in Notion
5. Add links back to GitHub PRs"
```
<Info>
Requires GitHub repository access. To add GitHub access, update your [integration settings](https://hub.continue.dev/settings/integrations).
</Info>
</Card>
<Card title="Test Coverage Report" icon="chart-bar">
```bash
cn -p --auto "
1. Connect to Notion using the API key in this session
2. Run test coverage report (npm test -- --coverage)
3. Parse coverage metrics
4. Update Test Metrics database in Notion
5. Flag files with coverage below 80%"
```
</Card>
<Card title="Blog Post Review" icon="magnifying-glass">
```bash
cn "
1. Connect to Notion using the API key in this session
2. In my Blog Posts Database, find drafts tagged 'Review'
3. Review all blog posts for grammar and clarity and suggest improvements through comments.
```
</Card>
<Card title="Weekly Report Generation" icon="list">
```bash
cn -p --auto "
1. Connect to Notion databases using API key
2. Aggregate completed tasks from the week
3. Calculate velocity and burndown metrics
4. Generate weekly report with charts
5. Share link in Slack #team-updates"
```
</Card>
</CardGroup>
## Security Best Practices
<Warning>
**Protect Your API Keys:**
- Never commit `NOTION_API_KEY` to version control
- Use environment variables or secure secret managers
- Rotate API keys every 90 days
- Grant integration access only to required databases/pages
- Monitor API usage through Notion's integration dashboard
- Use `.env` files with `.gitignore` for local development
</Warning>
## Next Steps
- Create a **GitHub Actions** workflow to automate changelog generation on releases
- Build a **daily standup bot** that runs every morning and posts to Slack
- Set up **database templates** in Notion for consistent formatting
- Explore **batch operations** to update multiple pages efficiently
- Implement **error handling** for API rate limits and network issues
---
## Troubleshooting
<Accordion title="Common Issues and Solutions">
**API Key Not Found:**
- Ensure `NOTION_API_KEY` is exported in your current shell session
- Check for typos in the environment variable name
- Verify the key starts with `secret_`
**Database Access Denied:**
- Share the specific database with your integration in Notion
- Ensure the integration has the correct permissions (Read, Write, Insert)
**Connection Issues:**
- Verify Continue CLI has internet access
- Check network connectivity to api.notion.com
- Ensure your Notion workspace allows API access
**Rate Limiting:**
- Notion API has rate limits (3 requests per second)
- Implement exponential backoff for automated scripts
- Consider batching operations when possible
</Accordion>

View file

@ -14,14 +14,21 @@ description: "Comprehensive collection of practical guides for Continue includin
- [Continuous AI: A Developer's Guide](/guides/continuous-ai) - Integrating AI into development workflows
- [How to Use Continue CLI (cn)](/guides/cli) - Command-line interface for Continue
- [Continuous AI Readiness Assessment](/guides/continuous-ai-readiness-assessment) - Evaluate team readiness for Continuous AI adoption
- [Notion + Continue Guide](/guides/notion-continue-guide) - Automate docs, tasks, and release workflows
## MCP Integration Cookbooks
Step-by-step guides for integrating Model Context Protocol (MCP) servers with Continue:
- [Continue Docs MCP Cookbook](/guides/continue-docs-mcp-cookbook) - Use the Continue Docs MCP to write cookbooks, guides, and documentation with AI-powered workflows
- [GitHub MCP Cookbook](/guides/github-mcp-continue-cookbook) - Use GitHub MCP to list, filter, and summarize open issues and merged PRs, and post AI-generated comments
- [PostHog Session Analysis Cookbook](/guides/posthog-github-continuous-ai) - Analyze user behavior data to optimize your codebase with automatic issue creation
- [Netlify Performance Optimization Cookbook](/guides/netlify-mcp-continuous-deployment) - Optimize web performance with A/B testing and automated monitoring using Netlify MCP
- [Chrome DevTools Performance Cookbook](/guides/chrome-devtools-mcp-performance) - Measure and optimize web performance with automated traces, Core Web Vitals monitoring, and performance budgets
- [Sanity CMS Integration Cookbook](/guides/sanity-mcp-continue-cookbook) - Manage headless CMS content with AI-powered workflows using Sanity MCP
- [Sentry Error Monitoring Cookbook](/guides/sentry-mcp-error-monitoring) - Automated error analysis with Sentry MCP to identify patterns and create actionable GitHub issues
- [Snyk + Continue Hub Agent Cookbook (MCP)](/guides/snyk-mcp-continue-cookbook) - Integrate Snyk MCP via Continue Hub to scan code, deps, IaC, and containers
- [dlt Data Pipelines Cookbook](/guides/dlt-mcp-continue-cookbook) - Build AI-powered data pipelines with dlt MCP for pipeline inspection, schema management, and debugging
## What Advanced Tutorials Are Available

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