merge: main

This commit is contained in:
Dallin Romney 2025-08-21 17:42:25 -07:00
commit 91908c92e4
473 changed files with 72412 additions and 3142 deletions

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

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

View file

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

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

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

View file

@ -120,7 +120,7 @@ jobs:
# # Set up Java environment for the next steps
- name: Setup Java
uses: actions/setup-java@v4
uses: actions/setup-java@v5
with:
distribution: zulu
java-version: 17
@ -433,7 +433,7 @@ jobs:
# Set up Java environment for the next steps
- name: Setup Java
uses: actions/setup-java@v4
uses: actions/setup-java@v5
with:
distribution: zulu
java-version: 17
@ -486,7 +486,7 @@ jobs:
# Set up Java environment for the next steps
- name: Setup Java
uses: actions/setup-java@v4
uses: actions/setup-java@v5
with:
distribution: zulu
java-version: 17
@ -517,7 +517,7 @@ jobs:
# Set up Java environment for the next steps
- name: Setup Java
uses: actions/setup-java@v4
uses: actions/setup-java@v5
with:
distribution: zulu
java-version: 17

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

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

View file

@ -14,7 +14,7 @@ jobs:
- name: Checkout sources
uses: actions/checkout@v5
- name: Setup Java
uses: actions/setup-java@v4
uses: actions/setup-java@v5
with:
distribution: "temurin"
java-version: 17

1
.gitignore vendored
View file

@ -158,6 +158,7 @@ extensions/intellij/.idea/**
**/.idea/shelf/
**/.idea/inspectionProfiles/Project_Default.xml
**/.idea/php.xml
**/.idea/kotlinc.xml
extensions/intellij/bin

6
.idea/kotlinc.xml generated
View file

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

43
.vscode/launch.json vendored
View file

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

View file

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

62
.vscode/tasks.json vendored
View file

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

View file

@ -40,7 +40,7 @@
"pkg": "^5.8.1",
"rimraf": "^5.0.7",
"ts-jest": "^29.1.4",
"typescript": "^5.3.3"
"typescript": "^5.6.3"
}
},
"../core": {
@ -59,6 +59,11 @@
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
"@sentry/cli": "^2.50.2",
"@sentry/core": "^9.43.0",
"@sentry/esbuild-plugin": "^4.0.2",
"@sentry/node": "^9.43.0",
"@sentry/vite-plugin": "^4.0.2",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@xenova/transformers": "2.14.0",
"adf-to-md": "^1.1.0",
@ -78,7 +83,7 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"iconv-lite": "^0.6.3",
"ignore": "^5.3.1",
"ignore": "^7.0.5",
"is-localhost-ip": "^2.0.0",
"jinja-js": "0.1.8",
"js-tiktoken": "^1.0.8",
@ -91,7 +96,7 @@
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",
"onnxruntime-node": "1.14.0",
"openai": "^4.104.0",
"openai": "^5.13.1",
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",
@ -6758,10 +6763,11 @@
}
},
"node_modules/typescript": {
"version": "5.4.5",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz",
"integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==",
"version": "5.9.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz",
"integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -20,9 +20,8 @@ import {
} from "../../";
import { stringifyMcpPrompt } from "../../commands/slash/mcpSlashCommand";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import CurrentFileContextProvider from "../../context/providers/CurrentFileContextProvider";
import ContinueProxyContextProvider from "../../context/providers/ContinueProxyContextProvider";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
import RulesContextProvider from "../../context/providers/RulesContextProvider";
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
@ -158,17 +157,13 @@ export default async function doLoadConfig(options: {
const { rules, errors: rulesErrors } = await loadRules(ide);
errors.push(...rulesErrors);
newConfig.rules.unshift(...rules);
newConfig.contextProviders.push(new RulesContextProvider({}));
// Add current file as context if setting is enabled
if (
newConfig.experimental?.useCurrentFileAsContext === true &&
!newConfig.contextProviders.find(
(c) =>
c.description.title === CurrentFileContextProvider.description.title,
)
) {
newConfig.contextProviders.push(new CurrentFileContextProvider({}));
const proxyContextProvider = newConfig.contextProviders?.find(
(cp) => cp.description.title === "continue-proxy",
);
if (proxyContextProvider) {
(proxyContextProvider as ContinueProxyContextProvider).workOsAccessToken =
workOsAccessToken;
}
// Show deprecation warnings for providers

View file

@ -14,18 +14,8 @@ import {
} from "@continuedev/config-yaml";
import { dirname } from "node:path";
import {
ContinueConfig,
IContextProvider,
IDE,
IdeInfo,
IdeSettings,
ILLMLogger,
} from "../..";
import { ContinueConfig, IDE, IdeInfo, IdeSettings, ILLMLogger } from "../..";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import FileContextProvider from "../../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../../context/providers/index";
import { ControlPlaneClient } from "../../control-plane/client";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import { getAllPromptFiles } from "../../promptFiles/getPromptFiles";
@ -37,6 +27,7 @@ import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlash
import { getControlPlaneEnvSync } from "../../control-plane/env";
import { getToolsForIde } from "../../tools";
import { getCleanUriPath } from "../../util/uri";
import { loadConfigContextProviders } from "../loadContextProviders";
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks";
import { LocalPlatformClient } from "./LocalPlatformClient";
@ -376,42 +367,14 @@ async function configYamlToContinueConfig(options: {
});
}
// Context providers
const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
({ description: { title } }) => title,
const { providers, errors: contextErrors } = loadConfigContextProviders(
config.context,
!!config.docs?.length,
ideInfo.ideType,
);
continueConfig.contextProviders = (config.context
?.map((context) => {
const cls = contextProviderClassFromName(context.provider) as any;
if (!cls) {
if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.provider)) {
localErrors.push({
fatal: false,
message: `Unknown context provider ${context.provider}`,
});
}
return undefined;
}
const instance: IContextProvider = new cls({
name: context.name,
...context.params,
});
return instance;
})
.filter((p) => !!p) ?? []) as IContextProvider[];
continueConfig.contextProviders.push(...DEFAULT_CONTEXT_PROVIDERS);
if (
continueConfig.docs?.length &&
!continueConfig.contextProviders?.some(
(cp) => cp.description.title === "docs",
)
) {
continueConfig.contextProviders.push(new DocsContextProvider({}));
}
continueConfig.contextProviders = providers;
localErrors.push(...contextErrors);
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();

View file

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

View file

@ -6,6 +6,7 @@ import {
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../";
import { isSecurityConcern } from "../../indexing/ignore";
import { walkDirs } from "../../indexing/walkDir";
import {
getShortestUniqueRelativeUriPaths,
@ -36,6 +37,21 @@ class FileContextProvider extends BaseContextProvider {
await extras.ide.getWorkspaceDirs(),
);
if (isSecurityConcern(relativePathOrBasename)) {
return [
{
description: last2Parts,
content:
"Content redacted, this file cannot be viewed for security reasons",
name: baseName,
uri: {
type: "file",
value: fileUri,
},
},
];
}
return [
{
name: baseName,

View file

@ -3,6 +3,7 @@ import {
ContextProviderDescription,
ContextProviderExtras,
} from "../../index.js";
import { isSecurityConcern } from "../../indexing/ignore.js";
import { getUriDescription } from "../../util/uri.js";
import { BaseContextProvider } from "../index.js";
@ -27,10 +28,23 @@ class OpenFilesContextProvider extends BaseContextProvider {
return await Promise.all(
openFiles.map(async (filepath: string) => {
const content = await ide.readFile(filepath);
const { relativePathOrBasename, last2Parts, baseName } =
getUriDescription(filepath, workspaceDirs);
if (isSecurityConcern(filepath)) {
return {
description: last2Parts,
content:
"Content redacted, this file cannot be viewed for security reasons",
name: baseName,
uri: {
type: "file",
value: filepath,
},
};
}
const content = await ide.readFile(filepath);
return {
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${content}\n\`\`\``,

View file

@ -3,6 +3,7 @@ import {
ContextProviderDescription,
ContextProviderExtras,
} from "../../index.js";
import { isSecurityConcern } from "../../indexing/ignore.js";
import { getUriDescription } from "../../util/uri.js";
import { BaseContextProvider } from "../index.js";
@ -28,6 +29,14 @@ class ProblemsContextProvider extends BaseContextProvider {
problem.filepath,
workspaceDirs,
);
if (isSecurityConcern(relativePathOrBasename)) {
return {
description: "Problems in current file",
content:
"Content was redacted because the file is detected as a potential security concern",
name: `Warnings in ${baseName}`,
};
}
const content = await ide.readFile(problem.filepath);
const lines = content.split("\n");
const rangeContent = lines
@ -40,7 +49,7 @@ class ProblemsContextProvider extends BaseContextProvider {
return {
description: "Problems in current file",
content: `\`\`\`${relativePathOrBasename}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`,
name: `Warning in ${baseName}`,
name: `Warnings in ${baseName}`,
};
}),
);

View file

@ -10,7 +10,6 @@ import {
import { ConfigHandler } from "./config/ConfigHandler";
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
import { addModel, deleteModel } from "./config/util";
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
import { getControlPlaneEnv } from "./control-plane/env";
import { DevDataSqliteDb } from "./data/devdataSqlite";
@ -51,6 +50,7 @@ import {
import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
import { createNewAssistantFile } from "./config/createNewAssistantFile";
import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
import { CodebaseRulesCache } from "./config/markdown/loadCodebaseRules";
import {
@ -354,6 +354,13 @@ export class Core {
);
});
on("config/newAssistantFile", async (msg) => {
await createNewAssistantFile(this.ide, undefined);
await this.configHandler.reloadConfig(
"Assistant file created (config/newAssistantFile message)",
);
});
on("config/addLocalWorkspaceBlock", async (msg) => {
await createNewWorkspaceBlockFile(this.ide, msg.data.blockType);
await this.configHandler.reloadConfig(
@ -1273,15 +1280,9 @@ export class Core {
throw new Error("No chat model selected");
}
const provider =
config.contextProviders?.find(
(provider) => provider.description.title === name,
) ??
[
// user doesn't need these in their config.json for the shortcuts to work
// option+enter
new CurrentFileContextProvider({}),
].find((provider) => provider.description.title === name);
const provider = config.contextProviders?.find(
(provider) => provider.description.title === name,
);
if (!provider) {
return [];
}

View file

@ -426,101 +426,6 @@ const a = 1;`;
});
});
describe("jaroWinklerFuzzyMatch strategy", () => {
it("should match similar code with variable name differences", () => {
const fileContent = `function calculateTotal(items) {
let sum = 0;
for (const item of items) {
sum += item.price;
}
return sum;
}`;
const searchContent = `function calculateTotal(products) {
let total = 0;
for (const product of products) {
total += product.price;
}
return total;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("jaroWinklerFuzzyMatch");
});
it("should match code with minor typos", () => {
const testCases = [
{
name: "typo in function name",
fileContent: "function getUserName() { return this.name; }",
searchContent: "function getUserNaem() { return this.name; }",
},
{
name: "typo in variable",
fileContent: "const message = 'Hello World';",
searchContent: "const mesage = 'Hello World';",
},
{
name: "missing character",
fileContent: "console.log('Debug info');",
searchContent: "console.log('Debug nfo');",
},
];
testCases.forEach(({ name, fileContent, searchContent }) => {
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("jaroWinklerFuzzyMatch");
});
});
it("should not match when similarity is too low", () => {
const fileContent = "function add(a, b) { return a + b; }";
const searchContent =
"class Calculator { multiply(x, y) { return x * y; } }";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should handle multiline fuzzy matches", () => {
const fileContent = `if (userIsLoggedIn) {
showDashboard();
loadUserData();
}`;
const searchContent = `if (isUserLoggedIn) {
displayDashboard();
fetchUserData();
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result!.strategyName).toBe("jaroWinklerFuzzyMatch");
});
it("should verify replacement with fuzzy matches", () => {
const fileContent = "const userName = 'John';";
const searchContent = "const usrName = 'John';"; // Typo in variable name
const replacement = "const userName = 'Jane';";
const match = findSearchMatch(fileContent, searchContent);
expect(match).not.toBeNull();
expect(match!.strategyName).toBe("jaroWinklerFuzzyMatch");
const result = performReplacement(fileContent, match!, replacement);
expect(result).toBe(replacement);
});
it("should handle edge case with very short strings", () => {
const fileContent = "ab";
const searchContent = "ac";
const result = findSearchMatch(fileContent, searchContent);
// Should not match due to low similarity on short strings
expect(result).toBeNull();
});
});
describe("Empty search content", () => {
it("should always return position 0 for empty search", () => {
const testCases = [

View file

@ -191,34 +191,6 @@ describe("Empty search content", () => {
});
});
describe("No matches", () => {
it("should return null when search content is not found", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `function goodbye() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch");
});
it("should return only fuzzy result when trimmed search content is not found", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `\n\nfunction goodbye() {
console.log("world");
}\n\n`;
const result = findSearchMatch(fileContent, searchContent);
expect(result?.strategyName).toEqual("jaroWinklerFuzzyMatch");
});
});
describe("Edge cases", () => {
it("should handle empty file with non-empty search", () => {
const fileContent = "";
@ -612,157 +584,4 @@ function test() {
strategyName: "exactMatch",
});
});
describe("Jaro-Winkler fuzzy matching", () => {
describe("Basic fuzzy matching", () => {
it("should find fuzzy match for similar strings", () => {
const fileContent = `function calculateSum(a, b) {
return a + b;
}`;
const searchContent = `function calculateSum(x, y) {
return x + y;
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
it("should find fuzzy match with minor typos", () => {
const fileContent = `const message = "Hello World";`;
const searchContent = `const mesage = "Hello World";`; // Missing 's' in 'message'
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result?.startIndex).toBe(0);
});
it("should find fuzzy match with different variable names", () => {
const fileContent = `let userAge = 25;
let userName = "John";`;
const searchContent = `let age = 25;
let name = "John";`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
it("should find fuzzy match for similar function signature", () => {
const fileContent = `function processUserData(userData) {
validateInput(userData);
return formatOutput(userData);
}`;
const searchContent = `function processData(data) {
validateInput(data);
return formatOutput(data);
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
});
describe("Multi-line fuzzy matching", () => {
it("should find fuzzy match for multi-line blocks", () => {
const fileContent = `class Calculator {
constructor() {
this.result = 0;
}
add(value) {
this.result += value;
return this;
}
}`;
const searchContent = `class Calculator {
constructor() {
this.value = 0;
}
add(num) {
this.value += num;
return this;
}
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
it("should find fuzzy match for partial blocks", () => {
const fileContent = `function processData(input) {
const validated = validateInput(input);
const processed = transformData(validated);
const result = formatOutput(processed);
return result;
}`;
const searchContent = `const validated = validateInput(input);
const processed = transformData(validated);`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
});
describe("Edge cases with fuzzy matching", () => {
it("should handle empty search content with fuzzy matching enabled", () => {
const fileContent = `function test() {}`;
const searchContent = "";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
strategyName: "emptySearch",
});
});
it("should handle empty file content with fuzzy matching enabled", () => {
const fileContent = "";
const searchContent = "function test() {}";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should prefer exact match over fuzzy match", () => {
const fileContent = `function test() { return true; }
function test() { return false; }`;
const searchContent = `function test() { return true; }`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
expect(result?.startIndex).toBe(0);
});
it("should handle very short strings", () => {
const fileContent = `a b c`;
const searchContent = `a c`;
const result = findSearchMatch(fileContent, searchContent);
// Should not match due to low similarity
expect(result).toBeNull();
});
it("should handle special characters in fuzzy matching", () => {
const fileContent = `const regex = /[a-zA-Z]+/g;
const symbols = !@#$%^&*();`;
const searchContent = `const regex = /[a-zA-Z0-9]+/g;
const symbols = !@#$%^&*();`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).not.toBeNull();
});
});
});
});

View file

@ -144,161 +144,6 @@ function whitespaceIgnoredMatch(
};
}
/**
* Calculate the Jaro similarity between two strings
*/
function jaroSimilarity(s1: string, s2: string): number {
if (s1 === s2) return 1.0;
if (s1.length === 0 || s2.length === 0) return 0.0;
const matchDistance = Math.floor(Math.max(s1.length, s2.length) / 2) - 1;
if (matchDistance < 0) return 0.0;
const s1Matches = new Array(s1.length).fill(false);
const s2Matches = new Array(s2.length).fill(false);
let matches = 0;
let transpositions = 0;
// Find matches
for (let i = 0; i < s1.length; i++) {
const start = Math.max(0, i - matchDistance);
const end = Math.min(i + matchDistance + 1, s2.length);
for (let j = start; j < end; j++) {
if (s2Matches[j] || s1[i] !== s2[j]) continue;
s1Matches[i] = true;
s2Matches[j] = true;
matches++;
break;
}
}
if (matches === 0) return 0.0;
// Count transpositions
let k = 0;
for (let i = 0; i < s1.length; i++) {
if (!s1Matches[i]) continue;
while (!s2Matches[k]) k++;
if (s1[i] !== s2[k]) transpositions++;
k++;
}
return (
(matches / s1.length +
matches / s2.length +
(matches - transpositions / 2) / matches) /
3.0
);
}
/**
* Calculate the Jaro-Winkler similarity between two strings
*/
function jaroWinklerSimilarity(
s1: string,
s2: string,
prefixScale = 0.1,
): number {
const jaroSim = jaroSimilarity(s1, s2);
if (jaroSim < 0.7) return jaroSim;
// Calculate common prefix length (up to 4 characters)
let prefixLength = 0;
const maxPrefix = Math.min(4, Math.min(s1.length, s2.length));
for (let i = 0; i < maxPrefix; i++) {
if (s1[i] === s2[i]) {
prefixLength++;
} else {
break;
}
}
return jaroSim + prefixLength * prefixScale * (1 - jaroSim);
}
/**
* Find the best fuzzy match for search content in file content using Jaro-Winkler
*/
function findFuzzyMatch(
fileContent: string,
searchContent: string,
threshold: number = 0.9,
): BasicMatchResult | null {
const searchLines = searchContent.split("\n");
const fileLines = fileContent.split("\n");
let bestMatch: BasicMatchResult | null = null;
let bestSimilarity = 0;
// Try matching the search content as a whole block
const searchBlock = searchContent.trim();
if (searchBlock.length > 5) {
// Require minimum length for meaningful matches
// Use sliding window approach for multi-line search
for (let i = 0; i <= fileLines.length - searchLines.length; i++) {
const candidateLines = fileLines.slice(i, i + searchLines.length);
const candidateBlock = candidateLines.join("\n").trim();
if (candidateBlock.length < 5) continue; // Skip very short blocks
const similarity = jaroWinklerSimilarity(searchBlock, candidateBlock);
if (similarity >= threshold && similarity > bestSimilarity) {
// Calculate character positions
const linesBeforeMatch = fileLines.slice(0, i);
const startIndex =
linesBeforeMatch.join("\n").length +
(linesBeforeMatch.length > 0 ? 1 : 0);
const endIndex = startIndex + candidateBlock.length;
bestMatch = {
startIndex,
endIndex,
};
bestSimilarity = similarity;
}
}
}
// Also try line-by-line matching for better granularity
for (
let searchLineIdx = 0;
searchLineIdx < searchLines.length;
searchLineIdx++
) {
const searchLine = searchLines[searchLineIdx].trim();
if (searchLine.length === 0 || searchLine.length < 3) continue; // Skip very short lines
for (let fileLineIdx = 0; fileLineIdx < fileLines.length; fileLineIdx++) {
const fileLine = fileLines[fileLineIdx].trim();
if (fileLine.length === 0 || fileLine.length < 3) continue; // Skip very short lines
const similarity = jaroWinklerSimilarity(searchLine, fileLine);
if (similarity >= threshold && similarity > bestSimilarity) {
// Calculate character positions for the line
const linesBeforeMatch = fileLines.slice(0, fileLineIdx);
const startIndex =
linesBeforeMatch.join("\n").length +
(linesBeforeMatch.length > 0 ? 1 : 0);
const endIndex = startIndex + fileLines[fileLineIdx].length;
bestMatch = {
startIndex,
endIndex,
};
bestSimilarity = similarity;
}
}
}
return bestMatch;
}
/**
* Ordered list of matching strategies to try with their names
*/
@ -306,7 +151,6 @@ const matchingStrategies: Array<{ strategy: MatchStrategy; name: string }> = [
{ strategy: exactMatch, name: "exactMatch" },
{ strategy: trimmedMatch, name: "trimmedMatch" },
{ strategy: whitespaceIgnoredMatch, name: "whitespaceIgnoredMatch" },
{ strategy: findFuzzyMatch, name: "jaroWinklerFuzzyMatch" },
];
/**

1
core/index.d.ts vendored
View file

@ -1682,6 +1682,7 @@ export interface Config {
experimental?: ExperimentalConfig;
/** Analytics configuration */
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
data?: DataDestination[];
}

View file

@ -64,8 +64,8 @@ class TestCodebaseIndexer extends CodebaseIndexer {
}
// Add public methods to test private methods
public testHasCodebaseContextProvider() {
return (this as any).hasCodebaseContextProvider();
public testHasIndexingProvider() {
return (this as any).hasIndexingContextProvider();
}
public async testHandleConfigUpdate(
@ -202,7 +202,7 @@ describe("CodebaseIndexer", () => {
test("should have indexed all of the files", async () => {
const indexed = await getAllIndexedFiles();
expect(indexed.length).toBe(4); // Files are indexed twice due to test execution
expect(indexed.length).toBe(2);
expect(indexed.some((file) => file.endsWith("test.ts"))).toBe(true);
expect(indexed.some((file) => file.endsWith("main.py"))).toBe(true);
});
@ -226,7 +226,7 @@ describe("CodebaseIndexer", () => {
// Check that the new file was indexed
const files = await getAllIndexedFiles();
expect(files.length).toBe(5); // Updated to match actual behavior
expect(files.length).toBe(3);
expect(files.some((file) => file.endsWith("main.rs"))).toBe(true);
});
@ -240,7 +240,7 @@ describe("CodebaseIndexer", () => {
// Check that the deleted file was removed from the index
const files = await getAllIndexedFiles();
expect(files.length).toBe(4); // Updated to match actual behavior
expect(files.length).toBe(2);
expect(files.every((file) => !file.endsWith("main.rs"))).toBe(true);
});
@ -474,20 +474,14 @@ describe("CodebaseIndexer", () => {
jest.clearAllMocks();
});
describe("hasCodebaseContextProvider", () => {
describe("hasIndexingProvider", () => {
test("should return true when codebase context provider is present", () => {
// Set up config with codebase context provider
(testIndexer as any).config = {
contextProviders: [
{
description: {
title: CodebaseContextProvider.description.title,
},
},
],
contextProviders: [new CodebaseContextProvider({})],
};
const result = testIndexer.testHasCodebaseContextProvider();
const result = testIndexer.testHasIndexingProvider();
expect(result).toBe(true);
});
@ -496,7 +490,7 @@ describe("CodebaseIndexer", () => {
contextProviders: undefined,
};
const result = testIndexer.testHasCodebaseContextProvider();
const result = testIndexer.testHasIndexingProvider();
expect(result).toBe(false);
});
@ -511,7 +505,7 @@ describe("CodebaseIndexer", () => {
],
};
const result = testIndexer.testHasCodebaseContextProvider();
const result = testIndexer.testHasIndexingProvider();
expect(result).toBe(false);
});
@ -520,7 +514,7 @@ describe("CodebaseIndexer", () => {
contextProviders: [],
};
const result = testIndexer.testHasCodebaseContextProvider();
const result = testIndexer.testHasIndexingProvider();
expect(result).toBe(false);
});
});
@ -535,9 +529,8 @@ describe("CodebaseIndexer", () => {
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, so we want them to not get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(0);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(0);
});
test("should return early when newConfig is undefined", async () => {
@ -549,9 +542,8 @@ describe("CodebaseIndexer", () => {
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, so we want them to not get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(0);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(0);
});
test("should return early when no codebase context provider is present", async () => {
@ -577,21 +569,14 @@ describe("CodebaseIndexer", () => {
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, so we want them to not get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(0);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(0);
});
test("should return early when no embed model is configured", async () => {
const configResult: ConfigResult<ContinueConfig> = {
config: {
contextProviders: [
{
description: {
title: CodebaseContextProvider.description.title,
},
},
],
contextProviders: [new CodebaseContextProvider({})],
selectedModelByRole: {
embed: undefined,
},
@ -602,21 +587,14 @@ describe("CodebaseIndexer", () => {
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, so we want them to not get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(0);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(0);
});
test("should call refreshCodebaseIndex when all conditions are met", async () => {
const configResult: ConfigResult<ContinueConfig> = {
config: {
contextProviders: [
{
description: {
title: CodebaseContextProvider.description.title,
},
},
],
contextProviders: [new CodebaseContextProvider({})],
selectedModelByRole: {
embed: {
model: "test-model",
@ -630,9 +608,8 @@ describe("CodebaseIndexer", () => {
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, and we want them to get called again
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(2);
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
"/test/workspace",
]);
@ -640,13 +617,7 @@ describe("CodebaseIndexer", () => {
test("should set config property before checking conditions", async () => {
const testConfig = {
contextProviders: [
{
description: {
title: CodebaseContextProvider.description.title,
},
},
],
contextProviders: [new CodebaseContextProvider({})],
selectedModelByRole: {
embed: {
model: "test-model",
@ -666,7 +637,7 @@ describe("CodebaseIndexer", () => {
// Verify that the config was set
expect((testIndexer as any).config).toBe(testConfig);
// These get called once on init, and we want them to get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
});
test("should handle multiple context providers correctly", async () => {
@ -678,11 +649,7 @@ describe("CodebaseIndexer", () => {
title: "SomeOtherProvider",
},
},
{
description: {
title: CodebaseContextProvider.description.title,
},
},
new CodebaseContextProvider({}),
{
description: {
title: "AnotherProvider",
@ -702,8 +669,7 @@ describe("CodebaseIndexer", () => {
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, and we want them to get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
"/test/workspace",
]);

View file

@ -16,7 +16,6 @@ import { Telemetry } from "../util/posthog.js";
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
import { ConfigResult } from "@continuedev/config-yaml";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js";
import { ContinueServerClient } from "../continueServer/stubs/client";
import { LLMError } from "../llm/index.js";
import { getRootCause } from "../util/errors.js";
@ -804,11 +803,9 @@ export class CodebaseIndexer {
return this.codebaseIndexingState;
}
private hasCodebaseContextProvider() {
private hasIndexingContextProvider() {
return !!this.config.contextProviders?.some(
(provider) =>
provider.description.title ===
CodebaseContextProvider.description.title,
({ description: { dependsOnIndexing } }) => dependsOnIndexing,
);
}
@ -837,8 +834,8 @@ export class CodebaseIndexer {
this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in
// No point in indexing if no codebase context provider
const hasCodebaseContextProvider = this.hasCodebaseContextProvider();
if (!hasCodebaseContextProvider) {
const hasIndexingProviders = this.hasIndexingContextProvider();
if (!hasIndexingProviders) {
return;
}

View file

@ -0,0 +1,26 @@
import fs from "fs";
import { IDE } from "..";
import { getGlobalContinueIgnorePath } from "../util/paths";
import { gitIgArrayFromFile } from "./ignore";
export const getGlobalContinueIgArray = () => {
const contents = fs.readFileSync(getGlobalContinueIgnorePath(), "utf8");
return gitIgArrayFromFile(contents);
};
export const getWorkspaceContinueIgArray = async (ide: IDE) => {
const dirs = await ide.getWorkspaceDirs();
return await dirs.reduce(
async (accPromise, dir) => {
const acc = await accPromise;
try {
const contents = await ide.readFile(`${dir}/.continueignore`);
return [...acc, ...gitIgArrayFromFile(contents)];
} catch (err) {
console.error(err);
return acc;
}
},
Promise.resolve([] as string[]),
);
};

View file

@ -1,11 +1,108 @@
import fs from "fs";
import ignore from "ignore";
import { IDE } from "..";
import { getGlobalContinueIgnorePath } from "../util/paths";
import path from "path";
import { fileURLToPath } from "url";
export const DEFAULT_IGNORE_FILETYPES = [
// Security-focused ignore patterns - these should always be excluded for security reasons
export const DEFAULT_SECURITY_IGNORE_FILETYPES = [
// Environment and configuration files with secrets
"*.env",
"*.env.*",
".env*",
"config.json",
"config.yaml",
"config.yml",
"settings.json",
"appsettings.json",
"appsettings.*.json",
// Certificate and key files
"*.key",
"*.pem",
"*.p12",
"*.pfx",
"*.crt",
"*.cer",
"*.jks",
"*.keystore",
"*.truststore",
// Database files that may contain sensitive data
"*.db",
"*.sqlite",
"*.sqlite3",
"*.mdb",
"*.accdb",
// Credential and secret files
"*.secret",
"*.secrets",
"credentials",
"credentials.*",
"auth.json",
"token",
"token.*",
"*.token",
// Backup files that might contain sensitive data
"*.bak",
"*.backup",
"*.old",
"*.orig",
// Docker secrets
"docker-compose.override.yml",
"docker-compose.override.yaml",
// SSH and GPG
"id_rsa",
"id_dsa",
"id_ecdsa",
"id_ed25519",
"*.ppk",
"*.gpg",
];
export const DEFAULT_SECURITY_IGNORE_DIRS = [
// Environment and configuration directories
".env/",
"env/",
".venv/",
"venv/",
// IDE directories that may contain cached credentials
// For now excluding, reasons for this unclear
// ".vscode/",
// ".idea/",
// ".vs/",
// Cloud provider credential directories
".aws/",
".gcp/",
".azure/",
".kube/",
".docker/",
// Secret directories
"secrets/",
".secrets/",
"private/",
".private/",
"certs/",
"certificates/",
"keys/",
".ssh/",
".gnupg/",
".gpg/",
// Temporary directories that might contain sensitive data
"tmp/secrets/",
"temp/secrets/",
".tmp/",
];
// Additional non-security patterns for general indexing exclusion
export const ADDITIONAL_INDEXING_IGNORE_FILETYPES = [
"*.DS_Store",
"*-lock.json",
"*.lock",
@ -46,8 +143,6 @@ export const DEFAULT_IGNORE_FILETYPES = [
"*.mpeg",
"*.mov",
"*.mp3",
"*.mp4",
"*.mkv",
"*.mkv",
"*.webm",
"*.jar",
@ -56,20 +151,15 @@ export const DEFAULT_IGNORE_FILETYPES = [
"*.pqt",
"*.wav",
"*.webp",
"*.db",
"*.sqlite",
"*.wasm",
"*.plist",
"*.profraw",
"*.gcda",
"*.gcno",
"go.sum",
"*.env",
"*.gitignore",
"*.gitkeep",
"*.continueignore",
"config.json",
"config.yaml",
"*.csv",
"*.uasset",
"*.pdb",
@ -80,17 +170,9 @@ export const DEFAULT_IGNORE_FILETYPES = [
// "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt
];
export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES);
export const DEFAULT_IGNORE_DIRS = [
export const ADDITIONAL_INDEXING_IGNORE_DIRS = [
".git/",
".svn/",
".vscode/",
".idea/",
".vs/",
"venv/",
".venv/",
"env/",
".env/",
"node_modules/",
"dist/",
"build/",
@ -100,7 +182,6 @@ export const DEFAULT_IGNORE_DIRS = [
"bin/",
".pytest_cache/",
".vscode-test/",
".continue/",
"__pycache__/",
"site-packages/",
".gradle/",
@ -110,40 +191,75 @@ export const DEFAULT_IGNORE_DIRS = [
"vendor/",
];
// Combined patterns: security + additional
export const DEFAULT_IGNORE_FILETYPES = [
...DEFAULT_SECURITY_IGNORE_FILETYPES,
...ADDITIONAL_INDEXING_IGNORE_FILETYPES,
];
export const DEFAULT_IGNORE_DIRS = [
...DEFAULT_SECURITY_IGNORE_DIRS,
...ADDITIONAL_INDEXING_IGNORE_DIRS,
];
// Create ignore instances
export const defaultSecurityIgnoreFile = ignore().add(
DEFAULT_SECURITY_IGNORE_FILETYPES,
);
export const defaultSecurityIgnoreDir = ignore().add(
DEFAULT_SECURITY_IGNORE_DIRS,
);
export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES);
export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS);
// String representations
export const DEFAULT_SECURITY_IGNORE =
DEFAULT_SECURITY_IGNORE_FILETYPES.join("\n") +
"\n" +
DEFAULT_SECURITY_IGNORE_DIRS.join("\n");
export const DEFAULT_IGNORE =
DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n");
// Combined ignore instances
export const defaultFileAndFolderSecurityIgnores = ignore()
.add(defaultSecurityIgnoreFile)
.add(defaultSecurityIgnoreDir);
export const defaultIgnoreFileAndDir = ignore()
.add(defaultIgnoreFile)
.add(defaultIgnoreDir);
export function isSecurityConcern(filePathOrUri: string) {
if (!filePathOrUri) {
return false;
}
let filepath = filePathOrUri;
try {
filepath = fileURLToPath(filePathOrUri);
} catch {}
if (path.isAbsolute(filepath)) {
const dir = path.dirname(filepath).split(/\/|\\/).at(-1) ?? "";
const basename = path.basename(filepath);
filepath = `${dir ? dir + "/" : ""}${basename}`;
}
if (!filepath) {
return false;
}
return defaultFileAndFolderSecurityIgnores.ignores(filepath);
}
export function throwIfFileIsSecurityConcern(filepath: string) {
if (isSecurityConcern(filepath)) {
throw new Error(
`Reading or Editing ${filepath} is not allowed because it is a security concern. Do not attempt to read or edit this file in any way.`,
);
}
}
export function gitIgArrayFromFile(file: string) {
return file
.split(/\r?\n/) // Split on new line
.map((l) => l.trim()) // Remove whitespace
.filter((l) => !/^#|^$/.test(l)); // Remove empty lines
}
export const getGlobalContinueIgArray = () => {
const contents = fs.readFileSync(getGlobalContinueIgnorePath(), "utf8");
return gitIgArrayFromFile(contents);
};
export const getWorkspaceContinueIgArray = async (ide: IDE) => {
const dirs = await ide.getWorkspaceDirs();
return await dirs.reduce(
async (accPromise, dir) => {
const acc = await accPromise;
try {
const contents = await ide.readFile(`${dir}/.continueignore`);
return [...acc, ...gitIgArrayFromFile(contents)];
} catch (err) {
console.error(err);
return acc;
}
},
Promise.resolve([] as string[]),
);
};

View file

@ -0,0 +1,268 @@
import { describe, expect, it } from "vitest";
import {
DEFAULT_SECURITY_IGNORE_DIRS,
DEFAULT_SECURITY_IGNORE_FILETYPES,
defaultFileAndFolderSecurityIgnores,
isSecurityConcern,
} from "./ignore";
describe("isSecurityConcern", () => {
describe("Security file types", () => {
it("should detect environment files as security concerns", () => {
expect(isSecurityConcern(".env")).toBe(true);
expect(isSecurityConcern(".env.local")).toBe(true);
expect(isSecurityConcern(".env.production")).toBe(true);
expect(isSecurityConcern("config/.env")).toBe(true);
expect(isSecurityConcern("/path/to/.env")).toBe(true);
expect(isSecurityConcern("file:///path/to/.env")).toBe(true);
});
it("should detect configuration files as security concerns", () => {
expect(isSecurityConcern("config.json")).toBe(true);
expect(isSecurityConcern("config.yaml")).toBe(true);
expect(isSecurityConcern("config.yml")).toBe(true);
expect(isSecurityConcern("settings.json")).toBe(true);
expect(isSecurityConcern("appsettings.json")).toBe(true);
expect(isSecurityConcern("appsettings.development.json")).toBe(true);
expect(isSecurityConcern("appsettings.production.json")).toBe(true);
});
it("should detect certificate and key files as security concerns", () => {
expect(isSecurityConcern("private.key")).toBe(true);
expect(isSecurityConcern("certificate.pem")).toBe(true);
expect(isSecurityConcern("server.crt")).toBe(true);
expect(isSecurityConcern("keystore.jks")).toBe(true);
expect(isSecurityConcern("ssl/server.key")).toBe(true);
expect(isSecurityConcern("/etc/ssl/certs/server.pem")).toBe(true);
});
it("should detect database files as security concerns", () => {
expect(isSecurityConcern("database.db")).toBe(true);
expect(isSecurityConcern("users.sqlite")).toBe(true);
expect(isSecurityConcern("data.sqlite3")).toBe(true);
expect(isSecurityConcern("app.mdb")).toBe(true);
expect(isSecurityConcern("data/users.db")).toBe(true);
});
it("should detect credential files as security concerns", () => {
expect(isSecurityConcern("app.secret")).toBe(true);
expect(isSecurityConcern("api.secrets")).toBe(true);
expect(isSecurityConcern("credentials")).toBe(true);
expect(isSecurityConcern("credentials.json")).toBe(true);
expect(isSecurityConcern("auth.json")).toBe(true);
expect(isSecurityConcern("token")).toBe(true);
expect(isSecurityConcern("api.token")).toBe(true);
expect(isSecurityConcern("access.token")).toBe(true);
});
it("should detect backup files as security concerns", () => {
expect(isSecurityConcern("database.bak")).toBe(true);
expect(isSecurityConcern("config.backup")).toBe(true);
expect(isSecurityConcern("settings.old")).toBe(true);
expect(isSecurityConcern("app.orig")).toBe(true);
});
it("should detect Docker override files as security concerns", () => {
expect(isSecurityConcern("docker-compose.override.yml")).toBe(true);
expect(isSecurityConcern("docker-compose.override.yaml")).toBe(true);
});
it("should detect SSH and GPG files as security concerns", () => {
expect(isSecurityConcern("id_rsa")).toBe(true);
expect(isSecurityConcern("id_dsa")).toBe(true);
expect(isSecurityConcern("id_ecdsa")).toBe(true);
expect(isSecurityConcern("id_ed25519")).toBe(true);
expect(isSecurityConcern("private.ppk")).toBe(true);
expect(isSecurityConcern("secret.gpg")).toBe(true);
});
});
describe("Security directories", () => {
it("should detect environment directories as security concerns", () => {
expect(isSecurityConcern(".env/")).toBe(true);
expect(isSecurityConcern("env/")).toBe(true);
expect(isSecurityConcern(".venv/")).toBe(true);
expect(isSecurityConcern("venv/")).toBe(true);
expect(isSecurityConcern(".env/config")).toBe(true);
expect(isSecurityConcern("project/.venv/lib")).toBe(true);
});
it("should detect IDE directories as security concerns", () => {
// expect(isSecurityConcern(".vscode/")).toBe(true);
// expect(isSecurityConcern(".idea/")).toBe(true);
// expect(isSecurityConcern(".vs/")).toBe(true);
expect(isSecurityConcern(".vscode/settings.json")).toBe(true);
// expect(isSecurityConcern(".idea/workspace.xml")).toBe(true);
});
it("should detect cloud provider directories as security concerns", () => {
expect(isSecurityConcern(".aws/")).toBe(true);
expect(isSecurityConcern(".gcp/")).toBe(true);
expect(isSecurityConcern(".azure/")).toBe(true);
expect(isSecurityConcern(".kube/")).toBe(true);
expect(isSecurityConcern(".docker/")).toBe(true);
expect(isSecurityConcern(".aws/credentials")).toBe(true);
expect(isSecurityConcern(".kube/config")).toBe(true);
});
it("should detect secret directories as security concerns", () => {
expect(isSecurityConcern("secrets/")).toBe(true);
expect(isSecurityConcern(".secrets/")).toBe(true);
expect(isSecurityConcern("private/")).toBe(true);
expect(isSecurityConcern(".private/")).toBe(true);
expect(isSecurityConcern("certs/")).toBe(true);
expect(isSecurityConcern("certificates/")).toBe(true);
expect(isSecurityConcern("keys/")).toBe(true);
expect(isSecurityConcern(".ssh/")).toBe(true);
expect(isSecurityConcern(".gnupg/")).toBe(true);
expect(isSecurityConcern(".gpg/")).toBe(true);
});
it("should detect continue directory as security concern", () => {
expect(isSecurityConcern(".continue/config.json")).toBe(true);
});
it("should detect temporary secret directories as security concerns", () => {
expect(isSecurityConcern("tmp/secrets/")).toBe(true);
expect(isSecurityConcern("temp/secrets/")).toBe(true);
expect(isSecurityConcern(".tmp/")).toBe(true);
expect(isSecurityConcern("tmp/secrets/api.key")).toBe(true);
});
});
describe("Path variations", () => {
it("should handle absolute paths", () => {
expect(isSecurityConcern("/home/user/.env")).toBe(true);
expect(isSecurityConcern("/var/www/.secrets/")).toBe(true);
expect(isSecurityConcern("/etc/ssl/private.key")).toBe(true);
});
it("should handle URI schemes", () => {
expect(isSecurityConcern("file:///home/user/.env")).toBe(true);
expect(isSecurityConcern("file:///var/secrets/api.key")).toBe(true);
});
it("should handle nested paths", () => {
expect(isSecurityConcern("project/config/.env")).toBe(true);
expect(isSecurityConcern("src/main/resources/application.secret")).toBe(
true,
);
expect(isSecurityConcern("backend/certs/server.key")).toBe(true);
});
// it("should handle Windows-style paths", () => {
// expect(isSecurityConcern("C:\\Users\\user\\.env")).toBe(true);
// expect(isSecurityConcern("D:\\projects\\app\\secrets\\")).toBe(true);
// });
});
describe("Non-security files", () => {
it("should not flag regular source code files", () => {
expect(isSecurityConcern("src/main.js")).toBe(false);
expect(isSecurityConcern("components/App.tsx")).toBe(false);
expect(isSecurityConcern("utils/helper.py")).toBe(false);
expect(isSecurityConcern("models/User.java")).toBe(false);
expect(isSecurityConcern("styles/main.css")).toBe(false);
});
it("should not flag regular configuration files", () => {
expect(isSecurityConcern("package.json")).toBe(false);
expect(isSecurityConcern("tsconfig.json")).toBe(false);
expect(isSecurityConcern("webpack.config.js")).toBe(false);
expect(isSecurityConcern("babel.config.js")).toBe(false);
expect(isSecurityConcern("jest.config.js")).toBe(false);
});
it("should not flag documentation files", () => {
expect(isSecurityConcern("README.md")).toBe(false);
expect(isSecurityConcern("CHANGELOG.md")).toBe(false);
expect(isSecurityConcern("docs/api.md")).toBe(false);
expect(isSecurityConcern("LICENSE")).toBe(false);
});
it("should not flag regular directories", () => {
expect(isSecurityConcern("src/")).toBe(false);
expect(isSecurityConcern("components/")).toBe(false);
expect(isSecurityConcern("utils/")).toBe(false);
expect(isSecurityConcern("tests/")).toBe(false);
expect(isSecurityConcern("docs/")).toBe(false);
});
it("should not flag files with similar names but different extensions", () => {
expect(isSecurityConcern("environment.js")).toBe(false);
expect(isSecurityConcern("config-template.json")).toBe(false);
expect(isSecurityConcern("secret-utils.js")).toBe(false);
expect(isSecurityConcern("token-validator.ts")).toBe(false);
});
});
describe("Edge cases", () => {
it("should handle empty strings", () => {
expect(isSecurityConcern("")).toBe(false);
});
it("should handle paths with only separators", () => {
expect(isSecurityConcern("/")).toBe(false);
});
it("should handle paths with multiple extensions", () => {
expect(isSecurityConcern("backup.env.old")).toBe(true); // matches *.old
expect(isSecurityConcern("config.json.bak")).toBe(true); // matches *.bak
expect(isSecurityConcern("server.key.backup")).toBe(true); // matches *.backup
});
it("should handle files in root vs subdirectories", () => {
expect(isSecurityConcern(".env")).toBe(true);
expect(isSecurityConcern("project/.env")).toBe(true);
expect(isSecurityConcern("deeply/nested/path/.env")).toBe(true);
});
});
describe("Pattern matching consistency", () => {
it("should match all defined security file patterns", () => {
// Test a sample from each category to ensure patterns work
DEFAULT_SECURITY_IGNORE_FILETYPES.forEach((pattern) => {
// Create a test file name that should match the pattern
let testFile: string;
if (pattern.startsWith("*.")) {
testFile = `test${pattern.substring(1)}`;
} else if (pattern.includes("*")) {
testFile = pattern.replace("*", "test");
} else {
testFile = pattern;
}
expect(isSecurityConcern(testFile)).toBe(true);
});
});
it("should match all defined security directory patterns", () => {
DEFAULT_SECURITY_IGNORE_DIRS.forEach((pattern) => {
// Test the directory pattern directly
expect(isSecurityConcern(pattern)).toBe(true);
// Test a file inside the directory
const fileInDir = `${pattern}testfile.txt`;
expect(isSecurityConcern(fileInDir)).toBe(true);
});
});
});
describe("Integration with ignore library", () => {
it("should use the same ignore instance as defaultFileAndFolderSecurityIgnores", () => {
// Test that our function uses the same logic as the exported ignore instance
const testFiles = [
".env",
"secrets/api.key",
".aws/credentials",
"regular-file.js",
];
testFiles.forEach((file) => {
const functionResult = isSecurityConcern(file);
const ignoreResult = defaultFileAndFolderSecurityIgnores.ignores(file);
expect(functionResult).toBe(ignoreResult);
});
});
});
});

View file

@ -1,7 +1,8 @@
import ignore from "ignore";
import type { FileType, IDE } from "../";
import { findUriInDirs, getUriPathBasename } from "../util/uri";
import { defaultIgnoreFileAndDir, getGlobalContinueIgArray } from "./ignore";
import { getGlobalContinueIgArray } from "./continueignore";
import { defaultIgnoreFileAndDir } from "./ignore";
import { getIgnoreContext } from "./walkDir";
/*

View file

@ -3,11 +3,8 @@ import ignore, { Ignore } from "ignore";
import type { FileType, IDE } from "..";
import { joinPathsToUri } from "../util/uri";
import {
defaultIgnoreFileAndDir,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "./ignore";
import { getGlobalContinueIgArray } from "./continueignore";
import { defaultIgnoreFileAndDir, gitIgArrayFromFile } from "./ignore";
export interface WalkerOptions {
include?: "dirs" | "files" | "both";

View file

@ -177,6 +177,7 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired(
// NOTE: When updating this list,
// update core/nextEdit/templating/NextEditPromptEngine.ts as well.
const MODEL_SUPPORTS_NEXT_EDIT: string[] = [
NEXT_EDIT_MODELS.MERCURY_CODER,
NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
NEXT_EDIT_MODELS.INSTINCT,
];

View file

@ -20,6 +20,7 @@ export enum LLMConfigurationStatuses {
}
export enum NEXT_EDIT_MODELS {
MERCURY_CODER = "mercury-coder",
MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit",
INSTINCT = "instinct",
}

View file

@ -145,6 +145,7 @@ function testLLM(
description: "Say Hello",
parameters: {
type: "object",
required: ["name"],
properties: {
name: {
type: "string",
@ -165,7 +166,7 @@ function testLLM(
},
)) {
const typedChunk = chunk as AssistantChatMessage;
if (!typedChunk.toolCalls) {
if (!typedChunk.toolCalls || typedChunk.toolCalls.length === 0) {
continue;
}
const toolCall = typedChunk.toolCalls[0];
@ -182,6 +183,15 @@ function testLLM(
}
}
// For Mistral, if no tool calls were received, skip the test
// as it may not support forced tool use
if (args === "" && llm.constructor.name === "Mistral") {
console.log(
"Mistral did not return tool calls, skipping assertion",
);
return;
}
const parsedArgs = JSON.parse(args);
expect(parsedArgs.name).toBe("Nate");
}),

View file

@ -1,6 +1,8 @@
import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import { ChatCompletionCreateParams } from "@continuedev/openai-adapters";
import { UNIQUE_TOKEN } from "../../nextEdit/constants.js";
import OpenAI from "./OpenAI.js";
/**
@ -32,6 +34,26 @@ class Inception extends OpenAI {
return true;
}
// It seems like this should be inherited automatically from the parent OpenAI class, but it sometimes doesn't.
// protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [
// "chat",
// "embed",
// "list",
// "rerank",
// "streamChat",
// "streamFim",
// ];
protected modifyChatBody(
body: ChatCompletionCreateParams,
): ChatCompletionCreateParams {
const hasNextEditCapability = this.capabilities?.nextEdit ?? false;
// Add the nextEdit parameter for Inception-specific routing.
(body as any).nextEdit = hasNextEditCapability;
return body;
}
async *_streamFim(
prefix: string,
suffix: string,
@ -67,6 +89,79 @@ class Inception extends OpenAI {
yield chunk.choices[0].text;
}
}
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
if (this.isNextEdit(messages)) {
messages = this.removeNextEditToken(messages);
// Use edit/completions endpoint.
const endpoint = new URL("edit/completions", this.apiBase);
const resp = await this.fetch(endpoint, {
method: "POST",
body: JSON.stringify({
model: options.model,
messages: messages,
max_tokens: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
stop: options.stop,
stream: true,
}),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
signal,
});
for await (const chunk of streamSse(resp)) {
if (chunk.choices?.[0]?.delta?.content) {
yield {
role: "assistant",
content: chunk.choices[0].delta.content,
};
}
}
} else {
// Use regular chat/completions endpoint - call parent OpenAI implementation.
yield* super._streamChat(messages, signal, options);
}
}
private isNextEdit(messages: ChatMessage[]): boolean {
// Check if any message contains the unique next edit token.
return messages.some(
(message) =>
typeof message.content === "string" &&
message.content.endsWith(UNIQUE_TOKEN),
);
}
private removeNextEditToken(messages: ChatMessage[]): ChatMessage[] {
const lastMessage = messages[messages.length - 1];
if (
typeof lastMessage?.content === "string" &&
lastMessage.content.endsWith(UNIQUE_TOKEN)
) {
const cleanedMessages = [...messages];
cleanedMessages[cleanedMessages.length - 1] = {
...lastMessage,
content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length),
};
return cleanedMessages;
}
return messages;
}
}
export default Inception;

View file

@ -101,15 +101,17 @@ export function toChatBody(
};
if (options.tools?.length) {
params.tools = options.tools.map((tool) => ({
type: tool.type,
function: {
name: tool.function.name,
description: tool.function.description,
parameters: tool.function.parameters,
strict: tool.function.strict,
},
}));
params.tools = options.tools
.filter((tool) => !tool.type || tool.type === "function")
.map((tool) => ({
type: tool.type,
function: {
name: tool.function.name,
description: tool.function.description,
parameters: tool.function.parameters,
strict: tool.function.strict,
},
}));
}
return params;
@ -158,7 +160,16 @@ export function fromChatResponse(response: ChatCompletion): ChatMessage {
return {
role: "assistant",
content: "",
toolCalls: message.tool_calls,
toolCalls: message.tool_calls
?.filter((tc) => !tc.type || tc.type === "function")
.map((tc) => ({
id: tc.id,
type: "function" as const,
function: {
name: (tc as any).function?.name,
arguments: (tc as any).function?.arguments,
},
})),
};
}
@ -179,18 +190,24 @@ export function fromChatCompletionChunk(
content: delta.content,
};
} else if (delta?.tool_calls) {
return {
role: "assistant",
content: "",
toolCalls: delta?.tool_calls.map((tool_call) => ({
const toolCalls = delta?.tool_calls
.filter((tool_call) => !tool_call.type || tool_call.type === "function")
.map((tool_call) => ({
id: tool_call.id,
type: tool_call.type,
type: "function" as const,
function: {
name: tool_call.function?.name,
arguments: tool_call.function?.arguments,
name: (tool_call as any).function?.name,
arguments: (tool_call as any).function?.arguments,
},
})),
};
}));
if (toolCalls.length > 0) {
return {
role: "assistant",
content: "",
toolCalls,
};
}
}
return undefined;

View file

@ -124,6 +124,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"nova-pro",
"nova-micro",
"nova-premier",
"gpt-oss",
].some((part) => model.toLowerCase().includes(part))
) {
return true;
@ -302,6 +303,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"meta-llama/llama-3-70b-instruct",
"arcee-ai/caller-large",
"nousresearch/hermes-3-llama-3.1-70b",
"moonshotai/kimi-k2",
];
for (const model of specificModels) {
if (model.toLowerCase() === model) {

View file

@ -30,14 +30,16 @@ import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js";
import { HelperVars } from "../autocomplete/util/HelperVars.js";
import { AutocompleteInput } from "../autocomplete/util/types.js";
import { myersDiff } from "../diff/myers.js";
import { isSecurityConcern } from "../indexing/ignore.js";
import { modelSupportsNextEdit } from "../llm/autodetect.js";
import { NEXT_EDIT_MODELS } from "../llm/constants.js";
import { countTokens } from "../llm/countTokens.js";
import { localPathOrUriToPath } from "../util/pathToUri.js";
import {
INSTINCT_SYSTEM_PROMPT,
MERCURY_CODE_TO_EDIT_OPEN,
MERCURY_SYSTEM_PROMPT,
MODEL_WINDOW_SIZES,
UNIQUE_TOKEN,
} from "./constants.js";
import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
import {
@ -284,6 +286,9 @@ export class NextEditProvider {
usingFullFileDiff: boolean;
},
): Promise<NextEditOutcome | undefined> {
if (isSecurityConcern(input.filepath)) {
return undefined;
}
try {
this.previousRequest = input;
const {
@ -392,9 +397,13 @@ export class NextEditProvider {
this.ide.getWorkspaceDirs(),
]);
const modelName = helper.modelName.includes("mercury-coder-nextedit")
? "mercury-coder-nextedit"
: "instinct";
const modelName = helper.modelName.includes(
NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT,
)
? NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT
: helper.modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER)
? NEXT_EDIT_MODELS.MERCURY_CODER
: NEXT_EDIT_MODELS.INSTINCT;
const { editableRegionStartLine, editableRegionEndLine } =
opts?.usingFullFileDiff
@ -551,7 +560,10 @@ export class NextEditProvider {
const modelName = helper.modelName;
let ctx: any;
if (modelName.includes("mercury-coder-nextedit")) {
if (
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
) {
ctx = {
recentlyViewedCodeSnippets:
snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({
@ -564,7 +576,7 @@ export class NextEditProvider {
editDiffHistory: this.diffContext,
currentFilePath: helper.filepath,
};
} else if (modelName.includes("instinct")) {
} else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) {
// Calculate the window around the cursor position (25 lines above and below).
const windowStart = Math.max(0, helper.pos.line - 25);
const windowEnd = Math.min(
@ -608,9 +620,11 @@ export class NextEditProvider {
const systemPrompt: Prompt = {
role: "system",
content: modelName.includes("mercury-coder-nextedit")
? MERCURY_SYSTEM_PROMPT
: INSTINCT_SYSTEM_PROMPT,
content:
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
? MERCURY_SYSTEM_PROMPT
: INSTINCT_SYSTEM_PROMPT,
};
return [systemPrompt, promptMetadata.prompt];
@ -677,25 +691,37 @@ export class NextEditProvider {
const llm = await this._prepareLlm();
if (!llm) return undefined;
const msg: ChatMessage = await llm.chat(prompts, token);
console.log("message");
console.log(msg.content);
// Check for mercury models, and inject unique token for next edit.
// Capture the unique tokens in llm Inception.ts and apis Inception.ts
const modelName = helper.modelName;
if (
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) ||
modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT)
) {
// Inject the unique token to the last prompt's content.
const lastPrompt = prompts[prompts.length - 1];
if (lastPrompt && typeof lastPrompt.content === "string") {
lastPrompt.content += UNIQUE_TOKEN;
}
}
const msg: ChatMessage = await llm.chat([prompts[1]], token, {
stream: false,
});
if (typeof msg.content !== "string") {
return undefined;
}
// const nextCompletion = msg.content.split(
// `${MERCURY_CODE_TO_EDIT_OPEN}\n`,
// )[1]
// ? replaceEscapedCharacters(
// msg.content.split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1],
// ).replace(/\n$/, "")
// : replaceEscapedCharacters(msg.content);
const nextCompletion =
msg.content
.split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1]
.replace(/\n$/, "") ?? msg.content;
// NOTE: Keep this in case there is a change in spec.
// const nextCompletion =
// msg.content
// .split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1]
// .replace(/\n$/, "") ?? msg.content;
const nextCompletion = msg.content.slice(
msg.content.indexOf("```\n") + "'''\n".length,
msg.content.lastIndexOf("\n\n```"),
);
if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
return await this._handlePartialFileDiff(

View file

@ -8,6 +8,10 @@ export const MODEL_WINDOW_SIZES: Record<
NEXT_EDIT_MODELS,
{ topMargin: number; bottomMargin: number }
> = {
"mercury-coder": {
topMargin: 0,
bottomMargin: 5,
}, // mercury coder uses full file diff, so this should be unnecessary
"mercury-coder-nextedit": {
topMargin: 0,
bottomMargin: 5,
@ -15,6 +19,8 @@ export const MODEL_WINDOW_SIZES: Record<
instinct: { topMargin: 1, bottomMargin: 5 },
};
export const UNIQUE_TOKEN = "<|!@#IS_NEXT_EDIT!@#|>";
// Model 1-specific tokens.
export const INSTINCT_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
export const INSTINCT_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";

View file

@ -11,6 +11,7 @@ import {
} from "../../autocomplete/util/types";
import { ConfigHandler } from "../../config/ConfigHandler";
import { IDE, ILLM } from "../../index";
import { isSecurityConcern } from "../../indexing/ignore";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../util/parameters";
/**
@ -61,6 +62,10 @@ export const getAutocompleteContext = async (
throw new Error("No config available");
}
if (isSecurityConcern(input.filepath)) {
throw new Error("File is a security concern, autocomplete disabled");
}
// Use provided autocomplete model or fall back to configured autocomplete model
let finalModel: ILLM;
let modelNameForTemplating: string;

View file

@ -39,11 +39,14 @@ import {
type TemplateRenderer = (vars: TemplateVars) => string;
const NEXT_EDIT_MODEL_TEMPLATES: Record<NEXT_EDIT_MODELS, NextEditTemplate> = {
"mercury-coder": {
template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`,
},
"mercury-coder-nextedit": {
template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`,
template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`,
},
instinct: {
template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`,
template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpt:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`,
},
};
@ -90,7 +93,7 @@ export async function renderPrompt(
let tv: TemplateVars;
switch (modelName) {
case "mercury-coder-nextedit": {
case NEXT_EDIT_MODELS.MERCURY_CODER: {
userEdits = ctx.editDiffHistory;
// editedCodeWithTokens = insertTokens(
@ -119,7 +122,36 @@ export async function renderPrompt(
break;
}
case "instinct": {
case NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT: {
userEdits = ctx.editDiffHistory;
// editedCodeWithTokens = insertTokens(
// helper.fileContents.split("\n"),
// helper.pos,
// MERCURY_CURSOR,
// );
const mercuryCtx: MercuryTemplateVars = {
recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
ctx.recentlyViewedCodeSnippets,
),
currentFileContent: currentFileContentBlock(
ctx.currentFileContent,
ctx.editableRegionStartLine,
ctx.editableRegionEndLine,
helper.pos,
),
editDiffHistory: editHistoryBlock(ctx.editDiffHistory),
currentFilePath: ctx.currentFilePath,
};
tv = mercuryCtx;
editedCodeWithTokens = mercuryCtx.currentFileContent;
break;
}
case NEXT_EDIT_MODELS.INSTINCT: {
userEdits = ctx.editDiffHistory;
// editedCodeWithTokens = insertTokens(

View file

@ -14,6 +14,8 @@ import {
MERCURY_EDIT_DIFF_HISTORY_OPEN,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN,
} from "../constants";
import {
renderDefaultSystemPrompt,
@ -31,7 +33,7 @@ describe("NextEditPromptEngine", () => {
beforeEach(() => {
mercuryHelper = {
modelName: "inception/mercury-coder-nextedit" as NEXT_EDIT_MODELS,
modelName: "inception/mercury-coder" as NEXT_EDIT_MODELS,
fileContents: "function test() {\n const a = 1;\n return a;\n}",
pos: { line: 1, character: 12 } as Position,
lang: { name: "typescript" },
@ -63,7 +65,7 @@ describe("NextEditPromptEngine", () => {
};
});
it("should render mercury-coder-nextedit prompt correctly", async () => {
it("should render mercury-coder prompt correctly", async () => {
const result = await renderPrompt(mercuryHelper, ctx);
expect(result).toHaveProperty("prompt");
@ -72,6 +74,8 @@ describe("NextEditPromptEngine", () => {
const content = result.prompt.content;
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN);
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE);
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN);
expect(content).toContain(MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE);
expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_OPEN);
expect(content).toContain(MERCURY_CURRENT_FILE_CONTENT_CLOSE);
expect(content).toContain(MERCURY_EDIT_DIFF_HISTORY_OPEN);
@ -106,7 +110,7 @@ describe("NextEditPromptEngine", () => {
expect(result.prompt.content).toContain(INSTINCT_USER_PROMPT_PREFIX);
expect(result.prompt.content).toContain("### Context:");
expect(result.prompt.content).toContain("### User Edits:");
expect(result.prompt.content).toContain("### User Excerpts:");
expect(result.prompt.content).toContain("### User Excerpt:");
expect(result.userEdits).toBe(instinctCtx.editDiffHistory);
expect(result.userExcerpts).toContain(INSTINCT_USER_CURSOR_IS_HERE_TOKEN);

View file

@ -3,6 +3,8 @@ import {
MERCURY_CODE_TO_EDIT_CLOSE,
MERCURY_CODE_TO_EDIT_OPEN,
MERCURY_CURSOR,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN,
} from "../constants";
import { insertCursorToken } from "./utils";
@ -11,8 +13,10 @@ export function recentlyViewedCodeSnippetsBlock(
) {
return recentlyViewedCodeSnippets.reduce((acc, snippet, i) => {
const block = [
MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN,
`code_snippet_file_path: ${snippet.filepath}`,
snippet.content,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE,
].join("\n");
return (

View file

@ -4,6 +4,8 @@ import {
MERCURY_CODE_TO_EDIT_CLOSE,
MERCURY_CODE_TO_EDIT_OPEN,
MERCURY_CURSOR,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE,
MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN,
} from "../constants";
import {
currentFileContentBlock,
@ -25,10 +27,14 @@ describe("mercuryCoderNextEdit", () => {
const result = recentlyViewedCodeSnippetsBlock(snippets);
const expected =
`${MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN}\n` +
"code_snippet_file_path: /path/to/file1.ts\n" +
"const a = 1;\n" +
`${MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE}\n` +
`${MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_OPEN}\n` +
"code_snippet_file_path: /path/to/file2.ts\n" +
"function test() { return true; }";
"function test() { return true; }\n" +
MERCURY_RECENTLY_VIEWED_CODE_SNIPPET_CLOSE;
expect(result).toBe(expected);
});

152
core/package-lock.json generated
View file

@ -44,7 +44,7 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"iconv-lite": "^0.6.3",
"ignore": "^5.3.1",
"ignore": "^7.0.5",
"is-localhost-ip": "^2.0.0",
"jinja-js": "0.1.8",
"js-tiktoken": "^1.0.8",
@ -57,7 +57,7 @@
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",
"onnxruntime-node": "1.14.0",
"openai": "^4.104.0",
"openai": "^5.13.1",
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",
@ -201,19 +201,19 @@
},
"../packages/openai-adapters": {
"name": "@continuedev/openai-adapters",
"version": "1.1.1",
"version": "1.5.1",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.842.0",
"@aws-sdk/credential-providers": "^3.840.0",
"@continuedev/config-types": "file:../config-types",
"@continuedev/config-yaml": "file:../config-yaml",
"@continuedev/fetch": "file:../fetch",
"@continuedev/config-types": "^1.0.14",
"@continuedev/config-yaml": "^1.8.0",
"@continuedev/fetch": "^1.0.16",
"dotenv": "^16.5.0",
"google-auth-library": "^10.1.0",
"json-schema": "^0.4.0",
"node-fetch": "^3.3.2",
"openai": "^4.104.0",
"openai": "^5.13.1",
"uuid": "^11.1.0",
"zod": "^3.24.2"
},
@ -3458,6 +3458,15 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/@eslint/eslintrc/node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
"license": "MIT",
"engines": {
"node": ">= 4"
}
},
"node_modules/@eslint/eslintrc/node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
@ -6789,6 +6798,7 @@
"version": "2.6.12",
"resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.12.tgz",
"integrity": "sha512-8nneRWKCg3rMtF69nLQJnOYUcbafYeFSjqkw3jCRLsqkWFlHaoQrr5mXmofFGOx3DKn7UfmBMyov8ySvLRVldA==",
"dev": true,
"dependencies": {
"@types/node": "*",
"form-data": "^4.0.0"
@ -7005,6 +7015,15 @@
}
}
},
"node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
"license": "MIT",
"engines": {
"node": ">= 4"
}
},
"node_modules/@typescript-eslint/parser": {
"version": "7.18.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.18.0.tgz",
@ -7439,6 +7458,7 @@
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.5.0.tgz",
"integrity": "sha512-5GG/5IbQQpC9FpkRGsSvZI5QYeSCzlJHdpBQntCsuTOxhKD8lqKhrleg2Yi7yvMIf82Ycmmqln9U8V9qwEiJew==",
"optional": true,
"dependencies": {
"humanize-ms": "^1.2.1"
},
@ -10575,6 +10595,15 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/eslint/node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
"license": "MIT",
"engines": {
"node": ">= 4"
}
},
"node_modules/eslint/node_modules/minimatch": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
@ -11243,31 +11272,6 @@
"node": ">= 6"
}
},
"node_modules/form-data-encoder": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz",
"integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A=="
},
"node_modules/formdata-node": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz",
"integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==",
"dependencies": {
"node-domexception": "1.0.0",
"web-streams-polyfill": "4.0.0-beta.3"
},
"engines": {
"node": ">= 12.20"
}
},
"node_modules/formdata-node/node_modules/web-streams-polyfill": {
"version": "4.0.0-beta.3",
"resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz",
"integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==",
"engines": {
"node": ">= 14"
}
},
"node_modules/formdata-polyfill": {
"version": "4.0.10",
"resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
@ -11702,6 +11706,15 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/globby/node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
"license": "MIT",
"engines": {
"node": ">= 4"
}
},
"node_modules/google-auth-library": {
"version": "9.15.0",
"resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.15.0.tgz",
@ -12120,6 +12133,7 @@
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz",
"integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==",
"optional": true,
"dependencies": {
"ms": "^2.0.0"
}
@ -12155,9 +12169,10 @@
]
},
"node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
"integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==",
"version": "7.0.5",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz",
"integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==",
"license": "MIT",
"engines": {
"node": ">= 4"
}
@ -15526,18 +15541,10 @@
}
},
"node_modules/openai": {
"version": "4.104.0",
"resolved": "https://registry.npmjs.org/openai/-/openai-4.104.0.tgz",
"integrity": "sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA==",
"dependencies": {
"@types/node": "^18.11.18",
"@types/node-fetch": "^2.6.4",
"abort-controller": "^3.0.0",
"agentkeepalive": "^4.2.1",
"form-data-encoder": "1.7.2",
"formdata-node": "^4.3.2",
"node-fetch": "^2.6.7"
},
"version": "5.13.1",
"resolved": "https://registry.npmjs.org/openai/-/openai-5.13.1.tgz",
"integrity": "sha512-Jty97Apw40znKSlXZL2YDap1U2eN9NfXbqm/Rj1rExeOLEnhwezpKQ+v43kIqojavUgm30SR3iuvGlNEBR+AFg==",
"license": "Apache-2.0",
"bin": {
"openai": "bin/cli"
},
@ -15554,52 +15561,6 @@
}
}
},
"node_modules/openai/node_modules/@types/node": {
"version": "18.19.67",
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.67.tgz",
"integrity": "sha512-wI8uHusga+0ZugNp0Ol/3BqQfEcCCNfojtO6Oou9iVNGPTL6QNSdnUdqq85fRgIorLhLMuPIKpsN98QE9Nh+KQ==",
"dependencies": {
"undici-types": "~5.26.4"
}
},
"node_modules/openai/node_modules/node-fetch": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/openai/node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
},
"node_modules/openai/node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
},
"node_modules/openai/node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/optionator": {
"version": "0.9.4",
"resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",
@ -19009,11 +18970,6 @@
"node": ">=18.17"
}
},
"node_modules/undici-types": {
"version": "5.26.5",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="
},
"node_modules/unicode-canonical-property-names-ecmascript": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-2.0.1.tgz",

View file

@ -85,7 +85,7 @@
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"iconv-lite": "^0.6.3",
"ignore": "^5.3.1",
"ignore": "^7.0.5",
"is-localhost-ip": "^2.0.0",
"jinja-js": "0.1.8",
"js-tiktoken": "^1.0.8",
@ -98,7 +98,7 @@
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",
"onnxruntime-node": "1.14.0",
"openai": "^4.104.0",
"openai": "^5.13.1",
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",

View file

@ -49,8 +49,8 @@ import {
ControlPlaneSessionInfo,
} from "../control-plane/AuthTypes";
import { FreeTrialStatus } from "../control-plane/client";
import { NextEditOutcome } from "../nextEdit/types";
import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue";
import { NextEditOutcome } from "../nextEdit/types";
export enum OnboardingModes {
API_KEY = "API Key",
@ -86,6 +86,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
];
"config/addLocalWorkspaceBlock": [{ blockType: BlockType }, void];
"config/newPromptFile": [undefined, void];
"config/newAssistantFile": [undefined, void];
"config/ideSettingsUpdate": [IdeSettings, void];
"config/getSerializedProfileInfo": [
undefined,

View file

@ -18,6 +18,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"devdata/log",
"config/addModel",
"config/newPromptFile",
"config/newAssistantFile",
"config/ideSettingsUpdate",
"config/addLocalWorkspaceBlock",
"config/getSerializedProfileInfo",

View file

@ -1,3 +1,5 @@
import ignore from "ignore";
import { ToolImpl } from ".";
import { walkDir } from "../../indexing/walkDir";
import { resolveRelativePathInDir } from "../../util/ideUtils";
@ -27,6 +29,7 @@ export const lsToolImpl: ToolImpl = async (args, extras) => {
returnRelativeUrisPaths: true,
include: "both",
recursive: args?.recursive ?? false,
overrideDefaultIgnores: ignore(), // Show all directories including dist/, build/, etc.
});
const lines = entries.slice(0, MAX_LS_TOOL_LINES);

View file

@ -1,12 +1,14 @@
import { getUriDescription } from "../../util/uri";
import { ToolImpl } from ".";
import { throwIfFileIsSecurityConcern } from "../../indexing/ignore";
import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => {
export const readCurrentlyOpenFileImpl: ToolImpl = async (_, extras) => {
const result = await extras.ide.getCurrentFile();
if (result) {
throwIfFileIsSecurityConcern(result.path);
await throwIfFileExceedsHalfOfContext(
result.path,
result.contents,

View file

@ -2,11 +2,13 @@ import { resolveRelativePathInDir } from "../../util/ideUtils";
import { getUriPathBasename } from "../../util/uri";
import { ToolImpl } from ".";
import { throwIfFileIsSecurityConcern } from "../../indexing/ignore";
import { getStringArg } from "../parseArgs";
import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
export const readFileImpl: ToolImpl = async (args, extras) => {
const filepath = getStringArg(args, "filepath");
throwIfFileIsSecurityConcern(filepath);
const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide);
if (!firstUriMatch) {

View file

@ -39,6 +39,7 @@ export type GlobalContextType = {
*/
hasDismissedConfigTsNoticeJetBrains: boolean;
hasAlreadyCreatedAPromptFile: boolean;
hasShownUnsupportedPlatformWarning: boolean;
showConfigUpdateToast: boolean;
isSupportedLanceDbCpuTargetForLinux: boolean;
sharedConfig: SharedConfigSchema;

View file

@ -9,7 +9,7 @@ import * as JSONC from "comment-json";
import dotenv from "dotenv";
import { IdeType, SerializedContinueConfig } from "../";
import { defaultConfig, defaultConfigJetBrains } from "../config/default";
import { defaultConfig } from "../config/default";
import Types from "../config/types";
dotenv.config();
@ -110,7 +110,10 @@ export function getConfigYamlPath(ideType?: IdeType): string {
const p = path.join(getContinueGlobalPath(), "config.yaml");
if (!fs.existsSync(p) && !fs.existsSync(getConfigJsonPath())) {
if (ideType === "jetbrains") {
fs.writeFileSync(p, YAML.stringify(defaultConfigJetBrains));
// https://github.com/continuedev/continue/pull/7224
// This was here because we had different context provider support between jetbrains and vs code
// Leaving so we could differentiate later but for now configs are the same between IDEs
fs.writeFileSync(p, YAML.stringify(defaultConfig));
} else {
fs.writeFileSync(p, YAML.stringify(defaultConfig));
}

View file

@ -1,4 +1,4 @@
import { Extras } from "@sentry/core";
import { Extras, type Integration, type Event } from "@sentry/core";
import * as Sentry from "@sentry/node";
import os from "node:os";
import { IdeInfo } from "../../index.js";
@ -25,7 +25,7 @@ export class SentryLogger {
// Filter integrations that use the global variable
const integrations = Sentry.getDefaultIntegrations({}).filter(
(defaultIntegration) => {
(defaultIntegration: Integration) => {
// Remove integrations that might interfere with shared environments
return ![
"OnUncaughtException",
@ -52,7 +52,7 @@ export class SentryLogger {
sendDefaultPii: false,
// Strip sensitive data and add basic properties before sending events
beforeSend(event) {
beforeSend(event: Event) {
// First apply anonymization
const anonymizedEvent = anonymizeSentryEvent(event);
if (!anonymizedEvent) return null;
@ -197,7 +197,7 @@ export function createSpan<T>(
}
// Use withScope from Sentry to isolate the span context
return Sentry.withScope((isolatedScope) => {
return Sentry.withScope((isolatedScope: Sentry.Scope) => {
isolatedScope.setClient(client);
return Sentry.startSpan(
{

View file

@ -1,4 +1,5 @@
import { ErrorEvent } from "@sentry/core";
import * as Sentry from "@sentry/node";
import { type Event } from "@sentry/core";
/**
* Minimalist Sentry anonymization utilities
*/
@ -75,7 +76,7 @@ export function anonymizeUserInfo(user: any): any {
/**
* Main anonymization function - minimalist approach like Rasa
*/
export function anonymizeSentryEvent(event: ErrorEvent): any | null {
export function anonymizeSentryEvent(event: any): any | null {
try {
// Deep copy to avoid mutating the original event
const anonymized = structuredClone(event);

View file

@ -12,6 +12,20 @@ description: "These blocks form the foundation of the entire assistant experienc
![Model Blocks Overview](/images/customization/images/model-blocks-overview-36c30e7e01928d7a9b5b26ff1639c34b.png)
## Recommended Models
### Best Models by Role
| Model role | Best open models | Best closed models | Notes |
|:------------|:------------------|:-------------------|:--------|
| Agent / Plan | Qwen 3 Coder (480B), Qwen 3 Coder (30B), Devstral (24B), GLM 4.5 (355B), GLM 4.5 Air (106B), Kimi K2 (1T), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed models are slightly better than open models |
| Chat / Edit | Qwen 3 Coder (480B), Qwen 3 Coder (30B), gpt-oss (120B), gpt-oss (20B) | [Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus), [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet), [GPT-5](https://hub.continue.dev/openai/gpt-5), [Gemini 2.5 Pro](https://hub.continue.dev/google/gemini-2.5-pro) | Closed and open models have pretty similar performance |
| Autocomplete | [QwenCoder2.5 (1.5B)](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b), QwenCoder2.5 (7B) | [Codestral](https://hub.continue.dev/mistral/codestral), Mercury Coder | Closed models are slightly better than open models |
| Apply | N/A | [Relace Instant Apply](https://hub.continue.dev/relace/instant-apply), [Morph Fast Apply](https://hub.continue.dev/morphllm/morph-v2) | Open models are basically non-existent / not good enough for this model role |
| Embed | N/A | [Voyage Code 3](https://hub.continue.dev/voyageai/voyage-code-3), [Morph Embeddings](https://hub.continue.dev/morphllm/morph-embedding-v2), Codestral Embed | Open models are basically non-existent / not good enough for this model role |
| Rerank | zerank-1, zerank-1-small | rerank-2.5, Relace Code Rerank, [Morph Rerank](https://hub.continue.dev/morphllm/morph-rerank-v2) | Open models are beginning to emerge for this model role |
| Next Edit | Zeta | Mercury Coder | Closed models are significantly better than open models |
## Learn More About Model Blocks
Continue supports [many model providers](/customize/model-providers/top-level/openai), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`.

View file

@ -5,6 +5,10 @@ keywords: [autocomplete]
sidebarTitle: Autocomplete
---
<Info>
For a comprehensive comparison of all autocomplete models, see our [model recommendations table](/customization/models#recommended-models).
</Info>
## How to Set Up Autocomplete in Continue with Codestral (Recommended)
If you want to have the best autocomplete experience, we recommend using Codestral, which is available through the [Mistral API](https://console.mistral.ai/). To do this, obtain an API key and add it to your config:

View file

@ -1,7 +1,7 @@
---
title: "How to Configure Inception with Continue"
slug: ../inception
description: "Configure Inception Labs models with Continue, featuring Mercury Coder Small for both chat and autocomplete functions, optimized for programming and code generation tasks"
description: "Configure Inception models with Continue, featuring Mercury Coder Small for both chat and autocomplete functions, optimized for programming and code generation tasks"
sidebarTitle: "Inception"
---

View file

@ -17,6 +17,10 @@ Models in Continue can be configured to be used for various roles in the extensi
These roles can be specified for a `config.yaml` model block using `roles`. See the [YAML Specification](/reference#models) for more details.
<Info>
For recommendations on which models work best for each role, see our [comprehensive model recommendations](/customization/models#recommended-models).
</Info>
## Selecting model roles
You can control which of the models in your assistant for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role.

View file

@ -9,6 +9,10 @@ When editing code, Chat and Edit model output often doesn't clearly align with e
## Recommended Apply models
<Info>
For the latest Apply model recommendations, see our [comprehensive model recommendations](/customization/models#recommended-models).
</Info>
We recommend [Morph Fast Apply](https://morphllm.com) or [Relace's Instant Apply model](https://hub.continue.dev/relace/instant-apply) for the fastest Apply experience. You can sign up for Morph's free tier [here](https://morphllm.com/dashboard) or get a Relace API key [here](https://app.relace.ai/settings/api-keys).
However, most Chat models can also be used for applying code changes. We recommend smaller/cheaper models for the task, such as Claude 3.5 Haiku.

View file

@ -12,7 +12,11 @@ In Continue, autocomplete models are used to display inline [Autocomplete](../..
## Recommended Autocomplete models
Visit the [Autocomplete Deep Dive](../deep-dives/autocomplete) for recommended models and more details.
<Info>
See our [comprehensive model recommendations](/customization/models#recommended-models) for the best autocomplete models, including both open and closed options.
</Info>
Visit the [Autocomplete Deep Dive](../deep-dives/autocomplete) for detailed setup instructions and configuration options.
## Prompt templating

View file

@ -11,24 +11,28 @@ In Continue, these models are used for normal [Chat](../../features/chat/quick-s
## Recommended Chat models
<Info>
For the latest and most comprehensive model recommendations, see our [model recommendations table](/customization/models#recommended-models).
</Info>
## Best overall experience
For the best overall Chat experience, you will want to use a 400B+ parameter model or one of the frontier models.
### Claude Sonnet 3.7 from Anthropic
### Claude Opus 4.1 and Claude Sonnet 4 from Anthropic
Our current top recommendation is Claude 3.7 Sonnet from [Anthropic](../model-providers/top-level/anthropic).
Our current top recommendations are Claude Opus 4.1 and Claude Sonnet 4 from [Anthropic](../model-providers/top-level/anthropic).
<Tabs>
<Tab title="Hub">
View the [Claude 3.7 Sonnet model block](https://hub.continue.dev/anthropic/claude-3-7-sonnet) on the hub.
View the [Claude Opus 4.1 model block](https://hub.continue.dev/anthropic/claude-4-1-opus) or [Claude Sonnet 4 model block](https://hub.continue.dev/anthropic/claude-4-sonnet) on the hub.
</Tab>
<Tab title="YAML">
```yaml title="config.yaml"
models:
- name: Claude 3.7 Sonnet
- name: Claude Opus 4.1
provider: anthropic
model: claude-3-7-sonnet-latest
model: claude-4-1-opus
apiKey: <YOUR_ANTHROPIC_API_KEY>
```
</Tab>
@ -37,9 +41,9 @@ Our current top recommendation is Claude 3.7 Sonnet from [Anthropic](../model-pr
{
"models": [
{
"title": "Claude 3.5 Sonnet",
"title": "Claude Opus 4.1",
"provider": "anthropic",
"model": "claude-3-5-sonnet-latest",
"model": "claude-4-1-opus",
"apiKey": "<YOUR_ANTHROPIC_API_KEY>"
}
]

View file

@ -44,6 +44,10 @@ In Continue, you can add `edit` to a model's roles to specify that it can be use
Explore edit models in [the hub](https://hub.continue.dev/explore/models?roles=edit). Generally, our recommendations for Edit overlap with recommendations for Chat.
<Info>
See our [comprehensive model recommendations](/customization/models#recommended-models) for the best models for Edit and Chat roles.
</Info>
## Prompt templating
You can customize the prompt template used for editing code by setting the `promptTemplates.edit` property in your model configuration. Continue uses [Handlebars syntax](https://handlebarsjs.com/guide/) for templating.

View file

@ -19,6 +19,10 @@ You can add `embed` to a model's `roles` to specify that it can be used to embed
## Recommended embedding models
<Info>
See our [comprehensive model recommendations](/customization/models#recommended-models) for the best embedding models comparison.
</Info>
If you have the ability to use any model, we recommend `voyage-code-3`, which is listed below along with the rest of the options for embeddings models.
If you want to generate embeddings locally, we recommend using `nomic-embed-text` with [Ollama](../model-providers/top-level/ollama#embeddings-model).

View file

@ -11,6 +11,10 @@ In Continue, rerankers are designated using the `rerank` role and used by [@Code
## Recommended reranking models
<Info>
For a comparison of all reranking models including open and closed options, see our [comprehensive model recommendations](/customization/models#recommended-models).
</Info>
If you have the ability to use any model, we recommend `rerank-2` by Voyage AI, which is listed below along with the rest of the options for rerankers.
### Voyage AI

View file

@ -6,6 +6,10 @@ sidebarTitle: "Model Setup"
The models you set up for Chat mode will be used with Agent mode if the model supports tool calling. The recommended models and how to set them up can be found [here](/features/chat/model-setup).
<Info>
For the latest recommendations on the best models for Agent/Plan mode, see our [comprehensive model recommendations](/customization/models#recommended-models).
</Info>
## How System Message Tools Work
<Info>

View file

@ -6,6 +6,10 @@ sidebarTitle: "Recommended Autocomplete Models"
Setting up the right model for autocomplete is crucial for a smooth coding experience. Here are our top recommendations:
<Info>
For a complete comparison of all autocomplete models, see our [comprehensive model recommendations](/customization/models#recommended-models).
</Info>
## Recommended Models for Autocomplete in Continue
### Hosted (Best Performance)
@ -23,13 +27,13 @@ This model is specifically designed for code completion and offers excellent per
### Hosted (Best Speed/Quality Tradeoff)
For fast, quality autocomplete suggestions, we recommend **[Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small)** from Inception Labs.
For fast, quality autocomplete suggestions, we recommend **[Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small)** from Inception.
This model is specifically designed for code completion and is particularly fast because it is a diffusion model.
**Mercury Coder Small Quick Setup:**
1. Get your API key from [Inception Labs](https://platform.inceptionlabs.ai/)
1. Get your API key from [Inception](https://platform.inceptionlabs.ai/)
2. Add [Mercury Coder Small](https://hub.continue.dev/inceptionlabs/mercury-coder-small) to your assistant on Continue Hub
3. Add `INCEPTION_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
4. Click `Reload config` in the assistant selector in the Continue IDE extension

View file

@ -4,9 +4,10 @@ description: "Learn how Continue's Next Edit feature predicts and suggests your
---
<Warning>
Next Edit is currently an experimental feature. It requires Mercury Coder Next
Edit model configured in your Continue autocomplete settings and is not yet
available for JetBrains use.
Next Edit is currently an experimental feature. It requires [Mercury Coder
model](https://hub.continue.dev/inceptionlabs/mercury-coder) configured in
your Continue autocomplete settings and is not yet available for JetBrains
use.
</Warning>
## What is Next Edit?
@ -70,16 +71,16 @@ Next Edit activates automatically when:
Next Edit requires:
- Compatible AI models (Mercury Coder Next Edit)
- Compatible AI models (Mercury Coder)
- Continue development team access
- VS Code (JetBrains support coming soon)
- **API Keys**: Organizations can add API keys to [org secrets](/hub/secrets/secret-types) for team-wide access. Individual users need to provide their own API keys in their [model configuration](/customize/model-providers/overview)
<Note>
To use Next Edit, you must have the Mercury Coder Next Edit model configured
in your Continue autocomplete model settings. This model is specifically
designed for next edit predictions. Once it's been loaded, you must reload VS
Code to activate it.
To use Next Edit, you must have the Mercury Coder model configured in your
Continue autocomplete model settings. This model is specifically designed for
next edit predictions. Once it's been loaded, you must reload VS Code to
activate it.
<img
src="/images/features/autocomplete/images/mercury-coder-next-edit.png"
alt="Next Edit Model Setup"
@ -115,7 +116,7 @@ Next Edit requires:
Next Edit requires AI models specifically trained for code prediction:
- **Mercury Coder Next Edit**: Primary model optimized for next edit prediction
- **Mercury Coder**: Primary model optimized for next edit prediction
### Automatic Detection

View file

@ -3,6 +3,10 @@ The model you use for for Chat mode will be
- used with Edit mode by default but can be switched
- always used with Agent mode if the model supports tool calling
<Info>
For a comprehensive comparison of all available models by role, see our [model recommendations table](/customization/models#recommended-models).
</Info>
## What Models Are Recommended for Chat?
Our strong recommendation is to use [Claude Sonnet 4](https://hub.continue.dev/anthropic/claude-4-sonnet) from Anthropic.

View file

@ -8,6 +8,10 @@ The model you set up for Chat mode will be used for Edit mode by default.
The recommended models and how to set them up can be found [here](/features/chat/model-setup).
<Info>
See our [comprehensive model recommendations](/customization/models#recommended-models) for the best models for each role, including Edit and Apply.
</Info>
## How to Set Up an Apply Model
We also recommend setting up an Apply model for the best Edit experience.

View file

@ -29,57 +29,162 @@ curl -fsSL https://ollama.ai/install.sh | sh
# Download from ollama.ai
```
### Step 2: How to Download Models
### Step 2: How to Start Ollama
After installing Ollama, download the models you want to use. Here are some popular options:
After installation, start the Ollama service:
```bash
# Start Ollama (runs in background)
ollama serve
# Verify it's running
curl http://localhost:11434
# Should return "Ollama is running"
```
# Popular models for development
ollama pull mistral
ollama pull qwen2.5-coder:1.5b-base
ollama pull nomic-embed-text:latest
### Step 3: How to Download Models
<Warning>
**Important**: Always use `ollama pull` instead of `ollama run` to download models. The `run` command starts an interactive session which isn't needed for Continue.
</Warning>
Download models using the exact tag specified:
```bash
# Pull models with specific tags
ollama pull deepseek-r1:32b # 32B parameter version
ollama pull deepseek-r1:latest # Latest/default version
ollama pull mistral:latest
ollama pull qwen2.5-coder:1.5b
# List all downloaded models
ollama list
```
**Common Model Tags:**
- `:latest` - Default version (used if no tag specified)
- `:32b`, `:7b`, `:1.5b` - Parameter count versions
- `:instruct`, `:base` - Model variants
<Note>
If a model page shows `deepseek-r1:32b` on Ollama's website, you must pull it with that exact tag. Using just `deepseek-r1` will pull `:latest` which may be a different size.
</Note>
## How to Configure Ollama with Continue
Configure Continue to work with your local Ollama instance:
There are multiple ways to configure Ollama models in Continue:
### How to Set Up Continue Configuration
### Method 1: Using Hub Model Blocks in Local config.yaml
The easiest way is to use pre-configured model blocks from the Continue Hub in your local configuration:
```yaml
# ~/.continue/assistants/My Local Assistant.yaml
name: My Local Assistant
version: 0.0.1
schema: v1
models:
- uses: ollama/deepseek-r1-32b
- uses: ollama/qwen2.5-coder-7b
- uses: ollama/gpt-oss-20b
```
<Warning>
**Important**: Hub blocks only provide configuration - you still need to pull the model locally. The hub block `ollama/deepseek-r1-32b` configures Continue to use `model: deepseek-r1:32b`, but the actual model must be installed:
```bash
# Check what the hub block expects (view on hub.continue.dev)
# Then pull that exact model tag locally
ollama pull deepseek-r1:32b # Required for ollama/deepseek-r1-32b hub block
```
If the model isn't installed, Ollama will return: `404 model "deepseek-r1:32b" not found, try pulling it first`
</Warning>
### Method 2: Using Autodetect
Continue can automatically detect available Ollama models. You can configure this in your YAML:
```yaml
models:
- name: mistral
- name: Autodetect
provider: ollama
apiBase: http://localhost:11434
model: mistral
model: AUTODETECT
roles:
- chat
- edit
- apply
- name: Qwen2.5-Coder 1.5B
provider: ollama
apiBase: http://localhost:11434
model: qwen2.5-coder:1.5b-base
roles:
- autocomplete
- name: Nomic Embed
provider: ollama
apiBase: http://localhost:11434
model: nomic-embed-text:latest
roles:
- embed
```
Or use it through the GUI:
1. Click on the model selector dropdown
2. Select "Autodetect" option
3. Continue will scan for available Ollama models
4. Select your desired model from the detected list
<Note>
The Autodetect feature scans your local Ollama installation and lists all available models. When set to `AUTODETECT`, Continue will dynamically populate the model list based on what's installed locally via `ollama list`. This is useful for quickly switching between models without manual configuration.
</Note>
You can update `apiBase` with the IP address of a remote machine serving Ollama.
### Method 3: Manual Configuration
For custom configurations or models not on the hub:
```yaml
models:
- name: DeepSeek R1 32B
provider: ollama
model: deepseek-r1:32b # Must match exactly what `ollama list` shows
apiBase: http://localhost:11434
roles:
- chat
- edit
capabilities: # Add if not auto-detected
- tool_use
- name: Qwen2.5-Coder 1.5B
provider: ollama
model: qwen2.5-coder:1.5b
roles:
- autocomplete
```
### Model Capabilities and Tool Support
Some Ollama models support tools (function calling) which is required for Agent mode. However, not all models that claim tool support work correctly:
#### Checking Tool Support
```yaml
models:
- name: DeepSeek R1
provider: ollama
model: deepseek-r1:latest
capabilities:
- tool_use # Add this to enable tools
```
<Warning>
**Known Issue**: Some models like DeepSeek R1 may show "Agent mode is not supported" or "does not support tools" even with capabilities configured. This is a known limitation where the model's actual tool support differs from its advertised capabilities.
</Warning>
#### If Agent Mode Shows "Not Supported"
1. First, add `capabilities: [tool_use]` to your model config
2. If you still get errors, the model may not actually support tools despite documentation
3. Use a different model known to work with tools (e.g., Llama 3.1, Mistral)
See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for more details.
### How to Configure Advanced Settings
For optimal performance, consider these advanced configuration options:
- Memory optimization
- GPU acceleration
- Custom model parameters
- Performance tuning
- Memory optimization: Adjust `num_ctx` for context window size
- GPU acceleration: Use `num_gpu` to control GPU layers
- Custom model parameters: Temperature, top_p, top_k settings
- Performance tuning: Batch size and threading options
## What Are the Best Practices for Ollama
@ -102,30 +207,68 @@ To get the best performance from Ollama:
## How to Troubleshoot Ollama Issues
### What Are Common Issues
### Common Configuration Problems
Here are solutions to common problems you might encounter:
#### "404 model not found, try pulling it first"
#### How to Fix Connection Problems
This error occurs when the model isn't installed locally:
- Check Ollama service status
- Verify port availability
- Review firewall settings
**Problem**: Using a hub block or config that references a model not yet pulled
**Solution**:
```bash
# Check what models you have
ollama list
#### How to Resolve Performance Issues
# Pull the exact model version needed
ollama pull model-name:tag # e.g., deepseek-r1:32b
```
- Insufficient RAM
- Model too large for system
- GPU compatibility
#### Model Tag Mismatches
### How to Apply Solutions
**Problem**: `ollama pull deepseek-r1` installs `:latest` but hub block expects `:32b`
**Solution**: Always pull with the exact tag:
```bash
# Wrong - pulls :latest
ollama pull deepseek-r1
Try these solutions in order:
# Right - pulls specific version
ollama pull deepseek-r1:32b
```
1. Restart Ollama service
2. Clear model cache
3. Update to latest version
4. Check system requirements
#### "Agent mode is not supported"
**Problem**: Model doesn't support tools/function calling
**Solutions**:
1. Add `capabilities: [tool_use]` to your model config
2. If still not working, the model may not actually support tools
3. Switch to a model with confirmed tool support (Llama 3.1, Mistral)
#### Using Hub Blocks in Local Config
**Problem**: Unclear how to use hub models locally
**Solution**: Create a local assistant file:
```yaml
# ~/.continue/assistants/Local.yaml
name: Local Assistant
version: 0.0.1
schema: v1
models:
- uses: ollama/model-name
```
### How to Fix Connection Problems
- Verify Ollama is running: `curl http://localhost:11434`
- Check service status: `systemctl status ollama` (Linux)
- Ensure port 11434 is not blocked by firewall
- For remote connections, set `OLLAMA_HOST=0.0.0.0:11434`
### How to Resolve Performance Issues
- Insufficient RAM: Use smaller models (7B instead of 32B)
- Model too large: Check available memory with `ollama ps`
- GPU issues: Verify CUDA/ROCm installation for GPU acceleration
- Slow generation: Adjust `num_gpu` layers in model configuration
## What Are Example Workflows with Ollama

View file

@ -0,0 +1,7 @@
# Continue API settings
# API base URL - defaults to https://api.continue.dev/ if not specified
CONTINUE_API_BASE=http://localhost:3001
# Continue API key
# This is required for authentication with the Continue API
CONTINUE_API_KEY=

1
extensions/cli/.github/CODEOWNERS vendored Normal file
View file

@ -0,0 +1 @@
* @continuedev/continue-code-reviewers

View file

@ -0,0 +1,111 @@
name: Legacy Release (Deprecated)
on:
# schedule:
# # Run every day at 9am UTC
# - cron: "0 9 * * *"
workflow_dispatch:
# Keep manual triggering for emergencies
permissions:
contents: write
issues: write
pull-requests: write
jobs:
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: 20
registry-url: "https://registry.npmjs.org"
always-auth: true
- name: Install dependencies
run: npm ci
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
# - name: Check beta version age
# run: |
# echo "Checking if any beta versions are less than 7 days old..."
# # Get all beta versions from npm
# BETA_VERSIONS=$(npm view @continuedev/cli versions --json | jq -r '.[] | select(contains("-beta."))' 2>/dev/null || echo "[]")
# if [ "$BETA_VERSIONS" = "[]" ] || [ -z "$BETA_VERSIONS" ]; then
# echo "No beta versions found, proceeding with release"
# exit 0
# fi
# # Current date in seconds since epoch
# CURRENT_DATE=$(date +%s)
# SEVEN_DAYS_AGO=$((CURRENT_DATE - 7 * 24 * 60 * 60))
# # Check each beta version
# echo "$BETA_VERSIONS" | while read -r version; do
# if [ -z "$version" ]; then
# continue
# fi
# echo "Checking version: $version"
# # Extract date from beta version (format: X.Y.Z-beta.YYYYMMDD or X.Y.Z-beta.YYYYMMDD.HHMM)
# DATE_PART=$(echo "$version" | sed -n 's/.*-beta\.\([0-9]\{8\}\).*/\1/p')
# if [ -z "$DATE_PART" ]; then
# echo "Could not extract date from version $version, skipping"
# continue
# fi
# # Convert YYYYMMDD to epoch seconds (assuming midnight UTC)
# YEAR=${DATE_PART:0:4}
# MONTH=${DATE_PART:4:2}
# DAY=${DATE_PART:6:2}
# # Validate date components
# if [ ${#YEAR} -ne 4 ] || [ ${#MONTH} -ne 2 ] || [ ${#DAY} -ne 2 ]; then
# echo "Invalid date format in version $version, skipping"
# continue
# fi
# # Convert to epoch seconds
# VERSION_DATE=$(date -d "${YEAR}-${MONTH}-${DAY}" +%s 2>/dev/null || continue)
# echo "Version $version date: ${YEAR}-${MONTH}-${DAY} (${VERSION_DATE})"
# echo "Seven days ago: $(date -d @${SEVEN_DAYS_AGO} '+%Y-%m-%d') (${SEVEN_DAYS_AGO})"
# # Check if beta version is less than 7 days old
# if [ "$VERSION_DATE" -gt "$SEVEN_DAYS_AGO" ]; then
# echo "❌ ERROR: Beta version $version was created on ${YEAR}-${MONTH}-${DAY}, which is less than 7 days ago."
# echo "Cannot create a stable release until at least 7 days have passed since the latest beta."
# echo "Please wait until $(date -d @$((VERSION_DATE + 7 * 24 * 60 * 60)) '+%Y-%m-%d') before creating a stable release."
# exit 1
# else
# echo "✅ Beta version $version is older than 7 days (created ${YEAR}-${MONTH}-${DAY})"
# fi
# done
# echo "All beta versions are at least 7 days old, proceeding with release"
- name: Install semantic-release and plugins
run: npm install -D semantic-release @semantic-release/changelog @semantic-release/git @semantic-release/github @semantic-release/npm
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Semantic Release
id: semantic
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npx semantic-release

View file

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

13
extensions/cli/.gitignore vendored Normal file
View file

@ -0,0 +1,13 @@
node_modules
dist
.env
/*-repomix.xml
chat.log
*notes.md
# Local config files (users should not commit their personal configs)
config.yaml
.continue-debug/

17
extensions/cli/.npmignore Normal file
View file

@ -0,0 +1,17 @@
.env*
test
.vscode
.github
.continue
.releaserc.json
AGENTS.md
vitest.config.ts
vitest.e2e.config.ts
vitest.setup.ts
tsconfig.json
tsconfig.build.json
TESTING_STRATEGY.md
.env.example
package-lock.json
eslint.config.js
spec/

View file

@ -0,0 +1,38 @@
{
"branches": ["main"],
"plugins": [
[
"@semantic-release/commit-analyzer",
{
"releaseRules": [
{ "type": "feat", "release": "patch" },
{ "type": "fix", "release": "patch" },
{ "type": "perf", "release": "patch" },
{ "type": "revert", "release": "patch" },
{ "type": "docs", "release": false },
{ "type": "style", "release": false },
{ "type": "chore", "release": false },
{ "type": "refactor", "release": false },
{ "type": "test", "release": false },
{ "type": "build", "release": false },
{ "type": "ci", "release": false }
]
}
],
"@semantic-release/release-notes-generator",
[
"@semantic-release/changelog",
{
"changelogFile": "CHANGELOG.md"
}
],
[
"@semantic-release/npm",
{
"npmPublish": true,
"pkgRoot": "."
}
],
"@semantic-release/github"
]
}

80
extensions/cli/AGENTS.md Normal file
View file

@ -0,0 +1,80 @@
# AGENTS.md
This file provides guidance to AI coding agents when working with code in this repository.
## Development Commands
- **Build**: `npm run build` - Compiles TypeScript to JavaScript in dist/
- **Test**: `npm test` - Runs Vitest tests with ESM support
- **Type Check**: `npm run lint` - Runs TypeScript compiler without emitting files for type checking
- **Format**: `npm run format` - Runs Prettier with --write flag to check + fix formatting
- **Start**: `npm start` - Runs the built CLI from dist/index.js
- **Development**: After building, test locally with `node dist/index.js`
## Architecture Overview
This is a CLI tool for Continue Dev that provides an interactive AI-assisted development experience. The architecture consists of:
### Core Components
1. **Entry Point** (`src/index.ts`): Main CLI logic with two modes:
- **Headless mode**: Non-interactive mode for automation/CI
- **TUI mode**: Terminal User Interface using Ink/React
- **Standard mode**: Traditional readline-based chat interface
2. **Authentication** (`src/auth/`): WorkOS-based authentication system
- `ensureAuth.ts`: Handles authentication flow
- `workos.ts`: WorkOS configuration and token management
3. **Continue SDK Integration** (`src/continueSDK.ts`): Initializes the Continue SDK client with:
- API key authentication
- Assistant configuration (slug-based)
- Organization support
4. **Terminal UI** (`src/ui/`): React/Ink-based TUI components
- `TUIChat.tsx`: Main chat interface component
- `UserInput.tsx`: Input handling with multi-line support
- `TextBuffer.ts`: Text display utilities
5. **Tools System** (`src/tools/`): Built-in development tools including:
- File operations (read, write, list)
- Code search functionality
- Terminal command execution
- Diff viewing
- Exit tool (headless mode only)
6. **MCP Integration** (`src/mcp.ts`): Model Context Protocol service for extended tool capabilities
### Key Features
- **Streaming Responses**: Real-time AI response streaming (`streamChatResponse.ts`)
- **Slash Commands**: Built-in commands like `/help`, `/exit` (`slashCommands.ts`)
- **Multi-mode Operation**: Supports TUI, headless, and standard chat modes
- **Tool Integration**: Extensible tool system for development tasks
### Testing Setup
- Uses Vitest with TypeScript and ESM support
- Configuration in `vitest.config.ts`
- Tests should be written with `.test.ts` extension
- No existing test files found - tests should be added when writing new functionality
- Run tests using `npm run test path/or/pattern`
### Build System
- TypeScript compilation with declaration files
- ESNext target with NodeNext module resolution
- Outputs to `dist/` directory
- Source maps and inline sources enabled
- JSX support for React components
- Relative import paths require explicit file extensions, e.g. 'from "./test.js"' instead of 'from "./test"'
### Important rules
- Whenever you create / update a test, you should run the test to be certain that it passes
- If you ever create a PR, you should be sure to check the formatting and linting first with `npm run format` and `npm run lint` / `npm run lint:fix`.

134
extensions/cli/CHANGELOG.md Normal file
View file

@ -0,0 +1,134 @@
## [1.4.2](https://github.com/continuedev/cli/compare/v1.4.1...v1.4.2) (2025-07-17)
### Bug Fixes
- remove warning ([31b3f67](https://github.com/continuedev/cli/commit/31b3f6707b0f42180c8ae56faf9dfb2f566be5c1))
## [1.4.1](https://github.com/continuedev/cli/compare/v1.4.0...v1.4.1) (2025-07-17)
### Bug Fixes
- update readme ([0d45e14](https://github.com/continuedev/cli/commit/0d45e14b1be6557ace027cfeadfbf418061a28b0))
# [1.4.0](https://github.com/continuedev/cli/compare/v1.3.6...v1.4.0) (2025-07-17)
### Features
- dim user msg text color ([b22429b](https://github.com/continuedev/cli/commit/b22429ba0a101f99b14313345a8a8894caff3081))
## [1.3.6](https://github.com/continuedev/cli/compare/v1.3.5...v1.3.6) (2025-07-16)
### Bug Fixes
- update readme ([01329e4](https://github.com/continuedev/cli/commit/01329e4b4f66d97c93c98e0342f100792f626126))
## [1.3.5](https://github.com/continuedev/cli/compare/v1.3.4...v1.3.5) (2025-07-16)
### Bug Fixes
- package.json issues page ([91e1e2e](https://github.com/continuedev/cli/commit/91e1e2e004e86d6fb1df3bbfbbf94f6d46a4adb7))
- update review.yaml config ([b49ab0d](https://github.com/continuedev/cli/commit/b49ab0d9e54edf8374b113af4752e1c6fba15738))
## [1.3.4](https://github.com/continuedev/cli/compare/v1.3.3...v1.3.4) (2025-07-16)
### Bug Fixes
- add /clear command to clear chat history ([3782732](https://github.com/continuedev/cli/commit/378273239b32fce735266cb4835512f5c547a86d))
## [1.3.3](https://github.com/continuedev/cli/compare/v1.3.2...v1.3.3) (2025-07-16)
### Bug Fixes
- update chat history state after streaming and save complete conversation ([936786a](https://github.com/continuedev/cli/commit/936786aee08fcbdde2484896730a0c67f1ebafee))
## [1.3.2](https://github.com/continuedev/cli/compare/v1.3.1...v1.3.2) (2025-07-16)
### Bug Fixes
- remove .js extensions from highlight.js language imports ([6426777](https://github.com/continuedev/cli/commit/6426777d659a2747681d22d4c78574d6e0686ba6))
## [1.3.1](https://github.com/continuedev/cli/compare/v1.3.0...v1.3.1) (2025-07-16)
### Bug Fixes
- type err ([f5f1bca](https://github.com/continuedev/cli/commit/f5f1bca7c6a9f2c4f2842605847d55b765fd3499))
# [1.3.0](https://github.com/continuedev/cli/compare/v1.2.0...v1.3.0) (2025-07-15)
### Features
- add session management with --resume flag and cn alias ([0096fbc](https://github.com/continuedev/cli/commit/0096fbcc4934d7264d9a7a134908e016e037df1a))
# [1.2.0](https://github.com/continuedev/cli/compare/v1.1.0...v1.2.0) (2025-07-14)
### Bug Fixes
- bg color for diff ([63c9ecf](https://github.com/continuedev/cli/commit/63c9ecf24fcf74f43d07244c963cef04f91baee8))
- display diff ([fde6098](https://github.com/continuedev/cli/commit/fde6098ef2c4d99a9b9b8d6ffc1299436e0f52c1))
- improve streaming message handling and display buffering ([d1372b3](https://github.com/continuedev/cli/commit/d1372b3aa2f79221957468fd1decbae2258becc0))
- remove part of the system message ([daae972](https://github.com/continuedev/cli/commit/daae97242f1fca92f42f8c979df8d9c3f912f69d))
- truncate diff at 16 lines ([cbb77e3](https://github.com/continuedev/cli/commit/cbb77e35ff19809c1c05760fbdf7c995d85dc72c))
### Features
- add /clear command to clear chat history ([c9c000c](https://github.com/continuedev/cli/commit/c9c000cfab6aa6efe156126f1eafc99349466413))
- convert absolute paths to relative paths in tool display ([2c722c4](https://github.com/continuedev/cli/commit/2c722c485eea4c3c283fb643193a4b1ffe14bf7f))
# [1.1.0](https://github.com/continuedev/cli/compare/v1.0.1...v1.1.0) (2025-07-14)
### Bug Fixes
- improve streaming message handling and API endpoint ([b822b93](https://github.com/continuedev/cli/commit/b822b938f110af2de2c040f45cd3fca770d9a4a7))
- use ignore-walk for sys msg ([eb59dcc](https://github.com/continuedev/cli/commit/eb59dcc76a5bf16d4da2e4f2c7dc87765e8382b3))
### Features
- base system message ([25a67cf](https://github.com/continuedev/cli/commit/25a67cf947f786d4cdc36c60e36e303a4e466c87))
## [1.0.1](https://github.com/continuedev/cli/compare/v1.0.0...v1.0.1) (2025-07-14)
### Bug Fixes
- release index.js ([091cfa7](https://github.com/continuedev/cli/commit/091cfa7b64c1591f371e444e602d04fdcbca48d4))
# 1.0.0 (2025-07-14)
### Bug Fixes
- adjust placeholder ([94e6f12](https://github.com/continuedev/cli/commit/94e6f12924ff5ee429a43c53d1810d5519f026bb))
- adjust waiting message ([454df15](https://github.com/continuedev/cli/commit/454df1554500a530645ef5e7a6a80fea6a27f207))
- allow multiple consecutive new lines ([423dbdd](https://github.com/continuedev/cli/commit/423dbdd457683260f66eda9024f35dee9c49d5db))
- backspace on mac ([aa5606f](https://github.com/continuedev/cli/commit/aa5606f65f3284c9ff4d0a02cb1e4611b5cd080c))
- cursor position ([388eeeb](https://github.com/continuedev/cli/commit/388eeeb37afa7625b954e4dd44cbcd7cf0ab22bb))
- delete hallucinated tools ([2d4cf55](https://github.com/continuedev/cli/commit/2d4cf55c393121570ff2c4459c6942e124bc88dd))
- dot shade of green ([8f6ec39](https://github.com/continuedev/cli/commit/8f6ec398ff23ec1d59567cb5b2de92dabd58ab4b))
- empty assistant message ([5e773f5](https://github.com/continuedev/cli/commit/5e773f52684dc8b267fa33a94b0b707d292a6111))
- even nicer tool UI ([3716ebc](https://github.com/continuedev/cli/commit/3716ebcdd73a23e021e59a9d162d61915ce31184))
- more slashcommand UI ([daa4538](https://github.com/continuedev/cli/commit/daa45387725f6b0b9b247ebde63f1f3018052bc2))
- nicer tool display ([6749e10](https://github.com/continuedev/cli/commit/6749e10daad3fc9238dce6bf5c7309dd610cad2a))
- option + left/rght ([efa2c43](https://github.com/continuedev/cli/commit/efa2c434d0a5942e9aaf5171c2d1f03c5df3ca51))
- refactor display name for tools ([837ac2d](https://github.com/continuedev/cli/commit/837ac2d5c33ad0ef6482f8216dd7b3a8ec852fe3))
- round corners ([a08e217](https://github.com/continuedev/cli/commit/a08e2176a70f5a216f6e03657e9f6522eade99b8))
- shift+enter for newline ([fa30094](https://github.com/continuedev/cli/commit/fa30094e61dbb2b11f7940b875fc719d06ed3eec))
- slash command prefix matching ([0a40201](https://github.com/continuedev/cli/commit/0a402010d9ae98a6913b7ceb68b97dfd9772754e))
- slash command tab ([ee40d8b](https://github.com/continuedev/cli/commit/ee40d8bbb48d502055cad1e811e973598b0bf9bd))
- stream above input box ([c8945ad](https://github.com/continuedev/cli/commit/c8945adb85c99379039afa02ac4d63f114a6de6b))
- tool call custom UI ([fa4b98f](https://github.com/continuedev/cli/commit/fa4b98f455db6fe48b4c5810327d0222fade7902))
- tool name matching ([9792b14](https://github.com/continuedev/cli/commit/9792b1411f713c2615c0d3b82df2c7032d434205))
- tool ui again ([9c18d28](https://github.com/continuedev/cli/commit/9c18d28cbefed79f316a0b9d219f7ec585455eca))
- tool UI again ([9d4ea20](https://github.com/continuedev/cli/commit/9d4ea20deb278a7c8d427647b5c1d5cf4d333352))
- tui no longer completely broken ([8c0fd5e](https://github.com/continuedev/cli/commit/8c0fd5e87e7e8ce59b4b022669d4aba2ba1b8bcf))
### Features
- basic ink tui ([ed536d3](https://github.com/continuedev/cli/commit/ed536d3505167cd15e46ec4dee49847eb87b63a8))
- better slash command UI ([c62cbdc](https://github.com/continuedev/cli/commit/c62cbdc21e6e93788d8e01c0a97c17ef0c036261))
- disable PR description ([a5722ba](https://github.com/continuedev/cli/commit/a5722bab8bd7fb925806a767e9f76a4165f5f6b3))
- esc to interrupt ([5643a53](https://github.com/continuedev/cli/commit/5643a53b5a3440d1e3e2ee41df08524289ad94b2))
- integrate SDK into CLI ([#1](https://github.com/continuedev/cli/issues/1)) ([597e35b](https://github.com/continuedev/cli/commit/597e35b5be0ab1d1f62b6d9e2ac71e168d06e39c))
- more spinners ([dccb311](https://github.com/continuedev/cli/commit/dccb31106a43f2c295da3f8a4225a44969cb3ef7))
- new TextBuffer class for improved keystroke handling ([e7ab301](https://github.com/continuedev/cli/commit/e7ab301dbe3b7e27bd6bb15992f3cf1a3f9694d7))
- paste ([65f10a1](https://github.com/continuedev/cli/commit/65f10a1a4f2862bf1166d187e49fc732a503f9da))
- slash command UI and ASCII spinner ([7eefce2](https://github.com/continuedev/cli/commit/7eefce2de39fca9ab51b2d2fb1d0b24286c09404))
- suppress `console.info` in headless ([8177eef](https://github.com/continuedev/cli/commit/8177eef6a00a06f5c80d4b0ee4c84f00fd156cd5))
- TUI mode as default ([e73098b](https://github.com/continuedev/cli/commit/e73098b82ed5ea73f6d8d33eab24fdf6c67bb8ec))

60
extensions/cli/README.md Normal file
View file

@ -0,0 +1,60 @@
# Continue CLI
The Continue CLI (`cn`) is a customizable command line coding agent.
![Continue CLI Demo](./media/demo.gif)
## Installation
```bash
npm i -g @continuedev/cli
```
## Usage
```bash
cn
```
### Headless Mode
```bash
cn -p "Generate a conventional commit name for the current git changes."
```
### Session Management
The CLI automatically saves your chat history for each terminal session. You can resume where you left off:
```bash
# Resume the last session in this terminal
cn --resume
# List recent sessions and choose one to resume
cn ls
# List sessions in JSON format (for scripting)
cn ls --json
```
## Command Line Options
- `-p`: Run in headless mode (no TUI)
- `--config <path>`: Specify agent configuration path
- `--resume`: Resume the last session for this terminal
- `<prompt>`: Optional prompt to start with
## Commands
- `cn`: Start an interactive chat session
- `cn ls`: List recent sessions with TUI selector to choose one to resume
- `cn login`: Authenticate with Continue
- `cn logout`: Sign out of current session
- `cn remote`: Launch a remote instance
- `cn serve`: Start HTTP server mode
### Session Listing (`cn ls`)
Shows recent sessions, limited by screen height to ensure it fits on your terminal.
- `--json`: Output in JSON format for scripting (always shows 10 sessions)

View file

@ -0,0 +1,186 @@
import tsParser from "@typescript-eslint/parser";
import tsPlugin from "@typescript-eslint/eslint-plugin";
import importPlugin from "eslint-plugin-import";
import unusedImports from "eslint-plugin-unused-imports";
export default [
{
files: ["**/*.ts", "**/*.tsx"],
plugins: {
"@typescript-eslint": tsPlugin,
import: importPlugin,
"unused-imports": unusedImports,
},
languageOptions: {
parser: tsParser,
parserOptions: {
project: "./tsconfig.json",
ecmaVersion: "latest",
sourceType: "module",
},
},
rules: {
// Core rules - all as errors
"max-classes-per-file": ["error", 1],
"prefer-const": "error",
// "class-methods-use-this": [
// "error",
// {
// exceptMethods: [
// "render",
// "shouldComponentUpdate",
// "componentDidMount",
// "componentDidUpdate",
// "componentWillUnmount",
// ],
// },
// ],
"no-negated-condition": "error",
"max-lines": [
"error",
{ max: 500, skipBlankLines: true, skipComments: true },
],
complexity: ["error", { max: 20 }],
// "max-lines-per-function": [
// "error",
// { max: 150, skipBlankLines: true, skipComments: true },
// ],
"max-statements": ["error", { max: 50 }],
"max-depth": ["error", { max: 4 }],
"max-nested-callbacks": ["error", { max: 3 }],
"max-params": ["error", { max: 5 }],
eqeqeq: "error",
// TypeScript specific rules
// "@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-explicit-any": "error",
// "@typescript-eslint/member-ordering": [
// "error",
// {
// default: [
// // Static fields
// "public-static-field",
// "protected-static-field",
// "private-static-field",
// // Instance fields
// "public-instance-field",
// "protected-instance-field",
// "private-instance-field",
// // Constructors
// "constructor",
// // Static methods
// "public-static-method",
// "protected-static-method",
// "private-static-method",
// // Instance methods
// "public-instance-method",
// "protected-instance-method",
// "private-instance-method",
// ],
// },
// ],
// Import rules
"import/order": [
"error",
{
groups: [
"builtin",
"external",
"internal",
"parent",
"sibling",
"index",
],
"newlines-between": "always",
alphabetize: {
order: "asc",
caseInsensitive: true,
},
},
],
"import/no-default-export": "error",
// Unused code detection
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": "off",
"unused-imports/no-unused-imports": "error",
"unused-imports/no-unused-vars": [
"error",
{
vars: "all",
varsIgnorePattern: "^_",
args: "after-used",
argsIgnorePattern: "^_",
},
],
// Turn off rules that might be too strict for CLI
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-non-null-assertion": "off",
// Allow console for CLI tool
"no-console": "off",
},
settings: {
"import/resolver": {
typescript: {
project: "./tsconfig.json",
},
node: true,
},
},
},
{
// Allow default exports in specific files
files: ["src/index.ts", "*.config.js", "*.config.ts"],
rules: {
"import/no-default-export": "off",
},
},
{
// Test files can have different rules
files: [
"**/*.test.ts",
"**/*.test.tsx",
"**/*.spec.ts",
"**/*.spec.tsx",
"**/test-helpers/**/*.ts",
"**/test-helpers/**/*.tsx",
"**/__tests__/**/*.ts",
"**/__tests__/**/*.tsx",
"**/__mocks__/**/*.ts",
"**/__mocks__/**/*.tsx",
],
rules: {
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-floating-promises": "off",
"unused-imports/no-unused-vars": "off",
"max-classes-per-file": "off",
"max-lines": "off",
"max-lines-per-function": "off",
"max-statements": "off",
complexity: "off",
"class-methods-use-this": "off",
"max-nested-callbacks": "off",
},
},
{
ignores: [
"dist/**",
"node_modules/**",
"coverage/**",
"*.d.ts",
"src/__mocks__/**",
"vitest.config.ts",
"*.config.js",
"*.config.ts",
],
},
];

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 MiB

19705
extensions/cli/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

133
extensions/cli/package.json Normal file
View file

@ -0,0 +1,133 @@
{
"name": "@continuedev/cli",
"version": "0.0.0-dev",
"description": "Continue CLI",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"bin": {
"cn": "dist/index.js"
},
"scripts": {
"test": "vitest run",
"test:watch": "vitest watch",
"test:ui": "vitest --ui",
"test:e2e": "vitest run --config vitest.e2e.config.ts",
"build": "tsc -p tsconfig.build.json",
"start": "node dist/index.js",
"dev": "tsx src/index.ts",
"repomix:sdk": "npx repomix node_modules/@continuedev/sdk --ignore **/api,cli-repomix.xml -o sdk-repomix.xml",
"repomix:cli": "npx repomix --ignore sdk-repomix.xml -o cli-repomix.xml",
"lint": "tsc --noEmit && eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write .",
"format:check": "prettier --check .",
"typecheck": "tsc --noEmit",
"watch:logs": "touch ~/.continue/logs/cn.log && tail -f ~/.continue/logs/cn.log",
"prepare": "npm run build",
"semantic-release": "semantic-release",
"semantic-release:dry-run": "semantic-release --dry-run"
},
"author": "Continue Dev, Inc.",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/cli.git"
},
"bugs": {
"url": "https://github.com/continuedev/continue/issues"
},
"homepage": "https://continue.dev",
"dependencies": {
"@continuedev/config-yaml": "^1.0.96",
"@continuedev/openai-adapters": "^1.4.1",
"@continuedev/sdk": "^0.0.13",
"@modelcontextprotocol/sdk": "^1.17.2",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.203.0",
"@opentelemetry/exporter-metrics-otlp-http": "^0.203.0",
"@opentelemetry/instrumentation-fs": "^0.23.0",
"@opentelemetry/instrumentation-http": "^0.203.0",
"@opentelemetry/resources": "^2.0.1",
"@opentelemetry/sdk-node": "^0.203.0",
"@opentelemetry/semantic-conventions": "^1.36.0",
"@sentry/node": "^9.43.0",
"@sentry/profiling-node": "^9.43.0",
"@types/express": "^5.0.3",
"@types/react": "^19.1.8",
"@types/turndown": "^5.0.5",
"@workos-inc/node": "^7.45.0",
"chalk": "^5.4.1",
"commander": "^14.0.0",
"core": "file:../../core",
"date-fns": "^4.1.0",
"diff": "^7.0.0",
"dotenv": "^16.5.0",
"express": "^5.1.0",
"glob": "^11.0.3",
"gpt-tokenizer": "^3.0.1",
"gradient-string": "^3.0.0",
"ignore": "^7.0.5",
"ignore-walk": "^7.0.0",
"ink": "^6.1.0",
"jszip": "^3.10.1",
"lowlight": "^3.3.0",
"minimatch": "^10.0.3",
"node-fetch": "^3.3.2",
"node-machine-id": "^1.1.12",
"open": "^10.1.0",
"posthog-node": "^5.6.0",
"react": "^19.1.0",
"readline-sync": "^1.4.10",
"shell-quote": "^1.8.3",
"swr": "^2.3.4",
"turndown": "^7.2.0",
"typescript": "^5.8.3",
"uri-js": "^4.4.1",
"uuid": "^9.0.1",
"winston": "^3.17.0",
"yaml": "^2.8.0"
},
"devDependencies": {
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^11.0.3",
"@semantic-release/npm": "^12.0.2",
"@testing-library/react": "^16.3.0",
"@types/date-fns": "^2.5.3",
"@types/diff": "^7.0.2",
"@types/express": "^5.0.3",
"@types/glob": "^8.1.0",
"@types/ignore-walk": "^4.0.3",
"@types/ink-testing-library": "^1.0.4",
"@types/jszip": "^3.4.0",
"@types/nock": "^10.0.3",
"@types/readline-sync": "^1.4.8",
"@types/shell-quote": "^1.7.5",
"@types/supertest": "^6.0.3",
"@typescript-eslint/eslint-plugin": "^8.39.0",
"@typescript-eslint/parser": "^8.39.0",
"@vitest/ui": "^3.2.4",
"conventional-changelog-conventionalcommits": "^9.1.0",
"cross-env": "^7.0.3",
"eslint": "^9.32.0",
"eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-unused-imports": "^4.1.4",
"execa": "^9.6.0",
"express": "^5.1.0",
"happy-dom": "^18.0.1",
"ink-testing-library": "^4.0.0",
"jsdom": "^26.1.0",
"nock": "^14.0.5",
"prettier": "^3.6.2",
"semantic-release": "^24.2.7",
"supertest": "^7.1.3",
"ts-node": "^10.9.2",
"tsx": "^4.20.3",
"vitest": "^3.2.4"
},
"engine": {
"node": ">=18"
}
}

View file

@ -0,0 +1,191 @@
# Configuration Loading Behavior Specification
## Overview
This document specifies the behavior of the CLI's configuration loading system, including precedence rules, authentication interactions, and error handling.
## Authentication Precedence
**Authentication Source Priority:**
1. **Environment Variable**: `CONTINUE_API_KEY` environment variable
2. **File-Based Auth**: `~/.continue/auth.json` file
3. **No Authentication**: Unauthenticated mode
**Authentication Effects:**
- **Environment Auth**: Always uses personal organization, no config URI persistence
- **File Auth**: Supports organizations, persists config URIs, token refresh
- **No Auth**: Limited to default assistant, no personalization
## Configuration Source Precedence
**When CLI is invoked, config source is determined in this order:**
1. **CLI `--config` Flag** (highest priority)
- File path (starts with `.`, `/`, `~`): Loads local YAML file
- Assistant slug (`owner/package`): Fetches from Continue platform
- Overrides any saved preferences
2. **Saved Config URI** (if no `--config` flag)
- Retrieved from authentication config
- Converts `file://` URIs back to file paths
- Converts `slug://` URIs back to assistant slugs
3. **Default Resolution** (if no flag and no saved URI)
- **Authenticated**: First user assistant from `listAssistants()`
- **config.yaml**: The saved config file at `~/.continue/config.yaml`
- **Unauthenticated**: Falls back to `continuedev/default-agent`
## Authentication State Interactions
### Authenticated Users
**Available Options:**
- Personal assistants
- Organization assistants (if organization selected)
- Local YAML files
- Public assistants
**Behavior:**
- `listAssistants()` returns personalized results
- Config selections are saved as URIs in auth config
- Organization context affects available assistants
### Unauthenticated Users
**Available Options:**
- Local YAML files only
- Default assistant (`continuedev/default-agent`)
**Behavior:**
- No access to personal or organization assistants
- No config URI persistence
- Direct fallback to default when no config specified
### Environment Variable Auth (`CONTINUE_API_KEY`)
**Behavior:**
- Treated as authenticated for API access
- Always uses personal organization context
- No persistence of config URIs
- Cannot switch organizations
## Organization Context
**Organization Selection:**
- **Interactive Mode**: Auto-selects first available organization
- **Headless Mode**: Defaults to personal organization
- **Environment Auth**: Always personal organization
**Effects on Config Loading:**
- Organization ID passed to all API calls
- Affects which assistants appear in `listAssistants()`
- Organization changes trigger complete config reload
## Error Handling Behavior
### Config Loading Errors
**File Not Found:**
- Local file specified but doesn't exist
- **Result**: Error thrown, CLI exits
**Invalid YAML:**
- Local file exists but has syntax errors
- **Result**: Parsing error thrown, CLI exits
**Network Failures:**
- API calls fail for assistant slugs
- **Result**: Network error bubbled up, CLI exits
**Assistant Not Found:**
- Valid slug format but assistant doesn't exist
- **Result**: 404 error from API, CLI exits
### Fallback Scenarios
**No User Assistants:**
- Authenticated user has no personal assistants
- **Result**: Falls back to `continuedev/default-agent`
**Default Agent Unavailable:**
- Fallback to default agent fails
- **Result**: Error thrown, CLI cannot start
**Token Expired:**
- Saved auth token is expired
- **Result**: Automatic refresh attempted, re-auth required if refresh fails
## Config URI Persistence
**When URIs are Saved:**
- Any successful config load via service layer
- File paths converted to `file://path/to/config.yaml`
- Assistant slugs converted to `slug://owner/package`
**When URIs are NOT Saved:**
- Environment variable authentication in use
- Config loading failures
- Unauthenticated sessions
## Rule Integration
**Rule Processing:**
- `--rule` flags processed independently of config loading
- Multiple rules supported, injected into system message
- Rule failures are warnings, don't prevent config loading
- Rule sources: file paths, hub slugs, direct strings
## Session Continuity
**Next Session Behavior:**
- **With Saved URI**: Uses saved config automatically
- **CLI Override**: `--config` flag overrides saved URI and updates it
- **Config Switching**: UI actions update saved URI for future sessions
**Cross-Session State:**
- Authentication persists until logout
- Organization selection persists
- Config URI persists (except for environment auth)
## Complete Decision Flow
```
1. Parse CLI arguments
2. Load authentication state (env var > file > none)
3. Determine config source:
- CLI --config flag provided? Use it
- Saved config URI exists? Use it
- Default resolution based on auth state
4. Load configuration:
- File path? Parse YAML locally
- Assistant slug? Fetch from API
- Default resolution? List assistants or use default
5. Process and inject rules
6. Save config URI (if authenticated via file)
7. Initialize services with loaded config
```
This behavior ensures users get predictable config loading with clear precedence rules while maintaining session continuity and graceful fallbacks.

View file

@ -0,0 +1,49 @@
# `cn`
## Overall development goals
Fight to keep `cn` simple. This is an active process. The default is that `cn` will become disastrously complicated.
### Maintainability
Maintain minimal code (avoid new features unless there is overwhelming demand or they remove a clear blocker for many users). If someone offers up a feature you should seek to understand what they actually want and then decide as a maintainer of `cn` whether this can fit into some larger concept in a simple way. If someone asks to make something configurable, you should probably consider just changing the default.
### Don't write code by hand
Use `cn` for everything. You should very rarely need to write code by hand. If you find yourself doing this outside of small tweaks, you should ask what about the codebase is causing `cn` to be unable to make the change.
If we build a system that allows us to entrust all changes to `cn` then it will be more reliable than us writing the code. Not because we can't write better code, but because `cn` is consistently thorough + it will force us to build the right systems around the code.
### Do not test by hand
If you find yourself using `npm run start` to test that existing functionality is still working, this means that you are missing a test. A green check mark from `npm test` should be full proof that the code can be shipped. See our testing strategies [here](./testing-strategies.md).
For new features you obviously need to run them yourself to apply your taste. `cn` can't match that right now.
### Minimize the number of concepts
The spec for `cn` (if it were to be fully written out) should be relatively short. This helps keep the code / spec consistent. It also allows us to keep the docs short and makes it easier for users to understand.
### Low tolerance
Tolerance for the following should be very close to zero:
- Un-addressed code reviews
- Failing tests
- Flaky tests
- Sentry issues
If we are inundated then we should build a system to solve that. For example, if it is tiresome to address all AI code reviews, then set up a trigger to have `cn` automatically address them.
### Start with a spec
High level concepts / features should have a spec when possible. Good examples of this are [modes](./modes.md), [permissions](./permissions.md), [OTLP metrics](./otlp-metrics.md), and [wire format](./wire-format.md). Like code, the spec can and should be largely auto-generated.
## Codebase Design
- We intentionally write different implementations of the "loop" instead of trying to build a single engine that can be used across TUI, headless mode, `cn serve`, and more. So far, it would be more work than it is worth to add this abstraction.
- "Everything is a service." Nobody (human or AI) should need to re-invent a polling mechanism or way to store / update state. This decision has been made already so we can focus on the business logic. The service setup lets us easily keep reactive state and avoid React anti-patterns like `useEffect`.
- We use `ink` for UI, following the same usual React principles that we do elsewhere. Keep [components](../src/ui/components/) small, avoid `useEffect`, group logic into [hooks](../src/hooks).
- Always use the [logger](../src/util/logger.ts) instead of `console.log`.
- Use commander to define [commands](../src/commands/BaseCommandOptions.ts)
- `cn remote` is intended to act the same as `cn`'s TUI in almost every way. There is a test helper that allows us to run any e2e test in _both_ remote and normal modes to ensure this is true.

View file

@ -0,0 +1,44 @@
# Continue CLI Model Context Protocol (MCP) integration
## Intro
Model Context Protocol is a protocol for giving models access to resources and tools. MCP servers can run locally (stdio) or be remote (http/streamable/etc). See https://modelcontextprotocol.io/specification. The Continue CLI uses MCP to extend model's capabilities with MCP prompts and tools. MCP server configurations are stored in the `mcpServers` field of an assistant/config.yaml configuration.
## MCP Service
The CLI has an MCP Service should manage connections to MCP servers and provide state to the terminal app regarding MCP server connections.
Service initialization for MCP servers can take especially long, so it should not block service initialization. Instead, initialization should kick off server connections and then resolve.
All configured server connections can be initialized simultaneously using Promise.all
Each server configuration should have its own connection and state separated, but the service should also have an easy way to retrieve all tools and prompts from all servers to pass to the model.
Servers should have a status "idle", "connecting", "connected", or "error". Only "connected" servers contribute prompts and tools.
If a server successfully connects but there is an error retrieving prompts or tools, it should have an array of warning messages that can be accessed in the terminal app.
When the process exits, all servers should be shut down and disconnected.
Only MCP servers for the CURRENT config should be loaded
- Logs from MCP servers should be routed through the winston logger, not the standard console.log (since this is a terminal app)
## MCP slash command
Users can manage MCP connections using the /mcp slash command.
/mcp shows a menu with the following options
- "No servers" if there are no servers
- Restart all servers
- Stop all servers
- View servers
- Back (esc also goes back)
View servers should open a submenu that has each server name with its status icon
- red if error, yellow if warnings, green if connected, gray if idle
- "No Servers" if there are none
- Back (esc also goes back)
Finally, selecting a server opens a sub-submenu that keeps the name/icon as header and lists
- Back (esc also goes back)
- Restart server
- Stop server
- warnings the server currently has
- prompts the server contributes
- tools the server contributes

View file

@ -0,0 +1,84 @@
# Modes
Modes are a system for managing tool permissions in the CLI. They can be set via command-line flags at startup or switched dynamically during chat sessions. The following modes are available:
## Available Modes
### `normal` (default)
The default mode that follows configured permission policies from `permissions.yaml` and command-line overrides without any additional restrictions or mode-specific policies.
- **UI Indicator:** No indicator shown (clean interface for default behavior)
- **Current directory:** Visible in status bar for context
- **Permission behavior:** Uses existing permission policies as configured
- **Backward compatibility:** Existing configurations work unchanged
### `plan`
Planning mode that **completely overrides all user permissions** to enforce read-only access with command execution. This mode prevents file modifications but allows command execution for analysis, regardless of user configuration.
- **Command-line flag:** `--readonly` (for backward compatibility)
- **UI Indicator:** `[plan]` shown in blue
- **Current directory:** Hidden to save space and focus on analysis
- **Permission override:** **Absolute** - excludes write tools (Write, Edit, etc.) and allows read tools (Read, Grep, LS, etc.) and Bash for command execution
- **User config ignored:** Any user `--allow` flags for write tools are overridden
### `auto`
Auto mode that **completely overrides all user permissions** to allow everything without asking. This mode provides maximum automation by bypassing all permission policies and restrictions, regardless of user configuration.
- **Command-line flag:** `--auto` (starts in auto mode)
- **UI Indicator:** `[auto]` shown in green
- **Current directory:** Hidden to save space and focus on automation
- **Permission override:** **Absolute** - allows all tools with `*: allow` policy
- **User config ignored:** Any user `--exclude` flags are overridden - everything is allowed
## Usage
### Command-Line Initialization
Modes can be set when starting the CLI:
```bash
cn --readonly "Help me analyze this code" # Starts in plan mode
cn --auto "Fix all the linting errors" # Starts in auto mode
cn "Let me implement this feature" # Starts in normal mode (default)
```
### Dynamic Mode Switching
Users can switch modes during chat sessions using:
**Keyboard Shortcut:**
- **Shift+Tab** - Cycle through modes: normal → plan → auto → (repeat)
## Implementation
Modes are implemented through the permission system:
- **ModeService**: Singleton service managing the current mode and initialization
- **ToolPermissionService**: Extended to support mode-specific policies with highest priority
- **ModeIndicator**: UI component showing current mode (hidden for normal mode)
- **Keyboard shortcuts**: Shift+Tab cycles through modes instantly
- **Backward compatibility**: Existing `--readonly` flag maps to plan mode
### Mode Policy Priority
**Mode policies completely override all other configurations** when in plan or auto mode:
**Plan and Auto modes:**
1. **Mode policies** (absolute override - ignores everything else)
**Normal mode only:**
1. Command-line overrides (`--allow`, `--ask`, `--exclude`)
2. Permission configuration from `permissions.yaml`
3. Default tool policies
### Mode-Specific Behaviors
- **normal**: No mode policies applied, uses existing user configuration; shows current directory
- **plan**: **Absolute override** - excludes write tools (Write, Edit), allows read tools (Read, Grep, LS) and Bash; hides current directory
- **auto**: **Absolute override** - allows all tools with `*: allow` policy; hides current directory

View file

@ -0,0 +1,36 @@
# Onboarding
When a user first runs `cn` in interactive mode, they will be taken through "onboarding". After they have completed onboarding once, they will follow a normal config loading flow.
## Onboarding flow
**The onboarding flow runs when the user hasn't completed onboarding before, regardless of whether they have a valid config.yaml file.**
1. If the --config flag is provided, load this config
2. Otherwise, we will present the user with two options:
- Log in with Continue: log them in, which will automatically create their assistant and then we can load the first assistant from the first org
- Enter your Anthropic API key: let them enter the key, and then either create a ~/.continue/config.yaml with the following contents OR update the existing config.yaml to add the model
```yaml
name: Local Config
version: 1.0.0
schema: v1
models:
- uses: anthropic/claude-4-sonnet
with:
ANTHROPIC_API_KEY: <THEIR_ANTHROPIC_API_KEY>
```
When something in the onboarding flow is done automatically, we should tell the user what happened.
## Normal flow
**The normal flow runs when the user has already completed onboarding.**
1. If the --config flag is provided, load this config
2. If the user is logged in, look for the first assistant in the selected org
3. If there are no assistants in that org, then look for a local ~/.continue/config.yaml
4. If there is no config.yaml, look for an ANTHROPIC_API_KEY in the environment and manually construct the config object to include just the claude-4-sonnet model with that API key
5. If none of the above, then bring the user to step 3 of the onboarding flow

View file

@ -0,0 +1,342 @@
# OTLP Metrics Specification for Continue CLI
This document specifies the OpenTelemetry Protocol (OTLP) metrics that should be emitted by the Continue CLI to provide comprehensive observability and usage monitoring. The metrics are designed to be compatible with Claude Code dashboards for easy migration.
## Overview
The Continue CLI should emit metrics that provide insights into:
- Usage patterns and session analytics
- Performance and reliability
- Tool usage and effectiveness
- Error rates and types
- Resource utilization
- Code modification tracking
## Configuration
### Environment Variables
| Environment Variable | Description | Example Values |
| ------------------------------- | --------------------------------------------------------- | ------------------------------------ |
| `CONTINUE_CLI_ENABLE_TELEMETRY` | Enables telemetry collection (required) | `1` |
| `OTEL_METRICS_EXPORTER` | Metrics exporter type(s) (comma-separated) | `console`, `otlp`, `prometheus` |
| `OTEL_LOGS_EXPORTER` | Logs/events exporter type(s) (comma-separated) | `console`, `otlp` |
| `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol for OTLP exporter (all signals) | `grpc`, `http/json`, `http/protobuf` |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP collector endpoint (all signals) | `http://localhost:4317` |
| `OTEL_EXPORTER_OTLP_HEADERS` | Authentication headers for OTLP | `Authorization=Bearer token` |
| `OTEL_METRIC_EXPORT_INTERVAL` | Export interval in milliseconds (default: 60000) | `5000`, `60000` |
| `OTEL_LOGS_EXPORT_INTERVAL` | Logs export interval in milliseconds (default: 5000) | `1000`, `10000` |
| `OTEL_LOG_USER_PROMPTS` | Enable logging of user prompt content (default: disabled) | `1` to enable |
### Metrics Cardinality Control
| Environment Variable | Description | Default Value | Example to Disable |
| ----------------------------------- | ---------------------------------------------- | ------------- | ------------------ |
| `OTEL_METRICS_INCLUDE_SESSION_ID` | Include session.id attribute in metrics | `true` | `false` |
| `OTEL_METRICS_INCLUDE_VERSION` | Include app.version attribute in metrics | `false` | `true` |
| `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` | Include user.account_uuid attribute in metrics | `true` | `false` |
## Standard Attributes
All metrics and events share these standard attributes:
| Attribute | Description | Controlled By |
| ------------------- | ------------------------------------------------------------- | --------------------------------------------------- |
| `session.id` | Unique session identifier | `OTEL_METRICS_INCLUDE_SESSION_ID` (default: true) |
| `app.version` | Current Continue CLI version | `OTEL_METRICS_INCLUDE_VERSION` (default: false) |
| `organization.id` | Organization UUID (when authenticated) | Always included when available |
| `user.account_uuid` | Account UUID (when authenticated) | `OTEL_METRICS_INCLUDE_ACCOUNT_UUID` (default: true) |
| `terminal.type` | Terminal type (e.g., `iTerm.app`, `vscode`, `cursor`, `tmux`) | Always included when detected |
## Core Metrics
### ✅ `continue.cli.session.count`
**Type:** Counter
**Unit:** `count`
**Description:** Count of CLI sessions started
**Attributes:**
- All [standard attributes](#standard-attributes)
**Implementation:** Track in `src/commands/chat.ts` when session starts
---
### ✅ `continue.cli.lines_of_code.count`
**Type:** Counter
**Unit:** `count`
**Description:** Count of lines of code modified
**Attributes:**
- All [standard attributes](#standard-attributes)
- `type`: (`"added"`, `"removed"`)
**Implementation:** Track in `src/tools/writeFile.ts` by analyzing file diffs
---
### ✅ `continue.cli.pull_request.count`
**Type:** Counter
**Unit:** `count`
**Description:** Number of pull requests created
**Attributes:**
- All [standard attributes](#standard-attributes)
**Implementation:** Track when `runTerminalCommand` executes git/gh commands for PR creation
---
### ✅ `continue.cli.commit.count`
**Type:** Counter
**Unit:** `count`
**Description:** Number of git commits created
**Attributes:**
- All [standard attributes](#standard-attributes)
**Implementation:** Track when `runTerminalCommand` executes `git commit` commands
---
### ✅ `continue.cli.cost.usage`
**Type:** Counter
**Unit:** `USD`
**Description:** Cost of the Continue CLI session
**Attributes:**
- All [standard attributes](#standard-attributes)
- `model`: Model identifier (e.g., "claude-3-5-sonnet-20241022", "gpt-4")
**Implementation:** Calculate costs based on token usage and model pricing in `src/streamChatResponse.ts`
---
### ✅ `continue.cli.token.usage`
**Type:** Counter
**Unit:** `tokens`
**Description:** Number of tokens used
**Attributes:**
- All [standard attributes](#standard-attributes)
- `type`: (`"input"`, `"output"`, `"cacheRead"`, `"cacheCreation"`)
- `model`: Model identifier (e.g., "claude-3-5-sonnet-20241022", "gpt-4")
**Implementation:** Track in `src/streamChatResponse.ts` after each API response
---
### ❌ `continue.cli.code_edit_tool.decision`
**Type:** Counter
**Unit:** `count`
**Description:** Count of code editing tool permission decisions
**Attributes:**
- All [standard attributes](#standard-attributes)
- `tool`: Tool name (`"writeFile"`, `"runTerminalCommand"`, etc.)
- `decision`: User decision (`"accept"`, `"reject"`)
- `language`: Programming language of the edited file (e.g., `"TypeScript"`, `"Python"`, `"JavaScript"`, `"Markdown"`). Returns `"unknown"` for unrecognized file extensions.
**Implementation:** Track in tool execution when user confirmation is required (if implemented)
---
### ✅ `continue.cli.active_time.total`
**Type:** Counter
**Unit:** `s`
**Description:** Total active time in seconds
**Attributes:**
- All [standard attributes](#standard-attributes)
**Implementation:** Track in TUI mode (`src/ui/TUIChat.tsx`) and standard chat mode, measuring time during active interactions
## Core Events
### ✅ User Prompt Event
**Event Name:** `continue.cli.user_prompt`
**Attributes:**
- All [standard attributes](#standard-attributes)
- `event.name`: `"user_prompt"`
- `event.timestamp`: ISO 8601 timestamp
- `prompt_length`: Length of the prompt
- `prompt`: Prompt content (redacted by default, enable with `OTEL_LOG_USER_PROMPTS=1`)
**Implementation:** Log in `src/streamChatResponse.ts` when user message is added to chat history
---
### ✅ Tool Result Event
**Event Name:** `continue.cli.tool_result`
**Attributes:**
- All [standard attributes](#standard-attributes)
- `event.name`: `"tool_result"`
- `event.timestamp`: ISO 8601 timestamp
- `tool_name`: Name of the tool
- `success`: `"true"` or `"false"`
- `duration_ms`: Execution time in milliseconds
- `error`: Error message (if failed)
- `decision`: Either `"accept"` or `"reject"` (if applicable)
- `source`: Decision source - `"config"`, `"user_permanent"`, `"user_temporary"`, `"user_abort"`, or `"user_reject"` (if applicable)
- `tool_parameters`: JSON string containing tool-specific parameters (when available)
**Implementation:** Log in `src/tools/index.ts` `executeToolCall` function
---
### ✅ API Request Event
**Event Name:** `continue.cli.api_request`
**Attributes:**
- All [standard attributes](#standard-attributes)
- `event.name`: `"api_request"`
- `event.timestamp`: ISO 8601 timestamp
- `model`: Model identifier
- `duration_ms`: Request duration in milliseconds
- `success`: `"true"` or `"false"`
- `error`: Error message (if failed)
- `input_tokens`: Number of input tokens
- `output_tokens`: Number of output tokens
- `cost_usd`: Request cost in USD
**Implementation:** Log in `src/streamChatResponse.ts` for each API request
## Additional Metrics
These metrics are unique to Continue CLI and provide additional insights without conflicting with compatibility:
### Authentication Metrics
#### ✅ `continue.cli.auth.attempts`
**Type:** Counter
**Unit:** `{attempt}`
**Description:** Authentication attempts
**Labels:**
- All [standard attributes](#standard-attributes)
- `result`: `success` | `failure` | `cancelled`
- `method`: `workos` | `token`
**Implementation:** Track in `src/auth/workos.ts`
### MCP Integration Metrics
#### ❌ `continue.cli.mcp.connections`
**Type:** Gauge
**Unit:** `{connection}`
**Description:** Active MCP connections
**Labels:**
- All [standard attributes](#standard-attributes)
- `server_name`: MCP server identifier
- `status`: `connected` | `disconnected` | `error`
**Implementation:** Track in `src/mcp.ts`
### Performance Metrics
#### ❌ `continue.cli.startup.time`
**Type:** Histogram
**Unit:** `ms`
**Description:** Time from CLI start to ready state
**Labels:**
- All [standard attributes](#standard-attributes)
- `mode`: `tui` | `headless` | `standard`
- `cold_start`: `true` | `false`
**Implementation:** Track in `src/index.ts` and `src/commands/chat.ts`
#### ✅ `continue.cli.response_time`
**Type:** Histogram
**Unit:** `ms`
**Description:** LLM response time metrics (supplements API request events)
**Labels:**
- All [standard attributes](#standard-attributes)
- `model`: Model identifier
- `metric_type`: `time_to_first_token` | `total_response_time`
- `has_tools`: `true` | `false`
**Implementation:** Track in `src/streamChatResponse.ts`
## Implementation Guidelines
### Migration from Claude Code Dashboards
The core metrics (`session.count`, `lines_of_code.count`, `token.usage`, `cost.usage`, etc.) use identical naming and attribute structures to Claude Code, allowing for easy dashboard migration by simply changing the metric prefix from `claude_code.*` to `continue.cli.*`.
### Privacy Considerations
- **No PII**: Avoid logging file paths, user content, or other personally identifiable information
- **Redacted by Default**: User prompts are redacted unless `OTEL_LOG_USER_PROMPTS=1`
- **Configurable Attributes**: Use cardinality control variables to manage data granularity
- **Opt-out**: Provide mechanism to disable telemetry entirely
### Resource Attributes
All metrics should include these resource attributes:
- `service.name`: `continue-cli`
- `service.version`: CLI version
- `deployment.environment`: `development` | `production`
- `os.type`: Operating system
- `process.pid`: Process ID
### Implementation Points
1. **Session Tracking**: Initialize session ID and track lifecycle in `src/commands/chat.ts`
2. **Token/Cost Tracking**: Implement in `src/streamChatResponse.ts` with model-specific pricing
3. **Tool Usage**: Track in `src/tools/index.ts` and individual tool implementations
4. **File Operations**: Implement diff analysis in `src/tools/writeFile.ts` for LOC tracking
5. **Command Detection**: Parse git/gh commands in `src/tools/runTerminalCommand.ts`
6. **Authentication**: Track auth flows in `src/auth/workos.ts`
7. **Performance**: Add timing measurements throughout the application lifecycle
## Implementation Status
✅ = Implemented
❌ = Not implemented yet
**Core metrics:** 6/7 implemented (83%)
**Core events:** 3/3 implemented (100%)
**Additional metrics:** 4/7 implemented (57%)
**Missing implementations:**
- `continue.cli.code_edit_tool.decision` - requires user confirmation UI
- `continue.cli.mcp.connections` - needs MCP service monitoring
- `continue.cli.startup.time` - needs startup time tracking

View file

@ -0,0 +1,112 @@
# Permissions
## Permission types
To make sure that users can oversee the actions of the LLM, we implement a permissions system. Every tool has one of the following permissions:
- `allow`: The tool will be automatically called without asking
- `ask`: We will ask the user before calling the tool, giving them the options to accept or reject
- `exclude`: This tool will be completely excluded, so the model won't even know it exists
## Rule precedence
There is a default set of permissions for the builtin tools in [`src/permissions/defaultPolicies.ts`](../src/permissions/defaultPolicies.ts). But these policies can be overriden by multiple layers. The order of precedence is as follows, which the earlier items taking precedence:
1. **Mode policies** (highest priority - see [modes.md](./modes.md))
2. Command line flags (`--allow`, `--ask`, `--exclude`)
3. Permissions in `config.yaml` / configuration
4. Permissions in `~/.continue/permissions.yaml`
5. Default policies
**Note:** Mode policies **completely override all other permission settings** in plan and auto modes. Available modes:
- `normal`: No mode policies (uses existing configuration)
- `plan`: **Absolute override** - excludes all write tools, allows only read tools (ignores user config)
- `auto`: **Absolute override** - allows all tools without asking (ignores user config)
## Tool matching patterns
We use a tool matching pattern to match tools to permissions. This format looks like the following:
- `Read` matches any call to the `Read` tool
- `Read(*)` also matches any call to the `Read` tool
- `Read(**/*.ts)` matches any call to the `Read` tool where the primary parameter matches the glob pattern `**/*.ts`.
Note that for an `exclude` policy, it doesn't make sense to have argument matching.
## Command line flags
Each of the `--allow`, `--ask`, and `--exclude` flags allow you to set the permission for a tool. Usage must be a "tool matching pattern" as described above for each flag, with each providing a policy that will be added to the list of policies in order.
```bash
# Allow Read, Ask Write, and Exclude Bash
cn --allow Read --ask Write --exclude Bash
# Start in plan mode (read-only tools only)
cn --readonly "Help me understand this codebase"
# Use mode switching during chat
cn "Let me work on this feature" # Starts in normal mode
# Then use Shift+Tab to cycle through modes
```
## `config.yaml` / Configuration (implement later)
::: info
This should not be implemented yet.
:::
To let users define their permissions as a part of their custom assistant, they can do so in the permissions section of `config.yaml` or their configuration:
```yaml
permissions:
allow:
- Read(*)
ask:
- Write(**/*.py)
exclude:
- Write
```
## `~/.continue/permissions.yaml` (personal settings)
It would be frustrating for users to have to set the same permissions across all of their assistants, so we provide them a file for personal settings. It should be basically equivalent to the `permissions` section of `config.yaml`:
```yaml title="~/.continue/permissions.yaml"
allow:
- Read(*)
ask:
- Write(**/*.py)
exclude:
- Write
```
Except that it's important to understand that this file is _not_ intended to be edited by the user. It is only for persistence, and users should interact with their permissions by using the TUI.
This file should be created the first time that the CLI starts.
## Headless mode permissions
When running in headless mode (using the `-p` or `--print` flag), the CLI uses the same default policies as normal mode, but with different behavior for tools that require confirmation:
- **Normal mode**: Write operations and terminal commands require confirmation (`ask`) - user is prompted
- **Headless mode**: Same default policies, but tools requiring confirmation (`ask`) will cause the process to exit with an error message
To use tools that normally require confirmation in headless mode, you must explicitly allow them:
```bash
# Headless mode with explicit permissions for write operations
cn -p --allow write_file "Write a hello world script"
# Headless mode with wildcard permission (allow all tools)
cn -p --allow "*" "Write and run a script"
# Headless mode with specific restrictions
cn -p --exclude run_terminal_command "Clean up the codebase"
```
This approach ensures that headless mode is secure by default while providing clear guidance on how to enable the needed permissions.

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