Merge branch 'main' into chunk_query

This commit is contained in:
Nate 2025-03-16 13:13:40 -07:00
commit 2adab6f828
471 changed files with 12941 additions and 5903 deletions

View file

@ -0,0 +1,5 @@
## 0.0.92 - 2025-02-26
### Fixed
* Off-screen rendering to solve white flash on load and lack of changing cursor type
* OSR-related fixes for non-Mac users
* Fixes for inline edit in JetBrains

View file

@ -0,0 +1,7 @@
## 1.0.0 - 2025-02-26
### Added
* Introduces hub.continue.dev
* Improved theme matching
### Fixed
* Fixes interference between SonarQube and Continue autocomplete
* Numerous reliability improvements

View file

@ -0,0 +1,6 @@
## 1.0.0 - 2025-02-26
### Added
* Introduces hub.continue.dev
* Improved apply quality
### Fixed
* Numerous reliability improvements

View file

@ -1,5 +0,0 @@
project: extensions/intellij
kind: Fixed
body: Off-screen rendering to solve white flash on load and lack of changing cursor
type
time: 2024-10-07T18:38:20.733658-07:00

View file

@ -1,4 +0,0 @@
project: extensions/intellij
kind: Fixed
body: OSR-related fixes for non-Mac users
time: 2024-11-08T11:43:22.623155-08:00

View file

@ -1,4 +0,0 @@
project: extensions/intellij
kind: Fixed
body: Fixes for inline edit in JetBrains
time: 2024-11-08T11:47:07.953304-08:00

View file

@ -4,7 +4,7 @@ description: Generate unit tests for core utilities
Write jest tests for the provided code.
Use jest version ^29 (e.g. jest 29.7.0)
Use best practices. Be clear and consise.
Use best practices. Be clear and concise.
Aim for 100% code coverage where reasonable.
Multiple tests can be written, split up tests for best clarity and readability.
Only use typescript, and if the file/code is not typescript, warn the user.
@ -15,7 +15,7 @@ Use double quotes (or backticks if needed) for strings
The code being tested is used in IDE extensions, and it:
- accesses code workspaces through the IDE ("workspace directories")
- persists extension-related data to the the local machine of the user ("global directory"), and
- uses configuration via a `ConfigHandler`, which is stored in either the global directory (default) or accesed via a remote "control plane" using the `ControlPlaneClient`
- uses configuration via a `ConfigHandler`, which is stored in either the global directory (default) or accessed via a remote "control plane" using the `ControlPlaneClient`
Jest testing setup includes
- @core/test/jest.global-setup.ts initializes a temporary global directory, which is where files that store persisted extension data live.
@ -31,7 +31,7 @@ Jest testing setup includes
Do NOT write tests for any files in `core/test`, only use them as helpers for testing other files. If no other files are provided, warn the user and write no tests.
IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock 3rd party modules, etc. when sensible.
IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock 3rd party modules, etc. when sensible.
Instead, generate actual mock files and data for operations
Pure mocks should only be used to emulate specific network responses/error or hard-to-duplicate errors, or to prevent long-duration tests

View file

@ -5,4 +5,5 @@ docs/docs/languages
.vscode/
.archive/
**/*.scm
**/*.diff
**/*.diff
.continue/

1
.github/CODEOWNERS vendored Normal file
View file

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

View file

@ -27,8 +27,7 @@ body:
- **Continue version**: v0.9.4
- **IDE version**: VSCode 1.85.1
- Model: Claude Sonnet 3.5
- config.yaml: `models: ...`
- OR config.json: `{ "models": ... }`
- Assistant configuration
value: |
- OS:
- Continue version:
@ -38,6 +37,7 @@ body:
```yaml
```
OR link to assistant in Continue hub:
render: Markdown
validations:
required: false

View file

@ -31,7 +31,7 @@ jobs:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v0.0.*-jetbrains ]]; then
if [[ "${{ github.event.release.tag_name }}" == v1.0.*-jetbrains ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT

View file

@ -20,7 +20,7 @@ jobs:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v0.8.*-vscode ]]; then
if [[ "${{ github.event.release.tag_name }}" == v1.0.*-vscode ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT

View file

@ -4,10 +4,12 @@ on:
pull_request:
branches:
- main
- staging
push:
branches:
- main
- staging
jobs:
install-root:
@ -273,7 +275,7 @@ jobs:
cd core
npm test
env:
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork }}
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
@ -301,7 +303,13 @@ jobs:
cd extensions/vscode
npm ci
npm run e2e:compile
FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .)
if [[ "${{ github.event.pull_request.head.repo.fork }}" == "true" || "${{ github.actor }}" == "dependabot[bot]" ]]; then
# Exclude SSH tests for forks
FILES=$(ls -1 e2e/_output/tests/*.test.js | grep -v "SSH" | jq -R . | jq -s .)
else
# Include all tests for non-forks
FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .)
fi
echo "test_file_matrix<<EOF" >> $GITHUB_OUTPUT
echo "$FILES" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
@ -407,6 +415,13 @@ jobs:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
# We don't want to cache the Continue extension, so it is deleted at the end of the job
- uses: actions/cache@v4
id: test-extensions-cache
with:
path: extensions/vscode/e2e/.test-extensions
key: CONSTANT
- name: Download build artifact
uses: actions/download-artifact@v4
with:
@ -434,7 +449,7 @@ jobs:
chmod 600 ~/.ssh/id_rsa
ssh-keyscan -H "$SSH_HOST" >> ~/.ssh/known_hosts
echo -e "Host ssh-test-container\n\tHostName $SSH_HOST\n\tUser ec2-user\n\tIdentityFile ~/.ssh/id_rsa" >> ~/.ssh/config
if: ${{ github.event.pull_request.head.repo.fork == false }}
if: ${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }}
- name: Set up Xvfb
run: |
@ -444,10 +459,15 @@ jobs:
- name: Run e2e tests
run: |
cd extensions/vscode
IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }}
IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }}
env:
DISPLAY: :99
- name: Delete continue from test extensions
run: |
cd extensions/vscode
rm -rf e2e/.test-extensions/continue*
- name: Upload e2e test screenshots
if: failure()
uses: actions/upload-artifact@v4

View file

@ -20,7 +20,7 @@ jobs:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v0.9.*-vscode ]]; then
if [[ "${{ github.event.release.tag_name }}" == v1.1.*-vscode ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT
@ -217,8 +217,8 @@ jobs:
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
- name: Pull latest changes
run: git pull origin main
- name: Pull latest changes from release
run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }}
# 1. Download the artifacts
- uses: actions/download-artifact@v4

View file

@ -0,0 +1,25 @@
name: "Label / close stale issues"
on:
schedule:
- cron: "30 1 * * *"
jobs:
stale:
permissions:
issues: write
pull-requests: write
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
with:
close-issue-message: "This issue was closed because it wasn't updated for 10 days after being marked stale. If it's still important, please reopen + comment and we'll gladly take another look!"
stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after an additional 10 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue."
days-before-stale: 90
days-before-close: 10
days-before-pr-stale: -1
days-before-pr-close: -1
operations-per-run: 1000
stale-issue-label: "stale"
stale-pr-label: "stale"
exempt-issue-labels: "needs-triage,no-stale,high,highest"
exempt-pr-labels: "no-stale"

3
.gitignore vendored
View file

@ -168,4 +168,5 @@ extensions/.continue-debug/
*.vsix
.continuerules
.continuerules
**/.continue/assistants/

View file

@ -14,4 +14,5 @@ gui/dist
**/.continueignore
CHANGELOG.md
**/continue_tutorial.py
**/node_modules
**/node_modules
**/CODEOWNERS

19
.vscode/launch.json vendored
View file

@ -138,6 +138,25 @@
"env": {
"NODE_OPTIONS": "--experimental-vm-modules"
}
},
{
"name": "[config-yaml] Jest Test Debugger, Current Open File",
"type": "node",
"request": "launch",
"runtimeArgs": [
"--inspect-brk",
"${workspaceRoot}/packages/config-yaml/node_modules/jest/bin/jest.js",
"--runInBand",
"--config",
"${workspaceRoot}/packages/config-yaml/jest.config.mjs",
"${relativeFile}"
],
"cwd": "${workspaceRoot}/packages/config-yaml",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"env": {
"NODE_OPTIONS": "--experimental-vm-modules"
}
}
]
}

View file

@ -13,6 +13,9 @@
"args": ["-l"]
}
},
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit"
},
"editor.defaultFormatter": "esbenp.prettier-vscode",
"search.exclude": {
"**/package-lock.json": true,

22
.vscode/tasks.json vendored
View file

@ -71,7 +71,27 @@
}
]
},
// Build the React app. It gets bundled into the extension as a file resource and has a seprate build step
{
"label": "vscode-extension:package",
"dependsOn": ["vscode-extension:esbuild"],
"type": "npm",
"script": "package",
"path": "extensions/vscode",
"problemMatcher": [
{
"pattern": [
{
"regexp": "> (.*?):([0-9]+):([0-9]+): (warning|error): (.+)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
]
}
]
},
{
"label": "vscode-extension:continue-ui:build",
"type": "shell",

View file

@ -128,7 +128,7 @@ nvm use
1. The new VS Code window with the extension is referred to as the _Host VS Code_
2. The window you started debugging from is referred to as the _Main VS Code_
3. To package the extension, run `npm run package` in the `extensions/vscode` directory. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX".
3. To package the extension, run `npm run package` in the `extensions/vscode` directory, select `Tasks: Run Task` and then select `vscode-extension:package`. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX".
##### Debugging

View file

@ -8,7 +8,7 @@
<div align="center">
**[Continue](https://docs.continue.dev) is the leading open-source AI code assistant. You can connect any models and any context to build custom autocomplete and chat experiences inside [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)**
**[Continue](https://docs.continue.dev) enables developers to create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
</div>
@ -46,7 +46,7 @@
## Actions
[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases.
[Actions](https://continue.dev/docs/actions/how-to-use-it) are shortcuts for common use cases
![actions](docs/static/img/actions.gif)

View file

@ -285,7 +285,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
// Informs the `continue-binary` of where to look for node_sqlite3.node
// https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
// fs.writeFileSync(`${targetDir}/package.json`, "");
fs.writeFileSync(`${targetDir}/package.json`, "");
}
// Cleanup - this is needed when running locally

View file

@ -0,0 +1,6 @@
const path = require('path');
process.env.CONTINUE_DEVELOPMENT = true;
process.env.CONTINUE_GLOBAL_DIR = path.join(process.env.PROJECT_DIR, 'extensions', '.continue-debug');
require('./out/index.js');

View file

@ -44,17 +44,17 @@
"version": "1.0.13",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
"@aws-sdk/client-sagemaker-runtime": "^3.758.0",
"@aws-sdk/credential-providers": "^3.758.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "^1.0.28",
"@continuedev/config-yaml": "^1.0.52",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/openai-adapters": "^1.0.10",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@octokit/rest": "^20.1.1",
"@typescript-eslint/eslint-plugin": "^7.8.0",
"@xenova/transformers": "2.14.0",
"adf-to-md": "^1.1.0",
@ -107,7 +107,7 @@
"wink-nlp-utils": "^2.1.0",
"workerpool": "^9.1.3",
"yaml": "^2.4.2",
"zod": "^3.23.8"
"zod": "^3.24.2"
},
"devDependencies": {
"@babel/preset-env": "^7.24.7",
@ -128,7 +128,7 @@
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
"cross-env": "^7.0.3",
"esbuild": "0.24.0",
"esbuild": "0.17.19",
"eslint": "^8",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",

20
binary/prompt-logs.js Normal file
View file

@ -0,0 +1,20 @@
const fs = require('fs');
const path = require('path');
const logDirPath = path.join(__dirname, '..', 'extensions', '.continue-debug', 'logs');
const logFilePath = path.join(logDirPath, "prompt.log");
if (!fs.existsSync(logDirPath)) {
fs.mkdirSync(logDirPath, { recursive: true });
}
if (!fs.existsSync(logFilePath)) {
fs.createWriteStream(logFilePath).end();
}
console.log("Watching logs at " + logFilePath)
fs.watch(logFilePath, () => {
// console.clear();
fs.createReadStream(logFilePath).pipe(process.stdout);
});

View file

@ -134,6 +134,13 @@ export class CompletionProvider {
token: AbortSignal | undefined,
): Promise<AutocompleteOutcome | undefined> {
try {
// Create abort signal if not given
if (!token) {
const controller = this.loggingService.createAbortController(
input.completionId,
);
token = controller.signal;
}
const startTime = Date.now();
const options = await this._getAutocompleteOptions();
@ -158,14 +165,6 @@ export class CompletionProvider {
return undefined;
}
// Create abort signal if not given
if (!token) {
const controller = this.loggingService.createAbortController(
input.completionId,
);
token = controller.signal;
}
const [snippetPayload, workspaceDirs] = await Promise.all([
getAllSnippets({
helper,
@ -263,7 +262,7 @@ export class CompletionProvider {
// When using the JetBrains extension, Mark as displayed
const ideType = (await this.ide.getIdeInfo()).ideType;
if (ideType === "jetbrains") {
if (ideType.toLowerCase() === "jetbrains") {
this.markDisplayed(input.completionId, outcome);
}

View file

@ -240,6 +240,14 @@ export const Solidity = {
endOfLine: [";"],
};
// Lua
export const Lua = {
name: "Lua",
topLevelKeywords: ["function"],
singleLineComment: "--",
endOfLine: [],
};
// YAML
export const YAML: AutocompleteLanguageInfo = {
name: "YAML",
@ -367,6 +375,8 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
yaml: YAML,
yml: YAML,
md: Markdown,
lua: Lua,
luau: Lua,
};
export function languageForFilepath(fileUri: string): AutocompleteLanguageInfo {

View file

@ -399,7 +399,8 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
lowerCaseModel.includes("gpt") ||
lowerCaseModel.includes("davinci-002") ||
lowerCaseModel.includes("claude") ||
lowerCaseModel.includes("granite3")
lowerCaseModel.includes("granite3") ||
lowerCaseModel.includes("granite-3")
) {
return holeFillerTemplate;
}

View file

@ -1,4 +1,4 @@
import { logDevData } from "../../util/devdata";
import { DataLogger } from "../../data/log";
import { COUNT_COMPLETION_REJECTED_AFTER } from "../../util/parameters";
import { Telemetry } from "../../util/posthog";
import { getUriFileExtension } from "../../util/uri";
@ -96,7 +96,14 @@ export class AutocompleteLoggingService {
}
private logAutocompleteOutcome(outcome: AutocompleteOutcome) {
logDevData("autocomplete", outcome);
void DataLogger.getInstance().logDevData({
name: "autocomplete",
data: {
...outcome,
useFileSuffix: true, // from outdated schema
},
});
const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
void Telemetry.capture(
"autocomplete",

View file

@ -10,7 +10,7 @@ export function slashFromCustomCommand(
return {
name: customCommand.name,
description: customCommand.description ?? "",
run: async function* ({ input, llm, history, ide }) {
run: async function* ({ input, llm, history, ide, completionOptions }) {
// Remove slash command prefix from input
let userInput = input;
if (userInput.startsWith(`/${customCommand.name}`)) {
@ -20,11 +20,16 @@ export function slashFromCustomCommand(
}
// Render prompt template
const promptUserInput = await renderTemplatedString(
customCommand.prompt,
ide.readFile.bind(ide),
{ input: userInput },
);
let promptUserInput: string;
if (customCommand.prompt.includes("{{{ input }}}")) {
promptUserInput = await renderTemplatedString(
customCommand.prompt,
ide.readFile.bind(ide),
{ input: userInput },
);
} else {
promptUserInput = customCommand.prompt + "\n\n" + userInput;
}
const messages = [...history];
// Find the last chat message with this slash command and replace it with the user input
@ -67,6 +72,7 @@ export function slashFromCustomCommand(
for await (const chunk of llm.streamChat(
messages,
new AbortController().signal,
completionOptions,
)) {
yield renderChatMessage(chunk);
}

View file

@ -2,8 +2,7 @@ import ignore from "ignore";
import type { FileType, IDE, SlashCommand } from "../..";
import {
defaultIgnoreDir,
defaultIgnoreFile,
DEFAULT_IGNORE,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "../../indexing/ignore";
@ -58,10 +57,7 @@ const OnboardSlashCommand: SlashCommand = {
};
async function getEntriesFilteredByIgnore(dir: string, ide: IDE) {
const ig = ignore()
.add(defaultIgnoreDir)
.add(defaultIgnoreFile)
.add(getGlobalContinueIgArray());
const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray());
const entries = await ide.listDir(dir);
const ignoreUri = joinPathsToUri(dir, ".gitignore");

View file

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

View file

@ -1,11 +1,4 @@
import * as fs from "node:fs";
import {
AssistantUnrolled,
ConfigResult,
FullSlug,
} from "@continuedev/config-yaml";
import * as YAML from "yaml";
import { ConfigResult, FullSlug } from "@continuedev/config-yaml";
import {
ControlPlaneClient,
@ -22,9 +15,8 @@ import {
} from "../index.js";
import Ollama from "../llm/llms/Ollama.js";
import { GlobalContext } from "../util/GlobalContext.js";
import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js";
import { localPathToUri } from "../util/pathToUri.js";
import { getAllAssistantFiles } from "./loadLocalAssistants.js";
import {
LOCAL_ONBOARDING_CHAT_MODEL,
LOCAL_ONBOARDING_PROVIDER_TITLE,
@ -36,7 +28,6 @@ import {
ProfileDescription,
ProfileLifecycleManager,
} from "./ProfileLifecycleManager.js";
import { clientRenderHelper } from "./yaml/clientRender.js";
export type { ProfileDescription };
@ -47,59 +38,97 @@ type ConfigUpdateFunction = (payload: ConfigResult<ContinueConfig>) => void;
export class ConfigHandler {
private readonly globalContext = new GlobalContext();
private additionalContextProviders: IContextProvider[] = [];
private profiles: ProfileLifecycleManager[];
private selectedProfileId: string | null;
private selectedOrgId: string | null;
private profiles: ProfileLifecycleManager[] | null = null; // null until profiles are loaded
private selectedProfileId: string | null = null;
private localProfileManager: ProfileLifecycleManager;
controlPlaneClient: ControlPlaneClient;
initializedPromise: Promise<void>;
constructor(
private readonly ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private readonly writeLog: (text: string) => Promise<void>,
private controlPlaneClient: ControlPlaneClient,
sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
private readonly didSelectOrganization?: (orgId: string | null) => void,
) {
this.ide = ide;
this.ideSettingsPromise = ideSettingsPromise;
this.writeLog = writeLog;
this.controlPlaneClient = new ControlPlaneClient(
sessionInfoPromise,
ideSettingsPromise,
);
// Set local profile as default
const localProfileLoader = new LocalProfileLoader(
ide,
ideSettingsPromise,
controlPlaneClient,
this.controlPlaneClient,
writeLog,
);
this.localProfileManager = new ProfileLifecycleManager(
localProfileLoader,
this.ide,
);
this.profiles = [this.localProfileManager];
this.selectedProfileId = localProfileLoader.description.id;
this.selectedOrgId = null;
void this.init();
// Profiles are loaded asynchronously
this.initializedPromise = new Promise((resolve, reject) => {
this.init()
.then(() => {
resolve();
})
.catch((e) => {
reject(e);
});
});
}
/**
* Users can define as many local assistants as they want in a `.continue/assistants` folder
*/
private async getLocalAssistantProfiles() {
const assistantFiles = await getAllAssistantFiles(this.ide);
const profiles = assistantFiles.map((assistant) => {
return new LocalProfileLoader(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
this.writeLog,
assistant,
);
});
return profiles.map(
(profile) => new ProfileLifecycleManager(profile, this.ide),
);
}
/**
* Retrieves the titles of additional context providers that are of type "submenu".
*
* @returns {string[]} An array of titles of the additional context providers that have a description type of "submenu".
*/
getAdditionalSubmenuContextProviders(): string[] {
return this.additionalContextProviders
.filter((provider) => provider.description.type === "submenu")
.map((provider) => provider.description.title);
}
private async init() {
// Always load local profile immediately in case control plane doesn't load
try {
await this.loadConfig();
await this.fetchControlPlaneProfiles();
} catch (e) {
// If this fails, make sure at least local profile is loaded
console.error("Failed to fetch control plane profiles in init: ", e);
await this.loadLocalProfilesOnly();
}
try {
const configResult = await this.loadConfig();
this.notifyConfigListeners(configResult);
} catch (e) {
console.error("Failed to load config: ", e);
}
const workspaceId = await this.getWorkspaceId();
const lastSelectedOrgIds =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
const selectedOrgId = lastSelectedOrgIds[workspaceId];
// We want to set the org ID before fetching control plane profiles
if (selectedOrgId) {
this.selectedOrgId = selectedOrgId;
}
// Load control plane profiles
void this.fetchControlPlaneProfiles();
}
get currentProfile() {
@ -110,101 +139,120 @@ export class ConfigHandler {
// We must fall back to null, not the first or local profiles
// Because GUI must be the source of truth for selected profile
return (
this.profiles.find(
this.profiles?.find(
(p) => p.profileDescription.id === this.selectedProfileId,
) ?? this.profiles[0]
) ?? null
);
}
get inactiveProfiles() {
return this.profiles.filter(
return (this.profiles ?? []).filter(
(p) => p.profileDescription.id !== this.selectedProfileId,
);
}
async openConfigProfile(profileId?: string) {
let openProfileId = profileId || this.selectedProfileId;
if (openProfileId === "local") {
const profile = this.profiles?.find(
(p) => p.profileDescription.id === openProfileId,
);
if (profile?.profileDescription.profileType === "local") {
const ideInfo = await this.ide.getIdeInfo();
const configYamlPath = getConfigYamlPath(ideInfo.ideType);
if (fs.existsSync(configYamlPath)) {
await this.ide.openFile(localPathToUri(configYamlPath));
} else {
await this.ide.openFile(localPathToUri(getConfigJsonPath()));
}
await this.ide.openFile(profile.profileDescription.uri);
} else {
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
}
}
async loadPlatformProfiles() {
async listOrganizations() {
return await this.controlPlaneClient.listOrganizations();
}
async loadAssistantsForSelectedOrg() {
// Get the profiles and create their lifecycle managers
this.controlPlaneClient
.listAssistants(this.selectedOrgId)
.then(async (assistants) => {
const hubProfiles = await Promise.all(
assistants.map(async (assistant) => {
let renderedConfig: AssistantUnrolled | undefined = undefined;
if (assistant.configResult.config) {
renderedConfig = await clientRenderHelper(
{
ownerSlug: assistant.ownerSlug,
packageSlug: assistant.packageSlug,
},
YAML.stringify(assistant.configResult.config),
this.ide,
this.controlPlaneClient,
);
}
const userId = await this.controlPlaneClient.userId;
const selectedOrgId = await this.getSelectedOrgId();
const profileLoader = new PlatformProfileLoader(
{ ...assistant.configResult, config: renderedConfig },
assistant.ownerSlug,
assistant.packageSlug,
assistant.iconUrl,
assistant.configResult.config?.version ?? "latest",
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
this.writeLog,
this.reloadConfig.bind(this),
);
let profiles: ProfileLifecycleManager[] | null = null;
if (!userId) {
// Not logged in
const allLocalProfiles = await this.getAllLocalProfiles();
profiles = [...allLocalProfiles];
} else {
// Logged in
const assistants =
await this.controlPlaneClient.listAssistants(selectedOrgId);
return new ProfileLifecycleManager(profileLoader, this.ide);
}),
);
this.profiles =
this.selectedOrgId === null
? [this.localProfileManager, ...hubProfiles]
: hubProfiles;
this.notifyProfileListeners(
this.profiles.map((profile) => profile.profileDescription),
);
// Check the last selected workspace, and reload if it isn't local
const workspaceId = await this.getWorkspaceId();
const lastSelectedIds =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
const selectedProfileId = lastSelectedIds[workspaceId];
if (selectedProfileId) {
this.selectedProfileId = selectedProfileId;
await this.loadConfig();
} else {
// Otherwise we stick with local profile, and record choice
lastSelectedIds[workspaceId] = this.selectedProfileId;
this.globalContext.update(
"lastSelectedProfileForWorkspace",
lastSelectedIds,
const hubProfiles = await Promise.all(
assistants.map(async (assistant) => {
const profileLoader = await PlatformProfileLoader.create(
{
...assistant.configResult,
config: assistant.configResult.config,
},
assistant.ownerSlug,
assistant.packageSlug,
assistant.iconUrl,
assistant.configResult.config?.version ?? "latest",
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
this.writeLog,
this.reloadConfig.bind(this),
);
}
})
.catch((e) => {
console.error("Failed to list assistants: ", e);
});
return new ProfileLifecycleManager(profileLoader, this.ide);
}),
);
if (selectedOrgId === null) {
// Personal
const allLocalProfiles = await this.getAllLocalProfiles();
profiles = [...hubProfiles, ...allLocalProfiles];
} else {
// Organization
profiles = hubProfiles;
}
}
await this.updateAvailableProfiles(profiles);
}
private async getAllLocalProfiles() {
const localAssistantProfiles = await this.getLocalAssistantProfiles();
return [this.localProfileManager, ...localAssistantProfiles];
}
private async loadLocalProfilesOnly() {
const allLocalProfiles = await this.getAllLocalProfiles();
await this.updateAvailableProfiles(allLocalProfiles);
}
private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) {
this.profiles = profiles;
// If the last selected profile is in the list choose that
// Otherwise, choose the first profile
const previouslySelectedProfileId =
await this.getPersistedSelectedProfileId();
// Check if the previously selected profile exists in the current profiles
const profileExists = profiles.some(
(profile) =>
profile.profileDescription.id === previouslySelectedProfileId,
);
const selectedProfileId = profileExists
? previouslySelectedProfileId
: (profiles[0]?.profileDescription.id ?? null);
// Notify listeners
const profileDescriptions = profiles.map(
(profile) => profile.profileDescription,
);
this.notifyProfileListeners(profileDescriptions, selectedProfileId);
await this.setSelectedProfile(selectedProfileId);
}
private platformProfilesRefreshInterval: NodeJS.Timeout | undefined;
@ -230,8 +278,9 @@ export class ConfigHandler {
}
private async reloadHubAssistants() {
const selectedOrgId = await this.getSelectedOrgId();
const newFullSlugsList =
await this.controlPlaneClient.listAssistantFullSlugs(this.selectedOrgId);
await this.controlPlaneClient.listAssistantFullSlugs(selectedOrgId);
if (newFullSlugsList) {
const shouldReload = this.fullSlugsListsDiffer(
@ -239,7 +288,7 @@ export class ConfigHandler {
this.lastFullSlugsList,
);
if (shouldReload) {
await this.loadPlatformProfiles();
await this.loadAssistantsForSelectedOrg();
}
this.lastFullSlugsList = newFullSlugsList;
}
@ -248,7 +297,7 @@ export class ConfigHandler {
private async fetchControlPlaneProfiles() {
if (await useHub(this.ideSettingsPromise)) {
clearInterval(this.platformProfilesRefreshInterval);
await this.loadPlatformProfiles();
await this.loadAssistantsForSelectedOrg();
// Every 5 seconds we ask the platform whether there are any assistant updates in the last 5 seconds
// If so, we do the full (more expensive) reload
@ -257,61 +306,57 @@ export class ConfigHandler {
PlatformProfileLoader.RELOAD_INTERVAL,
);
} else {
this.controlPlaneClient
.listWorkspaces()
.then(async (workspaces) => {
this.profiles = [this.localProfileManager];
workspaces.forEach((workspace) => {
const profileLoader = new ControlPlaneProfileLoader(
workspace.id,
workspace.name,
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
this.writeLog,
this.reloadConfig.bind(this),
);
this.profiles.push(
new ProfileLifecycleManager(profileLoader, this.ide),
);
});
this.notifyProfileListeners(
this.profiles.map((profile) => profile.profileDescription),
try {
const workspaces = await this.controlPlaneClient.listWorkspaces();
const profiles = await this.getAllLocalProfiles();
workspaces.forEach((workspace) => {
const profileLoader = new ControlPlaneProfileLoader(
workspace.id,
workspace.name,
this.controlPlaneClient,
this.ide,
this.ideSettingsPromise,
this.writeLog,
this.reloadConfig.bind(this),
);
// Check the last selected workspace, and reload if it isn't local
const workspaceId = await this.getWorkspaceId();
const lastSelectedIds =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
const selectedProfileId = lastSelectedIds[workspaceId];
if (selectedProfileId) {
this.selectedProfileId = selectedProfileId;
await this.loadConfig();
} else {
// Otherwise we stick with local profile, and record choice
lastSelectedIds[workspaceId] = this.selectedProfileId;
this.globalContext.update(
"lastSelectedProfileForWorkspace",
lastSelectedIds,
);
}
})
.catch((e) => {
console.error(e);
profiles.push(new ProfileLifecycleManager(profileLoader, this.ide));
});
await this.updateAvailableProfiles(profiles);
} catch (e: any) {
console.error("Failed to load profiles: ", e);
await this.loadLocalProfilesOnly();
}
}
}
async getPersistedSelectedProfileId(): Promise<string | null> {
const workspaceId = await this.getWorkspaceId();
const lastSelectedIds =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
return lastSelectedIds[workspaceId] ?? null;
}
async getSelectedOrgId(): Promise<string | null> {
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
const workspaceId = await this.getWorkspaceId();
return selectedOrgs[workspaceId] ?? null;
}
async setSelectedOrgId(orgId: string | null) {
this.selectedOrgId = orgId;
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
selectedOrgs[await this.getWorkspaceId()] = orgId;
this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs);
this.didSelectOrganization?.(orgId);
}
async setSelectedProfile(profileId: string | null) {
console.log(
`Changing selected profile from ${this.selectedProfileId} to ${profileId}`,
);
this.selectedProfileId = profileId;
const result = await this.loadConfig();
this.notifyConfigListeners(result);
@ -343,21 +388,43 @@ export class ConfigHandler {
Promise.resolve(sessionInfo),
this.ideSettingsPromise,
);
this.fetchControlPlaneProfiles().catch((e) => {
// After login, default to the first org as the selected org
try {
const orgs = await this.controlPlaneClient.listOrganizations();
if (orgs.length) {
await this.setSelectedOrgId(orgs[0].id);
}
} catch (e) {
console.error("Failed to fetch control plane profiles: ", e);
}
this.fetchControlPlaneProfiles().catch(async (e) => {
console.error("Failed to fetch control plane profiles: ", e);
await this.loadLocalProfilesOnly();
await this.reloadConfig();
});
}
private profilesListeners: ((profiles: ProfileDescription[]) => void)[] = [];
private profilesListeners: ((
profiles: ProfileDescription[],
selectedProfileId: string | null,
) => void)[] = [];
onDidChangeAvailableProfiles(
listener: (profiles: ProfileDescription[]) => void,
listener: (
profiles: ProfileDescription[],
selectedProfileId: string | null,
) => void,
) {
this.profilesListeners.push(listener);
}
private notifyProfileListeners(profiles: ProfileDescription[]) {
private notifyProfileListeners(
profiles: ProfileDescription[],
selectedProfileId: string | null,
) {
for (const listener of this.profilesListeners) {
listener(profiles);
listener(profiles, selectedProfileId);
}
}
@ -410,8 +477,8 @@ export class ConfigHandler {
);
}
listProfiles(): ProfileDescription[] {
return this.profiles.map((p) => p.profileDescription);
listProfiles(): ProfileDescription[] | null {
return this.profiles?.map((p) => p.profileDescription) ?? null;
}
async loadConfig(): Promise<ConfigResult<ContinueConfig>> {

View file

@ -21,6 +21,7 @@ export interface ProfileDescription {
id: string;
iconUrl: string;
errors: ConfigValidationError[] | undefined;
uri: string;
}
export interface OrganizationDescription {
@ -77,14 +78,18 @@ export class ProfileLifecycleManager {
// Set pending config promise
this.pendingConfigPromise = new Promise(async (resolve, reject) => {
let result: ConfigResult<ContinueConfig>;
// This try catch is expected to catch high-level errors that aren't block-specific
// Like invalid json, invalid yaml, file read errors, etc.
// NOT block-specific loading errors
try {
result = await this.profileLoader.doLoadConfig();
} catch (e: any) {
} catch (e) {
const message = e instanceof Error ? e.message : "Error loading config";
result = {
errors: [
{
fatal: true,
message: e.message,
message,
},
],
config: undefined,
@ -99,7 +104,6 @@ export class ProfileLifecycleManager {
).concat(additionalContextProviders);
}
this.savedConfigResult = result;
resolve(result);
});

View file

@ -82,10 +82,12 @@ export const defaultConfig: SerializedContinueConfig = {
models: [],
contextProviders: defaultContextProvidersVsCode,
slashCommands: defaultSlashCommandsVscode,
data: [],
};
export const defaultConfigJetBrains: SerializedContinueConfig = {
models: [],
contextProviders: defaultContextProvidersJetBrains,
slashCommands: defaultSlashCommandsJetBrains,
data: [],
};

View file

@ -3,6 +3,11 @@ import * as fs from "fs";
import os from "os";
import path from "path";
import {
ConfigResult,
ConfigValidationError,
ModelRole,
} from "@continuedev/config-yaml";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import * as JSONC from "comment-json";
import * as tar from "tar";
@ -18,6 +23,7 @@ import {
EmbeddingsProviderDescription,
IContextProvider,
IDE,
IdeInfo,
IdeSettings,
IdeType,
ILLM,
@ -30,14 +36,16 @@ import {
import {
slashCommandFromDescription,
slashFromCustomCommand,
} from "../commands/index.js";
} from "../commands/index";
import { AllRerankers } from "../context/allRerankers";
import { MCPManagerSingleton } from "../context/mcp";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
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 PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider";
import { useHub } from "../control-plane/env";
import { allEmbeddingsProviders } from "../indexing/allEmbeddingsProviders";
import { BaseLLM } from "../llm";
import { llmFromDescription } from "../llm/llms";
@ -61,10 +69,8 @@ import {
getContinueDotEnv,
getEsbuildBinaryPath,
} from "../util/paths";
import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml";
import { useHub } from "../control-plane/env";
import { localPathToUri } from "../util/pathToUri";
import {
defaultContextProvidersJetBrains,
defaultContextProvidersVsCode,
@ -72,7 +78,8 @@ import {
defaultSlashCommandsVscode,
} from "./default";
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
import { modifyContinueConfigWithSharedConfig } from "./sharedConfig";
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
import { getModelByRole, isSupportedLanceDbCpuTargetForLinux } from "./util";
import { validateConfig } from "./validation.js";
export function resolveSerializedConfig(
@ -166,10 +173,9 @@ function loadSerializedConfig(
? [...defaultSlashCommandsVscode]
: [...defaultSlashCommandsJetBrains];
// Temporarily disabling this check until we can verify the commands are accuarate
// if (!isSupportedLanceDbCpuTarget(ide)) {
// config.disableIndexing = true;
// }
if (os.platform() === "linux" && !isSupportedLanceDbCpuTargetForLinux(ide)) {
config.disableIndexing = true;
}
return { config, errors, configLoadInterrupted: false };
}
@ -226,18 +232,12 @@ export function isContextProviderWithParams(
return (contextProvider as ContextProviderWithParams).name !== undefined;
}
const getCodebaseProvider = async (params: any) => {
const { default: CodebaseContextProvider } = await import(
"../context/providers/CodebaseContextProvider"
);
return new CodebaseContextProvider(params);
};
/** Only difference between intermediate and final configs is the `models` array */
async function intermediateToFinalConfig(
config: Config,
ide: IDE,
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
@ -272,7 +272,7 @@ async function intermediateToFinalConfig(
{
...desc,
model: modelName,
title: `${llm.title} - ${modelName}`,
title: modelName,
},
ide.readFile.bind(ide),
uniqueId,
@ -326,7 +326,7 @@ async function intermediateToFinalConfig(
...model.requestOptions,
...config.requestOptions,
};
model.roles = model.roles ?? ["chat"]; // Default to chat role if not specified
model.roles = model.roles ?? ["chat", "apply", "edit", "summarize"]; // Default to chat role if not specified
}
if (allowFreeTrial) {
@ -398,7 +398,7 @@ async function intermediateToFinalConfig(
new FileContextProvider({}),
// Add codebase provider if indexing is enabled
...(!config.disableIndexing
? [await getCodebaseProvider(codebaseContextParams)]
? [new CodebaseContextProvider(codebaseContextParams)]
: []),
// Add prompt files provider if enabled
...(loadPromptFiles ? [new PromptFilesContextProvider({})] : []),
@ -436,23 +436,28 @@ async function intermediateToFinalConfig(
}
// Embeddings Provider
const embeddingsProviderDescription = config.embeddingsProvider as
| EmbeddingsProviderDescription
| undefined;
if (embeddingsProviderDescription?.provider) {
const { provider, ...options } = embeddingsProviderDescription;
function getEmbeddingsILLM(
embedConfig: EmbeddingsProviderDescription | ILLM | undefined,
): ILLM | null {
if (!embedConfig) {
return null;
}
if ("providerName" in embedConfig) {
return embedConfig;
}
const { provider, ...options } = embedConfig;
const embeddingsProviderClass = allEmbeddingsProviders[provider];
if (embeddingsProviderClass) {
if (
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
) {
config.embeddingsProvider = new embeddingsProviderClass();
return new embeddingsProviderClass();
} else {
const llmOptions: LLMOptions = {
model: options.model ?? "UNSPECIFIED",
...options,
};
config.embeddingsProvider = new embeddingsProviderClass(
return new embeddingsProviderClass(
llmOptions,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
@ -461,59 +466,94 @@ async function intermediateToFinalConfig(
}),
);
}
} else {
errors.push({
fatal: false,
message: `Embeddings provider ${provider} not found. Using default`,
});
}
return null;
}
if (!config.embeddingsProvider) {
config.embeddingsProvider = new TransformersJsEmbeddingsProvider();
}
const newEmbedder = getEmbeddingsILLM(config.embeddingsProvider);
// Reranker
if (config.reranker && !(config.reranker as ILLM | undefined)?.rerank) {
function getRerankingILLM(
rerankingConfig: ILLM | RerankerDescription | undefined,
): ILLM | null {
if (!rerankingConfig) {
return null;
}
if ("providerName" in rerankingConfig) {
return rerankingConfig;
}
const { name, params } = config.reranker as RerankerDescription;
const rerankerClass = AllRerankers[name];
if (name === "llm") {
const llm = models.find((model) => model.title === params?.modelTitle);
if (!llm) {
console.warn(`Unknown model ${params?.modelTitle}`);
errors.push({
fatal: false,
message: `Unknown reranking model ${params?.modelTitle}`,
});
return null;
} else {
config.reranker = new LLMReranker(llm);
return new LLMReranker(llm);
}
} else if (rerankerClass) {
const llmOptions: LLMOptions = {
model: "rerank-2",
...params,
};
config.reranker = new rerankerClass(llmOptions);
return new rerankerClass(llmOptions);
}
return null;
}
const newReranker = getRerankingILLM(config.reranker);
let continueConfig: ContinueConfig = {
const continueConfig: ContinueConfig = {
...config,
contextProviders,
models,
embeddingsProvider: config.embeddingsProvider as any,
tabAutocompleteModels,
reranker: config.reranker as any,
tools: allTools,
modelsByRole: {
chat: models,
edit: models,
apply: models,
summarize: models,
autocomplete: [...tabAutocompleteModels],
embed: newEmbedder ? [newEmbedder] : [],
rerank: newReranker ? [newReranker] : [],
},
selectedModelByRole: {
chat: null, // Not implemented (uses GUI defaultModel)
edit: null,
apply: null,
embed: newEmbedder ?? null,
autocomplete: null,
rerank: newReranker ?? null,
summarize: null, // Not implemented
},
};
// Apply MCP if specified
const mcpManager = MCPManagerSingleton.getInstance();
if (config.experimental?.modelContextProtocolServers) {
await Promise.all(
const abortController = new AbortController();
const mcpConnectionTimeout = setTimeout(
() => abortController.abort(),
4000,
);
await Promise.allSettled(
config.experimental.modelContextProtocolServers?.map(
async (server, index) => {
const mcpId = index.toString();
const mcpConnection = mcpManager.createConnection(mcpId, server);
if (!mcpConnection) {
return;
}
const abortController = new AbortController();
try {
const mcpId = index.toString();
const mcpConnection = mcpManager.createConnection(mcpId, server);
if (!mcpConnection) {
return;
}
const mcpError = await mcpConnection.modifyConfig(
continueConfig,
mcpId,
@ -524,62 +564,133 @@ async function intermediateToFinalConfig(
if (mcpError) {
errors.push(mcpError);
}
} catch (e: any) {
} catch (e) {
let errorMessage = "Failed to load MCP server";
if (e instanceof Error) {
if (e.name === "AbortError") {
errorMessage += ": connection timed out";
} else {
errorMessage += ": " + e.message;
}
}
errors.push({
fatal: false,
message: `Failed to load MCP server: ${e.message}`,
message: errorMessage,
});
if (e.name !== "AbortError") {
throw e;
}
} finally {
clearTimeout(mcpConnectionTimeout);
}
},
) || [],
);
}
// Handle experimental modelRole config values for apply and edit
const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
if (inlineEditModel) {
const match = continueConfig.models.find(
(m) => m.title === inlineEditModel,
);
if (match) {
continueConfig.selectedModelByRole.edit = match;
continueConfig.modelsByRole.edit = [match]; // The only option if inlineEdit role is set
} else {
errors.push({
fatal: false,
message: `experimental.modelRoles.inlineEdit model title ${inlineEditModel} not found in models array`,
});
}
}
const applyBlockModel = getModelByRole(
continueConfig,
"applyCodeBlock",
)?.title;
if (applyBlockModel) {
const match = continueConfig.models.find(
(m) => m.title === applyBlockModel,
);
if (match) {
continueConfig.selectedModelByRole.apply = match;
continueConfig.modelsByRole.apply = [match]; // The only option if applyCodeBlock role is set
} else {
errors.push({
fatal: false,
message: `experimental.modelRoles.applyCodeBlock model title ${inlineEditModel} not found in models array`,
});
}
}
// Add transformers JS to the embed models list if not already added
if (
ideInfo.ideType === "vscode" &&
!continueConfig.modelsByRole.embed.find(
(m) => m.providerName === "transformers.js",
)
) {
continueConfig.modelsByRole.embed.push(
new TransformersJsEmbeddingsProvider(),
);
}
return { config: continueConfig, errors };
}
function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
return {
provider: llm.providerName,
model: llm.model,
title: llm.title ?? llm.model,
apiKey: llm.apiKey,
apiBase: llm.apiBase,
contextLength: llm.contextLength,
template: llm.template,
completionOptions: llm.completionOptions,
systemMessage: llm.systemMessage,
requestOptions: llm.requestOptions,
promptTemplates: llm.promptTemplates as any,
capabilities: llm.capabilities,
roles: llm.roles,
};
}
async function finalToBrowserConfig(
final: ContinueConfig,
ide: IDE,
): Promise<BrowserSerializedContinueConfig> {
return {
allowAnonymousTelemetry: final.allowAnonymousTelemetry,
models: final.models.map((m) => ({
provider: m.providerName,
model: m.model,
title: m.title ?? m.model,
apiKey: m.apiKey,
apiBase: m.apiBase,
contextLength: m.contextLength,
template: m.template,
completionOptions: m.completionOptions,
systemMessage: m.systemMessage,
requestOptions: m.requestOptions,
promptTemplates: m.promptTemplates as any,
capabilities: m.capabilities,
roles: m.roles,
})),
models: final.models.map(llmToSerializedModelDescription),
systemMessage: final.systemMessage,
completionOptions: final.completionOptions,
slashCommands: final.slashCommands?.map((s) => ({
name: s.name,
description: s.description,
params: s.params, //PZTODO: is this why params aren't referenced properly by slash commands?
params: s.params, // TODO: is this why params aren't referenced properly by slash commands?
})),
contextProviders: final.contextProviders?.map((c) => c.description),
disableIndexing: final.disableIndexing,
disableSessionTitles: final.disableSessionTitles,
userToken: final.userToken,
embeddingsProvider: final.embeddingsProvider?.embeddingId,
ui: final.ui,
experimental: final.experimental,
docs: final.docs,
tools: final.tools,
tabAutocompleteOptions: final.tabAutocompleteOptions,
usePlatform: await useHub(ide.getIdeSettings()),
modelsByRole: Object.fromEntries(
Object.entries(final.modelsByRole).map(([k, v]) => [
k,
v.map(llmToSerializedModelDescription),
]),
) as Record<ModelRole, ModelDescription[]>, // TODO better types here
selectedModelByRole: Object.fromEntries(
Object.entries(final.selectedModelByRole).map(([k, v]) => [
k,
v ? llmToSerializedModelDescription(v) : null,
]),
) as Record<ModelRole, ModelDescription | null>, // TODO better types here
// data not included here because client doesn't need
};
}
@ -767,7 +878,7 @@ async function loadContinueConfigFromJson(
ide: IDE,
workspaceConfigs: ContinueRcJson[],
ideSettings: IdeSettings,
ideType: IdeType,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
@ -781,7 +892,7 @@ async function loadContinueConfigFromJson(
} = loadSerializedConfig(
workspaceConfigs,
ideSettings,
ideType,
ideInfo.ideType,
overrideConfigJson,
ide,
);
@ -798,16 +909,16 @@ async function loadContinueConfigFromJson(
// Apply shared config
// TODO: override several of these values with user/org shared config
const sharedConfig = new GlobalContext().getSharedConfig();
const withShared = modifyContinueConfigWithSharedConfig(
serialized,
sharedConfig,
);
const withShared = modifyAnyConfigWithSharedConfig(serialized, sharedConfig);
// Convert serialized to intermediate config
let intermediate = await serializedToIntermediateConfig(withShared, ide);
// Apply config.ts to modify intermediate config
const configJsContents = await buildConfigTsandReadConfigJs(ide, ideType);
const configJsContents = await buildConfigTsandReadConfigJs(
ide,
ideInfo.ideType,
);
if (configJsContents) {
try {
// Try config.ts first
@ -867,6 +978,7 @@ async function loadContinueConfigFromJson(
intermediate,
ide,
ideSettings,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,

View file

@ -0,0 +1,79 @@
import ignore from "ignore";
import { IDE } from "..";
import {
DEFAULT_IGNORE_DIRS,
DEFAULT_IGNORE_FILETYPES,
} from "../indexing/ignore";
import { walkDir } from "../indexing/walkDir";
import { getGlobalAssistantsPath } from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import { joinPathsToUri } from "../util/uri";
export const ASSISTANTS_FOLDER = ".continue/assistants";
export function isLocalAssistantFile(uri: string): boolean {
if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) {
return false;
}
const normalizedUri = uri.replace(/\\/g, "/");
return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
}
export async function getAssistantFilesFromDir(
ide: IDE,
dir: string,
): Promise<{ path: string; content: string }[]> {
try {
const exists = await ide.fileExists(dir);
if (!exists) {
return [];
}
const overrideDefaultIgnores = ignore()
.add(DEFAULT_IGNORE_FILETYPES.filter((t) => t !== "config.yaml"))
.add(DEFAULT_IGNORE_DIRS);
const uris = await walkDir(dir, ide, {
overrideDefaultIgnores,
source: "get assistant files",
});
const assistantFilePaths = uris.filter(
(p) => p.endsWith(".yaml") || p.endsWith(".yml"),
);
const results = assistantFilePaths.map(async (uri) => {
const content = await ide.readFile(uri); // make a try catch
return { path: uri, content };
});
return Promise.all(results);
} catch (e) {
console.error(e);
return [];
}
}
export async function getAllAssistantFiles(
ide: IDE,
): Promise<{ path: string; content: string }[]> {
const workspaceDirs = await ide.getWorkspaceDirs();
let assistantFiles: { path: string; content: string }[] = [];
let dirsToCheck = [ASSISTANTS_FOLDER];
const fullDirs = workspaceDirs
.map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d)))
.flat();
fullDirs.push(localPathToUri(getGlobalAssistantsPath()));
assistantFiles = (
await Promise.all(fullDirs.map((dir) => getAssistantFilesFromDir(ide, dir)))
).flat();
return await Promise.all(
assistantFiles.map(async (file) => {
const content = await ide.readFile(file.path);
return { path: file.path, content };
}),
);
}

View file

@ -10,6 +10,7 @@ import {
} from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import { PRODUCTION_ENV } from "../../control-plane/env.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";
@ -40,6 +41,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
},
title: workspaceTitle,
errors: undefined,
uri: `${PRODUCTION_ENV.APP_URL}workspaces/${workspaceId}`,
};
setInterval(async () => {
@ -59,7 +61,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
)) as any);
const serializedConfig: SerializedContinueConfig = settings;
const results = await doLoadConfig(
return await doLoadConfig(
this.ide,
this.ideSettingsPromise,
this.controlPlaneClient,
@ -68,12 +70,8 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
undefined,
undefined,
this.workspaceId,
undefined,
);
return {
...results,
errors: [], // Don't do config validation here, it happens in admin panel
};
}
setIsActive(isActive: boolean): void {}

View file

@ -1,33 +1,57 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import { getPrimaryConfigFilePath } from "../../util/paths.js";
import { localPathToUri } from "../../util/pathToUri.js";
import { getUriPathBasename } from "../../util/uri.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";
export default class LocalProfileLoader implements IProfileLoader {
static ID = "local";
description: ProfileDescription = {
id: LocalProfileLoader.ID,
profileType: "local",
fullSlug: {
ownerSlug: "",
packageSlug: "",
versionSlug: "",
},
iconUrl: "",
title: "Local Config",
errors: undefined,
};
constructor(
private ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private controlPlaneClient: ControlPlaneClient,
private writeLog: (message: string) => Promise<void>,
) {}
private overrideAssistantFile?:
| { path: string; content: string }
| undefined,
) {
const description: ProfileDescription = {
id: overrideAssistantFile?.path ?? LocalProfileLoader.ID,
profileType: "local",
fullSlug: {
ownerSlug: "",
packageSlug: "",
versionSlug: "",
},
iconUrl: "",
title: overrideAssistantFile?.path
? getUriPathBasename(overrideAssistantFile.path)
: "Local Assistant",
errors: undefined,
uri:
overrideAssistantFile?.path ??
localPathToUri(getPrimaryConfigFilePath()),
};
this.description = description;
if (overrideAssistantFile?.content) {
try {
const parsedAssistant = parseConfigYaml(
overrideAssistantFile?.content ?? "",
);
this.description.title = parsedAssistant.name;
} catch (e) {
console.error("Failed to parse assistant file: ", e);
}
}
}
description: ProfileDescription;
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
const result = await doLoadConfig(
@ -38,6 +62,8 @@ export default class LocalProfileLoader implements IProfileLoader {
undefined,
undefined,
undefined,
this.description.id,
this.overrideAssistantFile?.path,
);
this.description.errors = result.errors;

View file

@ -1,9 +1,11 @@
import { ConfigResult, AssistantUnrolled } from "@continuedev/config-yaml";
import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";
@ -20,21 +22,35 @@ export interface PlatformConfigMetadata {
export default class PlatformProfileLoader implements IProfileLoader {
static RELOAD_INTERVAL = 1000 * 5; // 5 seconds
description: ProfileDescription;
constructor(
private constructor(
private configResult: ConfigResult<AssistantUnrolled>,
private readonly ownerSlug: string,
private readonly packageSlug: string,
private readonly iconUrl: string,
versionSlug: string,
private readonly versionSlug: string,
private readonly controlPlaneClient: ControlPlaneClient,
private readonly ide: IDE,
private ideSettingsPromise: Promise<IdeSettings>,
private writeLog: (message: string) => Promise<void>,
private readonly onReload: () => void,
) {
this.description = {
readonly description: ProfileDescription,
) {}
static async create(
configResult: ConfigResult<AssistantUnrolled>,
ownerSlug: string,
packageSlug: string,
iconUrl: string,
versionSlug: string,
controlPlaneClient: ControlPlaneClient,
ide: IDE,
ideSettingsPromise: Promise<IdeSettings>,
writeLog: (message: string) => Promise<void>,
onReload: () => void,
): Promise<PlatformProfileLoader> {
const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise);
const description: ProfileDescription = {
id: `${ownerSlug}/${packageSlug}`,
profileType: "platform",
fullSlug: {
@ -42,14 +58,29 @@ export default class PlatformProfileLoader implements IProfileLoader {
packageSlug,
versionSlug,
},
title: `${ownerSlug}/${packageSlug}@${versionSlug}`,
title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`,
errors: configResult.errors,
iconUrl: this.iconUrl,
iconUrl: iconUrl,
uri: `${controlPlaneEnv}${ownerSlug}/${packageSlug}`,
};
return new PlatformProfileLoader(
configResult,
ownerSlug,
packageSlug,
iconUrl,
versionSlug,
controlPlaneClient,
ide,
ideSettingsPromise,
writeLog,
onReload,
description,
);
}
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
if (this.configResult.errors?.length) {
if (this.configResult.errors?.find((e) => e.fatal)) {
return {
config: undefined,
errors: this.configResult.errors,
@ -68,11 +99,14 @@ export default class PlatformProfileLoader implements IProfileLoader {
ownerSlug: this.ownerSlug,
packageSlug: this.packageSlug,
},
this.description.id,
undefined,
);
return {
...results,
errors: [], // Don't do config validation here, it happens in admin panel
config: results.config,
errors: [...(this.configResult.errors ?? []), ...(results.errors ?? [])],
configLoadInterrupted: results.configLoadInterrupted,
};
}

View file

@ -4,6 +4,7 @@ import {
AssistantUnrolled,
ConfigResult,
ConfigValidationError,
ModelRole,
} from "@continuedev/config-yaml";
import {
ContinueConfig,
@ -18,10 +19,12 @@ import { getControlPlaneEnv } from "../../control-plane/env.js";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
import { localPathOrUriToPath } from "../../util/pathToUri";
import { Telemetry } from "../../util/posthog";
import { TTS } from "../../util/tts";
import { loadContinueConfigFromJson } from "../load";
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
import { PlatformConfigMetadata } from "./PlatformProfileLoader";
@ -33,7 +36,8 @@ export default async function doLoadConfig(
overrideConfigJson: SerializedContinueConfig | undefined,
overrideConfigYaml: AssistantUnrolled | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
workspaceId?: string,
profileId: string,
overrideConfigYamlByPath: string | undefined,
): Promise<ConfigResult<ContinueConfig>> {
const workspaceConfigs = await getWorkspaceConfigs(ide);
const ideInfo = await ide.getIdeInfo();
@ -48,7 +52,9 @@ export default async function doLoadConfig(
migrateJsonSharedConfig(configJsonPath, ide);
}
const configYamlPath = getConfigYamlPath(ideInfo.ideType);
const configYamlPath = localPathOrUriToPath(
overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType),
);
let newConfig: ContinueConfig | undefined;
let errors: ConfigValidationError[] | undefined;
@ -59,13 +65,14 @@ export default async function doLoadConfig(
ide,
workspaceConfigs.map((c) => JSON.stringify(c)),
ideSettings,
ideInfo.ideType,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,
overrideConfigYaml,
platformConfigMetadata,
controlPlaneClient,
configYamlPath,
);
newConfig = result.config;
errors = result.errors;
@ -75,7 +82,7 @@ export default async function doLoadConfig(
ide,
workspaceConfigs,
ideSettings,
ideInfo.ideType,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,
@ -86,6 +93,11 @@ export default async function doLoadConfig(
configLoadInterrupted = result.configLoadInterrupted;
}
// Rectify model selections for each role
if (newConfig) {
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
}
if (configLoadInterrupted || !newConfig) {
return { errors, config: newConfig, configLoadInterrupted: true };
}
@ -117,7 +129,7 @@ export default async function doLoadConfig(
controlPlaneProxyUrl += "/";
}
const controlPlaneProxyInfo = {
workspaceId,
profileId,
controlPlaneProxyUrl,
workOsAccessToken,
};
@ -147,21 +159,26 @@ async function injectControlPlaneProxyInfo(
config: ContinueConfig,
info: ControlPlaneProxyInfo,
): Promise<ContinueConfig> {
[...config.models, ...(config.tabAutocompleteModels ?? [])].forEach(
async (model) => {
Object.keys(config.modelsByRole).forEach((key) => {
config.modelsByRole[key as ModelRole].forEach((model) => {
if (model.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
},
);
});
});
if (config.embeddingsProvider?.providerName === "continue-proxy") {
(config.embeddingsProvider as ContinueProxy).controlPlaneProxyInfo = info;
}
Object.keys(config.selectedModelByRole).forEach((key) => {
const model = config.selectedModelByRole[key as ModelRole];
if (model?.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
});
if (config.reranker?.providerName === "continue-proxy") {
(config.reranker as ContinueProxy).controlPlaneProxyInfo = info;
}
config.models.forEach((model) => {
if (model.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
});
return config;
}

View file

@ -0,0 +1,67 @@
import { ModelRole } from "@continuedev/config-yaml";
import { ContinueConfig, ILLM } from "..";
import {
GlobalContext,
GlobalContextModelSelections,
} from "../util/GlobalContext";
export function rectifySelectedModelsFromGlobalContext(
continueConfig: ContinueConfig,
profileId: string,
): ContinueConfig {
const configCopy = { ...continueConfig };
const globalContext = new GlobalContext();
const currentSelectedModels = globalContext.get("selectedModelsByProfileId");
const currentForProfile: GlobalContextModelSelections =
currentSelectedModels?.[profileId] ?? {};
let fellBack = false;
// chat and summarize not implemented yet
// default chat model is stored in GUI still
const roles: ModelRole[] = [
"autocomplete",
"apply",
"edit",
"embed",
"rerank",
];
for (const role of roles) {
let newModel: ILLM | null = null;
const currentSelection = currentForProfile[role] ?? null;
if (currentSelection) {
const match = continueConfig.modelsByRole[role].find(
(m) => m.title === currentSelection,
);
if (match) {
newModel = match;
}
}
if (!newModel && continueConfig.modelsByRole[role].length > 0) {
newModel = continueConfig.modelsByRole[role][0];
}
if (!(currentSelection === (newModel?.title ?? null))) {
fellBack = true;
}
configCopy.selectedModelByRole[role] = newModel;
}
// In the case shared config wasn't respected,
// Rewrite the shared config
if (fellBack) {
globalContext.update("selectedModelsByProfileId", {
...currentSelectedModels,
[profileId]: Object.fromEntries(
Object.entries(configCopy.selectedModelByRole).map(([key, value]) => [
key,
value?.title ?? null,
]),
),
});
}
return configCopy;
}

View file

@ -1,13 +1,15 @@
import z from "zod";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
Config,
ContinueConfig,
SerializedContinueConfig,
} from "..";
export const sharedConfigSchema = z
.object({
// boolean fields in config.json
allowAnonymousTelemetry: z.boolean(),
disableIndexing: z.boolean(),
disableSessionTitles: z.boolean(),
@ -18,6 +20,7 @@ export const sharedConfigSchema = z
promptPath: z.string(),
// `ui` in `ContinueConfig`
showSessionTabs: z.boolean(),
codeBlockToolbarPosition: z.enum(["top", "bottom"]),
fontSize: z.number(),
codeWrap: z.boolean(),
@ -65,7 +68,19 @@ export function salvageSharedConfig(sharedConfig: object): SharedConfigSchema {
return salvagedConfig;
}
export function modifyContinueConfigWithSharedConfig<
// Apply shared config to all forms of config
// - SerializedContinueConfig (config.json)
// - Config ("intermediate") - passed to config.ts
// - ContinueConfig
// - BrowserSerializedContinueConfig (final converted to be passed to GUI)
// This modify function is split into two steps
// - rectifySharedModelsFromSharedConfig - includes boolean flags like allowAnonymousTelemetry which
// must be added BEFORE config.ts and remote server config apply for JSON
// for security reasons
// - setSharedModelsFromSharedConfig - exists because of selectedModelsByRole
// Which don't exist on SerializedContinueConfig/Config types, so must be added after the fact
export function modifyAnyConfigWithSharedConfig<
T extends
| ContinueConfig
| BrowserSerializedContinueConfig
@ -92,6 +107,7 @@ export function modifyContinueConfigWithSharedConfig<
configCopy.ui = {
...configCopy.ui,
};
if (sharedConfig.codeBlockToolbarPosition !== undefined) {
configCopy.ui.codeBlockToolbarPosition =
sharedConfig.codeBlockToolbarPosition;
@ -119,6 +135,10 @@ export function modifyContinueConfigWithSharedConfig<
configCopy.disableSessionTitles = sharedConfig.disableSessionTitles;
}
if (sharedConfig.showSessionTabs !== undefined) {
configCopy.ui.showSessionTabs = sharedConfig.showSessionTabs;
}
configCopy.experimental = {
...configCopy.experimental,
};
@ -135,28 +155,3 @@ export function modifyContinueConfigWithSharedConfig<
return configCopy;
}
// continueConfig.tabAutocompleteOptions = {
// ...continueConfig.tabAutocompleteOptions,
// useCache: sharedConfig.useAutocompleteCache,
// disableInFiles: sharedConfig.disableAutocompleteInFiles,
// multilineCompletions: sharedConfig.useAutocompleteMultilineCompletions,
// };
// continueConfig.ui = {
// ...continueConfig.ui,
// codeBlockToolbarPosition: sharedConfig.codeBlockToolbarPosition,
// fontSize: sharedConfig.fontSize,
// codeWrap: sharedConfig.codeWrap,
// displayRawMarkdown: sharedConfig.displayRawMarkdown,
// showChatScrollbar: sharedConfig.showChatScrollbar,
// };
// continueConfig.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry;
// continueConfig.disableIndexing = sharedConfig.disableIndexing;
// continueConfig.disableIndexing = sharedConfig.disableIndexing;
// continueConfig.disableSessionTitles = sharedConfig.disableSessionTitles;
// continueConfig.experimental = {
// ...continueConfig.experimental,
// useChromiumForDocsCrawling: sharedConfig.useChromiumForDocsCrawling,
// readResponseTTS: sharedConfig.readResponseTTS,
// promptPath: sharedConfig.promptPath,
// };

View file

@ -1,4 +1,4 @@
import { execSync } from "child_process";
import fs from "fs";
import os from "os";
import {
@ -121,11 +121,13 @@ export function getModelByRole<T extends keyof ExperimentalModelRoles>(
*
* See here for details: https://github.com/continuedev/continue/issues/940
*/
export function isSupportedLanceDbCpuTarget(ide: IDE) {
export function isSupportedLanceDbCpuTargetForLinux(ide?: IDE) {
const CPU_FEATURES_TO_CHECK = ["avx2", "fma"] as const;
const globalContext = new GlobalContext();
const globalContextVal = globalContext.get("isSupportedLanceDbCpuTarget");
const globalContextVal = globalContext.get(
"isSupportedLanceDbCpuTargetForLinux",
);
// If we've already checked the CPU target, return the cached value
if (globalContextVal !== undefined) {
@ -133,51 +135,35 @@ export function isSupportedLanceDbCpuTarget(ide: IDE) {
}
const arch = os.arch();
const platform = os.platform();
// This check only applies to x64
//https://github.com/lancedb/lance/issues/2195#issuecomment-2057841311
if (arch !== "x64") {
globalContext.update("isSupportedLanceDbCpuTarget", true);
globalContext.update("isSupportedLanceDbCpuTargetForLinux", true);
return true;
}
try {
const cpuFlags = (() => {
switch (platform) {
case "darwin":
return execSync("sysctl -n machdep.cpu.features")
.toString()
.toLowerCase();
case "linux":
return execSync("cat /proc/cpuinfo").toString().toLowerCase();
case "win32":
return execSync("wmic cpu get caption /format:list")
.toString()
.toLowerCase();
default:
return "";
}
})();
const cpuFlags = fs.readFileSync("/proc/cpuinfo", "utf-8").toLowerCase();
const isSupportedLanceDbCpuTarget = cpuFlags
const isSupportedLanceDbCpuTargetForLinux = cpuFlags
? CPU_FEATURES_TO_CHECK.every((feature) => cpuFlags.includes(feature))
: true;
// If it's not a supported CPU target, and it's the first time we are checking,
// show a toast to inform the user that we are going to disable indexing.
if (!isSupportedLanceDbCpuTarget) {
if (!isSupportedLanceDbCpuTargetForLinux && ide) {
// We offload our async toast to `showUnsupportedCpuToast` to prevent making
// our config loading async upstream of `isSupportedLanceDbCpuTarget`
// our config loading async upstream of `isSupportedLanceDbCpuTargetForLinux`
void showUnsupportedCpuToast(ide);
}
globalContext.update(
"isSupportedLanceDbCpuTarget",
isSupportedLanceDbCpuTarget,
"isSupportedLanceDbCpuTargetForLinux",
isSupportedLanceDbCpuTargetForLinux,
);
return isSupportedLanceDbCpuTarget;
return isSupportedLanceDbCpuTargetForLinux;
} catch (error) {
// If we can't determine CPU features, default to true
return true;
@ -187,11 +173,13 @@ export function isSupportedLanceDbCpuTarget(ide: IDE) {
async function showUnsupportedCpuToast(ide: IDE) {
const shouldOpenLink = await ide.showToast(
"warning",
"Codebase indexing is disabled due to CPU incompatibility",
"Codebase indexing disabled - Your Linux system lacks required CPU features (AVX2, FMA)",
"Learn more",
);
if (shouldOpenLink) {
void ide.openUrl("https://github.com/continuedev/continue/pull/3551");
void ide.openUrl(
"https://docs.continue.dev/troubleshooting#i-received-a-codebase-indexing-disabled---your-linux-system-lacks-required-cpu-features-avx2-fma-notification",
);
}
}

View file

@ -1,43 +0,0 @@
import {
clientRender,
PackageSlug,
PlatformClient,
SecretStore,
} from "@continuedev/config-yaml";
import { IDE } from "../..";
import { ControlPlaneClient } from "../../control-plane/client";
export async function clientRenderHelper(
packageSlug: PackageSlug,
unrolledAssistant: string,
ide: IDE,
controlPlaneClient: ControlPlaneClient,
) {
const ideSecretStore: SecretStore = {
get: async function (secretName: string): Promise<string | undefined> {
const results = await ide.readSecrets([secretName]);
return results[secretName];
},
set: async function (
secretName: string,
secretValue: string,
): Promise<void> {
return await ide.writeSecrets({
[secretName]: secretValue,
});
},
};
const platformClient: PlatformClient = {
resolveFQSNs: controlPlaneClient.resolveFQSNs.bind(controlPlaneClient),
};
const userId = await controlPlaneClient.userId;
return await clientRender(
packageSlug,
unrolledAssistant,
ideSecretStore,
userId ? platformClient : undefined,
);
}

View file

@ -1,4 +1,4 @@
import { ModelConfig, AssistantUnrolled } from "@continuedev/config-yaml";
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { SerializedContinueConfig } from "../..";
@ -6,7 +6,7 @@ export function convertConfigJsonToConfigYaml(
configJson: SerializedContinueConfig,
): AssistantUnrolled {
return {
name: "Local Config",
name: "Local Assistant",
version: "1.0.0",
models: [
...configJson.models.map(
@ -15,10 +15,11 @@ export function convertConfigJsonToConfigYaml(
name: model.title,
// defaultCompletionOptions: model.completionOptions,
provider: model.provider,
roles: ["chat"],
roles: ["chat", "edit", "apply", "summarize"],
}),
),
// ... tabAutocompleteModels
// TODO
// tabAutocompleteModels
// embeddingsModels
// rerankModels
],

View file

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

View file

@ -4,8 +4,12 @@ import {
AssistantUnrolled,
ConfigResult,
ConfigValidationError,
FQSN,
ModelRole,
parseAssistantUnrolled,
PlatformClient,
RegistryClient,
SecretResult,
unrollAssistantFromContent,
validateConfigYaml,
} from "@continuedev/config-yaml";
import { fetchwithRequestOptions } from "@continuedev/fetch";
@ -14,9 +18,8 @@ import {
ContinueConfig,
IContextProvider,
IDE,
IdeInfo,
IdeSettings,
IdeType,
SlashCommand,
} from "../..";
import { slashFromCustomCommand } from "../../commands";
import { AllRerankers } from "../../context/allRerankers";
@ -37,10 +40,18 @@ import { GlobalContext } from "../../util/GlobalContext";
import { getConfigYamlPath } from "../../util/paths";
import { getSystemPromptDotFile } from "../getSystemPromptDotFile";
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
import { modifyContinueConfigWithSharedConfig } from "../sharedConfig";
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { llmsFromModelConfig } from "./models";
export class LocalPlatformClient implements PlatformClient {
async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> {
return fqsns.map((fqsn) => {
return undefined;
});
}
}
async function loadConfigYaml(
workspaceConfigs: string[],
rawYaml: string,
@ -48,14 +59,25 @@ async function loadConfigYaml(
ide: IDE,
controlPlaneClient: ControlPlaneClient,
): Promise<ConfigResult<AssistantUnrolled>> {
const ideSettings = await ide.getIdeSettings();
let config =
overrideConfigYaml ??
// (ideSettings.continueTestEnvironment === "production"
// ? await clientRenderHelper(rawYaml, ide, controlPlaneClient)
// :
parseAssistantUnrolled(rawYaml);
// );
// This is how we allow use of blocks locally
(await unrollAssistantFromContent(
{
ownerSlug: "",
packageSlug: "",
versionSlug: "",
},
rawYaml,
new RegistryClient(),
{
currentUserSlug: "",
onPremProxyUrl: null,
orgScopeId: null,
platformClient: new LocalPlatformClient(),
renderSecrets: true,
},
));
const errors = validateConfigYaml(config);
if (errors?.some((error) => error.fatal)) {
@ -69,52 +91,28 @@ async function loadConfigYaml(
// Set defaults if undefined (this lets us keep config.json uncluttered for new users)
return {
config,
errors: errors.map((error) => ({
message: error.message,
fatal: error.fatal,
})),
errors,
configLoadInterrupted: false,
};
}
async function slashCommandsFromV1PromptFiles(
ide: IDE,
): Promise<SlashCommand[]> {
const slashCommands: SlashCommand[] = [];
const promptFiles = await getAllPromptFiles(ide, undefined, true);
for (const file of promptFiles) {
const slashCommand = slashCommandFromPromptFileV1(file.path, file.content);
if (slashCommand) {
slashCommands.push(slashCommand);
}
}
return slashCommands;
}
async function configYamlToContinueConfig(
config: AssistantUnrolled,
ide: IDE,
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
allowFreeTrial: boolean = true,
): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
const errors: ConfigValidationError[] = [];
const localErrors: ConfigValidationError[] = [];
const continueConfig: ContinueConfig = {
slashCommands: [
...(await slashCommandsFromV1PromptFiles(ide)),
...(config.prompts?.map(slashFromCustomCommand) ?? []),
],
slashCommands: [],
models: [],
tabAutocompleteModels: [],
tools: allTools,
systemMessage: config.rules?.join("\n"),
embeddingsProvider: new TransformersJsEmbeddingsProvider(),
experimental: {
modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({
transport: {
@ -132,14 +130,71 @@ async function configYamlToContinueConfig(
faviconUrl: doc.faviconUrl,
})),
contextProviders: [],
modelsByRole: {
chat: [],
edit: [],
apply: [],
embed: [],
autocomplete: [],
rerank: [],
summarize: [],
},
selectedModelByRole: {
chat: null, // not currently used - defaultModel on GUI is used
edit: null, // not currently used
apply: null,
embed: null,
autocomplete: null,
rerank: null,
summarize: null,
},
data: config.data,
};
// Prompt files -
try {
const promptFiles = await getAllPromptFiles(ide, undefined, true);
for (const file of promptFiles) {
try {
const slashCommand = slashCommandFromPromptFileV1(
file.path,
file.content,
);
if (slashCommand) {
continueConfig.slashCommands?.push(slashCommand);
}
} catch (e) {
localErrors.push({
fatal: false,
message: `Failed to convert prompt file ${file.path} to slash command: ${e instanceof Error ? e.message : e}`,
});
}
}
} catch (e) {
localErrors.push({
fatal: false,
message: `Error loading local prompt files: ${e instanceof Error ? e.message : e}`,
});
}
config.prompts?.forEach((prompt) => {
try {
const slashCommand = slashFromCustomCommand(prompt);
continueConfig.slashCommands?.push(slashCommand);
} catch (e) {
localErrors.push({
message: `Error loading prompt ${prompt.name}: ${e instanceof Error ? e.message : e}`,
fatal: false,
});
}
});
// Models
const modelsArrayRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
for (const model of config.models ?? []) {
model.roles = model.roles ?? ["chat"]; // Default to chat role if not specified
if (modelsArrayRoles.some((role) => model.roles?.includes(role))) {
// Main model array
model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified
try {
const llms = await llmsFromModelConfig(
model,
ide,
@ -149,51 +204,119 @@ async function configYamlToContinueConfig(
platformConfigMetadata,
continueConfig.systemMessage,
);
continueConfig.models.push(...llms);
}
if (model.roles?.includes("autocomplete")) {
// Autocomplete models array
const llms = await llmsFromModelConfig(
model,
ide,
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
continueConfig.systemMessage,
);
continueConfig.tabAutocompleteModels?.push(...llms);
}
//
if (modelsArrayRoles.some((role) => model.roles?.includes(role))) {
continueConfig.models.push(...llms);
}
if (
model.roles?.includes("apply") &&
!continueConfig.experimental?.modelRoles?.applyCodeBlock
) {
continueConfig.experimental ??= {};
continueConfig.experimental!.modelRoles ??= {};
continueConfig.experimental!.modelRoles!.applyCodeBlock = model.name;
}
if (model.roles?.includes("chat")) {
continueConfig.modelsByRole.chat.push(...llms);
}
if (
model.roles?.includes("edit") &&
!continueConfig.experimental?.modelRoles?.inlineEdit
) {
continueConfig.experimental ??= {};
continueConfig.experimental!.modelRoles ??= {};
continueConfig.experimental!.modelRoles!.inlineEdit = model.name;
if (model.roles?.includes("summarize")) {
continueConfig.modelsByRole.summarize.push(...llms);
}
if (model.roles?.includes("apply")) {
continueConfig.modelsByRole.apply.push(...llms);
}
if (model.roles?.includes("edit")) {
continueConfig.modelsByRole.edit.push(...llms);
}
if (model.roles?.includes("autocomplete")) {
continueConfig.modelsByRole.autocomplete.push(...llms);
}
if (model.roles?.includes("embed")) {
const { provider, ...options } = model;
const embeddingsProviderClass = allEmbeddingsProviders[provider];
if (embeddingsProviderClass) {
if (
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
) {
continueConfig.modelsByRole.embed.push(
new embeddingsProviderClass(),
);
} else {
continueConfig.modelsByRole.embed.push(
new embeddingsProviderClass(
options,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...options.requestOptions,
}),
),
);
}
} else {
localErrors.push({
fatal: false,
message: `Unsupported embeddings model provider found: ${provider}`,
});
}
}
if (model.roles?.includes("rerank")) {
const { provider, ...options } = model;
const rerankerClass = AllRerankers[provider];
if (rerankerClass) {
continueConfig.modelsByRole.rerank.push(
new rerankerClass(options, (url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...options.requestOptions,
}),
),
);
} else {
localErrors.push({
fatal: false,
message: `Unsupported reranking model provider found: ${provider}`,
});
}
}
} catch (e) {
localErrors.push({
fatal: false,
message: `Failed to load model:\nName: ${model.name}\nModel: ${model.model}\nProvider: ${model.provider}\n${e instanceof Error ? e.message : e}`,
});
}
}
// Add transformers js to the embed models in vs code if not already added
if (
ideInfo.ideType === "vscode" &&
!continueConfig.modelsByRole.embed.find(
(m) => m.providerName === "transformers.js",
)
) {
continueConfig.modelsByRole.embed.push(
new TransformersJsEmbeddingsProvider(),
);
}
if (allowFreeTrial) {
// Obtain auth token (iff free trial being used)
const freeTrialModels = continueConfig.models.filter(
(model) => model.providerName === "free-trial",
);
if (freeTrialModels.length > 0) {
const ghAuthToken = await ide.getGitHubAuthToken({});
for (const model of freeTrialModels) {
(model as FreeTrial).setupGhAuthToken(ghAuthToken);
try {
const ghAuthToken = await ide.getGitHubAuthToken({});
for (const model of freeTrialModels) {
(model as FreeTrial).setupGhAuthToken(ghAuthToken);
}
} catch (e) {
localErrors.push({
fatal: false,
message: `Failed to obtain GitHub auth token for free trial:\n${e instanceof Error ? e.message : e}`,
});
// Remove free trial models
continueConfig.models = continueConfig.models.filter(
(model) => model.providerName !== "free-trial",
);
}
}
} else {
@ -203,8 +326,6 @@ async function configYamlToContinueConfig(
);
}
// TODO: Split into model roles.
// Context providers
const codebaseContextParams: IContextProvider[] =
(config.context || []).find((cp) => cp.provider === "codebase")?.params ||
@ -224,7 +345,10 @@ async function configYamlToContinueConfig(
const cls = contextProviderClassFromName(context.provider) as any;
if (!cls) {
if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.provider)) {
console.warn(`Unknown context provider ${context.provider}`);
localErrors.push({
fatal: false,
message: `Unknown context provider ${context.provider}`,
});
}
return undefined;
}
@ -243,74 +367,29 @@ async function configYamlToContinueConfig(
continueConfig.contextProviders.push(new DocsContextProvider({}));
}
// Embeddings Provider
// IMPORTANT this currently will grab the first model found with an embed role
const embedConfig = config.models?.find((model) =>
model.roles?.includes("embed"),
);
if (embedConfig) {
const { provider, ...options } = embedConfig;
const embeddingsProviderClass = allEmbeddingsProviders[provider];
if (embeddingsProviderClass) {
if (
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
) {
continueConfig.embeddingsProvider = new embeddingsProviderClass();
} else {
continueConfig.embeddingsProvider = new embeddingsProviderClass(
options,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...options.requestOptions,
}),
);
}
}
}
// Reranker
// IMPORTANT this currently will grab the first model found with a rerank role
const rerankConfig = config.models?.find((model) =>
model.roles?.includes("rerank"),
);
if (rerankConfig) {
const { provider, ...options } = rerankConfig;
const rerankerClass = AllRerankers[provider];
if (rerankerClass) {
continueConfig.reranker = new rerankerClass(
options,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...options.requestOptions,
}),
);
}
}
// Apply MCP if specified
const mcpManager = MCPManagerSingleton.getInstance();
await Promise.all(
await Promise.allSettled(
config.mcpServers?.map(async (server) => {
const mcpId = server.name;
const mcpConnection = mcpManager.createConnection(mcpId, {
transport: {
type: "stdio",
args: [],
...server,
},
});
if (!mcpConnection) {
return;
}
const abortController = new AbortController();
const mcpConnectionTimeout = setTimeout(
() => abortController.abort(),
5000,
4000,
);
try {
const mcpId = server.name;
const mcpConnection = mcpManager.createConnection(mcpId, {
transport: {
type: "stdio",
args: [],
...server,
},
});
if (!mcpConnection) {
return;
}
const mcpError = await mcpConnection.modifyConfig(
continueConfig,
mcpId,
@ -319,39 +398,49 @@ async function configYamlToContinueConfig(
server.faviconUrl,
);
if (mcpError) {
errors.push(mcpError);
localErrors.push(mcpError);
}
} catch (e: any) {
errors.push({
} catch (e) {
let errorMessage = `Failed to load MCP server ${server.name}`;
if (e instanceof Error) {
if (e.name === "AbortError") {
errorMessage += ": connection timed out";
} else {
errorMessage += ": " + e.message;
}
}
localErrors.push({
fatal: false,
message: `Failed to load MCP server: ${e.message}`,
message: errorMessage,
});
if (e.name !== "AbortError") {
throw e;
}
} finally {
clearTimeout(mcpConnectionTimeout);
}
clearTimeout(mcpConnectionTimeout);
}) ?? [],
);
return { config: continueConfig, errors };
return { config: continueConfig, errors: localErrors };
}
export async function loadContinueConfigFromYaml(
ide: IDE,
workspaceConfigs: string[],
ideSettings: IdeSettings,
ideType: IdeType,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
overrideConfigYaml: AssistantUnrolled | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
controlPlaneClient: ControlPlaneClient,
configYamlPath: string | undefined,
): Promise<ConfigResult<ContinueConfig>> {
const rawYaml =
overrideConfigYaml === undefined
? fs.readFileSync(getConfigYamlPath(ideType), "utf-8")
? fs.readFileSync(
configYamlPath ?? getConfigYamlPath(ideInfo.ideType),
"utf-8",
)
: "";
const configYamlResult = await loadConfigYaml(
@ -370,36 +459,49 @@ export async function loadContinueConfigFromYaml(
};
}
const { config: continueConfig, errors } = await configYamlToContinueConfig(
configYamlResult.config,
ide,
ideSettings,
uniqueId,
writeLog,
workOsAccessToken,
platformConfigMetadata,
);
const { config: continueConfig, errors: localErrors } =
await configYamlToContinueConfig(
configYamlResult.config,
ide,
ideSettings,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,
platformConfigMetadata,
);
const systemPromptDotFile = await getSystemPromptDotFile(ide);
if (systemPromptDotFile) {
if (continueConfig.systemMessage) {
continueConfig.systemMessage += "\n\n" + systemPromptDotFile;
} else {
continueConfig.systemMessage = systemPromptDotFile;
try {
const systemPromptDotFile = await getSystemPromptDotFile(ide);
if (systemPromptDotFile) {
if (continueConfig.systemMessage) {
continueConfig.systemMessage += "\n\n" + systemPromptDotFile;
} else {
continueConfig.systemMessage = systemPromptDotFile;
}
}
} catch (e) {
localErrors.push({
fatal: false,
message: `Failed to load system prompt dot file: ${e instanceof Error ? e.message : e}`,
});
}
// Apply shared config
// TODO: override several of these values with user/org shared config
// Don't try catch this - has security implications and failure should be fatal
const sharedConfig = new GlobalContext().getSharedConfig();
const withShared = modifyContinueConfigWithSharedConfig(
const withShared = modifyAnyConfigWithSharedConfig(
continueConfig,
sharedConfig,
);
if (withShared.allowAnonymousTelemetry === undefined) {
withShared.allowAnonymousTelemetry = true;
}
return {
config: withShared,
errors: [...(configYamlResult.errors ?? []), ...errors],
errors: [...(configYamlResult.errors ?? []), ...localErrors],
configLoadInterrupted: false,
};
}

View file

@ -35,8 +35,11 @@ async function modelConfigToBaseLLM(
return undefined;
}
const { capabilities, ...rest } = model;
let options: LLMOptions = {
...model,
...rest,
// contextLength: model.defaultCompletionOptions?.contextLength ?? undefined,
completionOptions: {
...(model.defaultCompletionOptions ?? {}),
model: model.model,
@ -49,8 +52,77 @@ async function modelConfigToBaseLLM(
title: model.name,
systemMessage,
promptTemplates: model.promptTemplates,
capabilities: {
tools: model.capabilities?.includes("tool_use"),
uploadImage: model.capabilities?.includes("image_input"),
},
};
// Model capabilities - need to be undefined if not found
// To fallback to our autodetection
if (capabilities?.find((c) => c === "tool_use")) {
options.capabilities = {
...options.capabilities,
tools: true,
};
}
if (capabilities?.find((c) => c === "image_input")) {
options.capabilities = {
...options.capabilities,
uploadImage: true,
};
}
if (model.embedOptions?.maxBatchSize) {
options.maxEmbeddingBatchSize = model.embedOptions.maxBatchSize;
}
if (model.embedOptions?.maxChunkSize) {
options.maxEmbeddingChunkSize = model.embedOptions.maxChunkSize;
}
// These are params that are at model config level in JSON
// But we decided to move to nested `env` in YAML
// Since types vary and we don't want to blindly spread env for now,
// Each one is handled individually here
const env = model.env ?? {};
if (
"useLegacyCompletionsEndpoint" in env &&
typeof env.useLegacyCompletionsEndpoint === "boolean"
) {
options.useLegacyCompletionsEndpoint = env.useLegacyCompletionsEndpoint;
}
if ("apiType" in env && typeof env.apiType === "string") {
options.apiType = env.apiType;
}
if ("apiVersion" in env && typeof env.apiVersion === "string") {
options.apiVersion = env.apiVersion;
}
if ("deployment" in env && typeof env.deployment === "string") {
options.deployment = env.deployment;
}
if ("deploymentId" in env && typeof env.deploymentId === "string") {
options.deploymentId = env.deploymentId;
}
if ("projectId" in env && typeof env.projectId === "string") {
options.projectId = env.projectId;
}
if ("region" in env && typeof env.region === "string") {
options.region = env.region;
}
if ("profile" in env && typeof env.profile === "string") {
options.profile = env.profile;
}
if ("modelArn" in env && typeof env.modelArn === "string") {
options.modelArn = env.modelArn;
}
if ("aiGatewaySlug" in env && typeof env.aiGatewaySlug === "string") {
options.aiGatewaySlug = env.aiGatewaySlug;
}
if ("accountId" in env && typeof env.accountId === "string") {
options.accountId = env.accountId;
}
const llm = new cls(options);
return llm;
}
@ -78,7 +150,7 @@ async function autodetectModels(
{
...model,
model: modelName,
name: `${llm.title} - ${modelName}`,
name: modelName,
},
uniqueId,
ideSettings,

View file

@ -5,6 +5,7 @@ import {
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
IDE,
LoadSubmenuItemsArgs,
} from "../..";
import DocsService from "../../indexing/docs/DocsService";
@ -23,7 +24,7 @@ class DocsContextProvider extends BaseContextProvider {
// Todo: consider a different renderInline so that when multiple docs are referenced in one message,
// Or the doc has an odd name unrelated to the content
// The name of the doc itself doesn't skew the embedding results
// renderInlineAs: "<docs-context-provider>",
renderInlineAs: "",
};
constructor(options: any) {
@ -36,6 +37,7 @@ class DocsContextProvider extends BaseContextProvider {
chunks: Chunk[],
reranker: NonNullable<ContextProviderExtras["reranker"]>,
fullInput: ContextProviderExtras["fullInput"],
ide: IDE,
) {
let chunksCopy = [...chunks];
@ -51,7 +53,7 @@ class DocsContextProvider extends BaseContextProvider {
this.options?.nFinal ?? DocsContextProvider.nFinal,
);
} catch (e) {
console.warn(`Failed to rerank docs results: ${e}`);
void ide.showToast("warning", `Failed to rerank retrieval results\n${e}`);
chunksCopy = chunksCopy.splice(
0,
@ -116,6 +118,7 @@ class DocsContextProvider extends BaseContextProvider {
chunks,
extras.reranker,
extras.fullInput,
extras.ide,
);
}

View file

@ -8,9 +8,9 @@ import {
} from "../../";
import { walkDirs } from "../../indexing/walkDir";
import {
getUriPathBasename,
getShortestUniqueRelativeUriPaths,
getUriDescription,
getUriPathBasename,
} from "../../util/uri";
const MAX_SUBMENU_ITEMS = 10_000;
@ -53,7 +53,13 @@ class FileContextProvider extends BaseContextProvider {
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const workspaceDirs = await args.ide.getWorkspaceDirs();
const results = await walkDirs(args.ide, undefined, workspaceDirs);
const results = await walkDirs(
args.ide,
{
source: "load submenu items - file",
},
workspaceDirs,
);
const files = results.flat().slice(-MAX_SUBMENU_ITEMS);
const withUniquePaths = getShortestUniqueRelativeUriPaths(
files,

View file

@ -50,7 +50,9 @@ class FileTreeContextProvider extends BaseContextProvider {
directories: [],
};
const uris = await walkDir(workspaceDir, extras.ide);
const uris = await walkDir(workspaceDir, extras.ide, {
source: "get context items - file tree",
});
const relativePaths = uris.map(
(uri) => findUriInDirs(uri, [workspaceDir]).relativePathOrBasename,
);

View file

@ -36,6 +36,7 @@ class FolderContextProvider extends BaseContextProvider {
args.ide,
{
onlyDirs: true,
source: "load submenu items - folder",
},
workspaceDirs,
);

View file

@ -94,7 +94,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
});
}
private async getRemoteBranchName(
private async getRemoteBranchInfo(
extras: ContextProviderExtras,
): Promise<RemoteBranchInfo> {
const subprocess = await getSubprocess(extras);
@ -121,9 +121,16 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
const remoteUrl = await subprocess(`git remote get-url ${branchRemote}`);
const urlMatches = /:(?<project>.*).git/.exec(remoteUrl);
let urlMatches: RegExpExecArray | null;
if (/https?.*/.test(remoteUrl)) {
const pathname = new URL(remoteUrl).pathname;
urlMatches = /\/(?<projectPath>.*?)(?:(?=\.git)|$)/.exec(pathname)
} else {
// ssh
urlMatches = /:(?<projectPath>.*).git/.exec(remoteUrl)
}
const project = urlMatches?.groups?.project ?? null;
const project = urlMatches?.groups?.projectPath ?? null;
return {
branch: remoteBranch,
@ -135,7 +142,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const { branch, project } = await this.getRemoteBranchName(extras);
const { branch, project } = await this.getRemoteBranchInfo(extras);
const api = await this.getApi();

View file

@ -36,6 +36,7 @@ class HttpContextProvider extends BaseContextProvider {
method: "POST",
headers: {
"Content-Type": "application/json",
...(this.options.headers || {}),
},
body: JSON.stringify({
query: query || "",

View file

@ -9,6 +9,7 @@ interface JiraClientOptions {
password: string;
issueQuery?: string;
apiVersion?: string;
maxResults?: string;
requestOptions?: RequestOptions;
}
@ -73,6 +74,7 @@ export class JiraClient {
"assignee = currentUser() AND resolution = Unresolved order by updated DESC",
apiVersion: "3",
requestOptions: {},
maxResults: "50",
...options,
};
this.baseUrl = `https://${this.options.domain}/rest/api/${this.options.apiVersion}`;
@ -146,7 +148,7 @@ export class JiraClient {
`/search?fields=summary&jql=${
this.options.issueQuery ??
"assignee = currentUser() AND resolution = Unresolved order by updated DESC"
}`,
}&maxResults=${this.options.maxResults ?? "50"}`,
),
{
method: "GET",

View file

@ -25,6 +25,7 @@ class JiraIssuesContextProvider extends BaseContextProvider {
issueQuery: this.options.issueQuery,
apiVersion: this.options.apiVersion,
requestOptions: this.options.requestOptions,
maxResults: this.options.maxResults
});
}
@ -32,8 +33,6 @@ class JiraIssuesContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const issueId = query;
const api = this.getApi();
const issue = await api.issue(query, extras.fetch);

View file

@ -55,6 +55,7 @@ class RepoMapContextProvider extends BaseContextProvider {
args.ide,
{
onlyDirs: true,
source: "load submenu items - repo map",
},
workspaceDirs,
);

View file

@ -7,7 +7,6 @@ import {
IContextProvider,
} from "../..";
import { ConfigHandler } from "../../config/ConfigHandler";
import { ControlPlaneClient } from "../../control-plane/client";
import { TEST_DIR } from "../../test/testDir";
import FileSystemIde from "../../util/filesystem";
@ -31,8 +30,9 @@ async function getContextProviderExtras(
ide,
ideSettingsPromise,
async (text) => {},
new ControlPlaneClient(Promise.resolve(undefined), ideSettingsPromise),
Promise.resolve(undefined),
);
await configHandler.initializedPromise;
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Config not found");
@ -42,10 +42,10 @@ async function getContextProviderExtras(
fullInput,
ide,
config,
embeddingsProvider: config.embeddingsProvider,
embeddingsProvider: config.selectedModelByRole.embed,
fetch: fetch,
llm: config.models[0],
reranker: config.reranker,
reranker: config.selectedModelByRole.rerank,
selectedCode: [],
};
}

View file

@ -7,6 +7,8 @@ import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCod
import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache";
const DEFAULT_CHUNK_SIZE = 384;
export interface RetrievalPipelineOptions {
llm: ILLM;
config: ContinueConfig;
@ -16,13 +18,13 @@ export interface RetrievalPipelineOptions {
nFinal: number;
tags: BranchAndDir[];
filterDirectory?: string;
includeEmbeddings?: boolean; // Used to handle JB w/o an embeddings model
}
export interface RetrievalPipelineRunArguments {
query: string;
tags: BranchAndDir[];
filterDirectory?: string;
includeEmbeddings: boolean;
}
export interface IRetrievalPipeline {
@ -31,12 +33,21 @@ export interface IRetrievalPipeline {
export default class BaseRetrievalPipeline implements IRetrievalPipeline {
private ftsIndex = new FullTextSearchCodebaseIndex();
private lanceDbIndex: LanceDbIndex;
private lanceDbIndex: LanceDbIndex | null = null;
constructor(protected readonly options: RetrievalPipelineOptions) {
this.lanceDbIndex = new LanceDbIndex(
options.config.embeddingsProvider,
(uri) => options.ide.readFile(uri),
void this.initLanceDb();
}
private async initLanceDb() {
const embedModel = this.options.config.selectedModelByRole.embed;
if (!embedModel) {
return;
}
this.lanceDbIndex = await LanceDbIndex.create(embedModel, (uri) =>
this.options.ide.readFile(uri),
);
}
@ -60,27 +71,28 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
return trigrams;
}
private escapeFtsQueryString(query: string): string {
const escapedDoubleQuotes = query.replace(/"/g, '""');
return `"${escapedDoubleQuotes}"`;
}
protected async retrieveFts(
args: RetrievalPipelineRunArguments,
n: number,
): Promise<Chunk[]> {
try {
if (args.query.trim() === "") {
return [];
}
const tokens = this.getCleanedTrigrams(args.query).join(" OR ");
return await this.ftsIndex.retrieve({
n,
text: tokens,
tags: args.tags,
directory: args.filterDirectory,
});
} catch (e) {
console.warn("Error retrieving from FTS:", e);
if (args.query.trim() === "") {
return [];
}
const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR ");
const tokens = this.escapeFtsQueryString(tokensRaw);
return await this.ftsIndex.retrieve({
n,
text: tokens,
tags: args.tags,
directory: args.filterDirectory,
});
}
protected async retrieveAndChunkRecentlyEditedFiles(
@ -109,7 +121,8 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
filepath,
contents,
maxChunkSize:
this.options.config.embeddingsProvider.maxEmbeddingChunkSize,
this.options.config.selectedModelByRole.embed
?.maxEmbeddingChunkSize ?? DEFAULT_CHUNK_SIZE,
digest: filepath,
});
@ -125,6 +138,13 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
input: string,
n: number,
): Promise<Chunk[]> {
if (!this.lanceDbIndex) {
console.warn(
"LanceDB index not available, skipping embeddings retrieval",
);
return [];
}
return this.lanceDbIndex.retrieve(
input,
n,

View file

@ -9,7 +9,7 @@ import BaseRetrievalPipeline, {
export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
async run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
const { input, nFinal, filterDirectory, includeEmbeddings } = this.options;
const { input, nFinal, filterDirectory, config } = this.options;
// We give 1/4 weight to recently edited files, 1/4 to full text search,
// and the remaining 1/2 to embeddings
@ -19,22 +19,42 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
let retrievalResults: Chunk[] = [];
const ftsChunks = await this.retrieveFts(args, ftsNFinal);
let ftsChunks: Chunk[] = [];
try {
ftsChunks = await this.retrieveFts(args, ftsNFinal);
} catch (error) {
console.error("Error retrieving FTS chunks:", error);
}
const embeddingsChunks = includeEmbeddings
? await this.retrieveEmbeddings(input, embeddingsNFinal)
: [];
let embeddingsChunks: Chunk[] = [];
try {
embeddingsChunks = !!config.selectedModelByRole.embed
? await this.retrieveEmbeddings(input, embeddingsNFinal)
: [];
} catch (error) {
console.error("Error retrieving embeddings:", error);
}
const recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal);
let recentlyEditedFilesChunks: Chunk[] = [];
try {
recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal);
} catch (error) {
console.error("Error retrieving recently edited files:", error);
}
const repoMapChunks = await requestFilesFromRepoMap(
this.options.llm,
this.options.config,
this.options.ide,
input,
filterDirectory,
);
let repoMapChunks: Chunk[] = [];
try {
repoMapChunks = await requestFilesFromRepoMap(
this.options.llm,
this.options.config,
this.options.ide,
input,
filterDirectory,
);
} catch (error) {
console.error("Error retrieving repo map chunks:", error);
}
retrievalResults.push(
...recentlyEditedFilesChunks,

View file

@ -12,25 +12,46 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
private async _retrieveInitial(
args: RetrievalPipelineRunArguments,
): Promise<Chunk[]> {
const { input, nRetrieve, filterDirectory, includeEmbeddings } =
this.options;
const { input, nRetrieve, filterDirectory, config } = this.options;
let retrievalResults: Chunk[] = [];
const ftsChunks = await this.retrieveFts(args, nRetrieve);
const embeddingsChunks = includeEmbeddings
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
const recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve);
let ftsChunks: Chunk[] = [];
try {
ftsChunks = await this.retrieveFts(args, nRetrieve);
} catch (error) {
console.error("Error retrieving FTS chunks:", error);
}
const repoMapChunks = await requestFilesFromRepoMap(
this.options.llm,
this.options.config,
this.options.ide,
input,
filterDirectory,
);
let embeddingsChunks: Chunk[] = [];
try {
embeddingsChunks = !!config.selectedModelByRole.embed
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
} catch (error) {
console.error("Error retrieving embeddings chunks:", error);
}
let recentlyEditedFilesChunks: Chunk[] = [];
try {
recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve);
} catch (error) {
console.error("Error retrieving recently edited files chunks:", error);
}
let repoMapChunks: Chunk[] = [];
try {
repoMapChunks = await requestFilesFromRepoMap(
this.options.llm,
this.options.config,
this.options.ide,
input,
filterDirectory,
);
} catch (error) {
console.error("Error retrieving repo map chunks:", error);
}
retrievalResults.push(
...recentlyEditedFilesChunks,
@ -42,7 +63,8 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
if (filterDirectory) {
// Backup if the individual retrieval methods don't listen
retrievalResults = retrievalResults.filter(
(chunk) => !!findUriInDirs(chunk.filepath, [filterDirectory]),
(chunk) =>
!!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir,
);
}
@ -53,35 +75,44 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
}
private async _rerank(input: string, chunks: Chunk[]): Promise<Chunk[]> {
if (!this.options.config.reranker) {
throw new Error("No reranker provided");
if (!this.options.config.selectedModelByRole.rerank) {
throw new Error("No reranker set up");
}
// remove empty chunks -- some APIs fail on that
chunks = chunks.filter((chunk) => chunk.content);
let scores: number[] = await this.options.config.reranker.rerank(
input,
chunks,
);
try {
let scores: number[] =
await this.options.config.selectedModelByRole.rerank.rerank(
input,
chunks,
);
// Filter out low-scoring results
let results = chunks;
// let results = chunks.filter(
// (_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold,
// );
// scores = scores.filter(
// (score) => score >= RETRIEVAL_PARAMS.rerankThreshold,
// );
// Filter out low-scoring results
let results = chunks;
// let results = chunks.filter(
// (_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold,
// );
// scores = scores.filter(
// (score) => score >= RETRIEVAL_PARAMS.rerankThreshold,
// );
const chunkIndexMap = new Map<Chunk, number>();
chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx));
const chunkIndexMap = new Map<Chunk, number>();
chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx));
results.sort(
(a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!],
);
results = results.slice(-this.options.nFinal);
return results;
results.sort(
(a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!],
);
results = results.slice(-this.options.nFinal);
return results;
} catch (e) {
void this.options.ide.showToast(
"warning",
`Failed to rerank retrieval results\n${e}`,
);
return chunks.slice(-this.options.nFinal);
}
}
private async _expandWithEmbeddings(chunks: Chunk[]): Promise<Chunk[]> {

View file

@ -1,8 +1,8 @@
import { Chunk, ContinueConfig, IDE, ILLM } from "../..";
import { getModelByRole } from "../../config/util";
import generateRepoMap from "../../util/generateRepoMap";
import { resolveRelativePathInDir } from "../../util/ideUtils";
import { renderChatMessage } from "../../util/messageContent";
import { getUriPathBasename } from "../../util/uri";
const SUPPORTED_MODEL_TITLE_FAMILIES = [
"claude-3",
@ -16,7 +16,7 @@ function isSupportedModel(
config: ContinueConfig,
modelTitle?: string,
): boolean {
if (config.experimental?.modelRoles?.applyCodeBlock) {
if (config.experimental?.modelRoles?.repoMapFileSelection) {
return true;
}
@ -49,14 +49,14 @@ export async function requestFilesFromRepoMap(
const repoMap = await generateRepoMap(llm, ide, {
dirUris: filterDirUri ? [filterDirUri] : undefined,
includeSignatures: false,
outputRelativeUriPaths: false,
outputRelativeUriPaths: true,
});
const prompt = `${repoMap}
Given the above repo map, your task is to decide which files are most likely to be relevant in answering a question. Before giving your answer, you should write your reasoning about which files/folders are most important. This thinking should start with a <reasoning> tag, followed by a paragraph explaining your reasoning, and then a closing </reasoning> tag on the last line.
After this, your response should begin with a <results> tag, followed by a list of each file, one per line, and then a closing </results> tag on the last line. You should select between 5 and 10 files. The names that you list should be the full path from the root of the repo, not just the basename of the file.
After this, your response should begin with a <results> tag, followed by a list of each file, one per line, and then a closing </results> tag on the last line. You should select between 5 and 10 files. The names that you list should be the exact relative path that you saw in the repo map, not just the basename of the file.
This is the question that you should select relevant files for: "${input}"`;
@ -73,16 +73,20 @@ This is the question that you should select relevant files for: "${input}"`;
return [];
}
const fileUris = content
const filepaths = content
.split("<results>")[1]
?.split("</results>")[0]
?.split("\n")
.filter(Boolean)
.map((uri) => uri.trim());
.map((filepath) => filepath.trim());
const chunks = await Promise.all(
fileUris.map(async (uri) => {
const content = await ide.readFile(uri);
filepaths.map(async (filepath) => {
const uri = await resolveRelativePathInDir(filepath, ide);
if (!uri) {
return undefined;
}
const content = await ide.readFile(filepath);
const lineCount = content.split("\n").length;
const chunk: Chunk = {
digest: uri,
@ -96,7 +100,7 @@ This is the question that you should select relevant files for: "${input}"`;
}),
);
return chunks;
return chunks.filter((c) => c !== undefined) as Chunk[];
} catch (e) {
console.debug("Error requesting files from repo map", e);
return [];

View file

@ -1,5 +1,4 @@
import { BranchAndDir, ContextItem, ContextProviderExtras } from "../../";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import { getUriDescription } from "../../util/uri";
import { INSTRUCTIONS_BASE_ITEM } from "../providers/utils";
@ -14,26 +13,16 @@ export async function retrieveContextItemsFromEmbeddings(
options: any | undefined,
filterDirectory: string | undefined,
): Promise<ContextItem[]> {
if (!extras.embeddingsProvider) {
return [];
}
// transformers.js not supported in JetBrains IDEs right now
const isJetBrainsAndTransformersJs =
extras.embeddingsProvider.providerName ===
TransformersJsEmbeddingsProvider.providerName &&
(await extras.ide.getIdeInfo()).ideType === "jetbrains";
if (isJetBrainsAndTransformersJs) {
void extras.ide.showToast(
"warning",
"Codebase retrieval is limited when `embeddingsProvider` is empty or set to `transformers.js` in JetBrains. " +
"You can use Ollama to set up local embeddings, use our 'free-trial', " +
"or configure your own. See here to learn more: " +
"https://docs.continue.dev/customize/model-types/embeddings",
);
}
// Currently you can use codebase without an embeddings provider and it will just skip the embeddings inputs
// if (!extras.embeddingsProvider) {
// void extras.ide.showToast(
// "warning",
// "Set up an embeddings model to use this feature. Visit the docs to learn more: " +
// "https://docs.continue.dev/customize/model-roles/embeddings",
// );
// return [];
// }
const includeEmbeddings = !!extras.config.selectedModelByRole.embed;
// Get tags to retrieve for
const workspaceDirs = await extras.ide.getWorkspaceDirs();
@ -78,7 +67,6 @@ export async function retrieveContextItemsFromEmbeddings(
input: extras.fullInput,
llm: extras.llm,
config: extras.config,
includeEmbeddings: !isJetBrainsAndTransformersJs,
};
const pipeline = new pipelineType(pipelineOptions);
@ -86,16 +74,17 @@ export async function retrieveContextItemsFromEmbeddings(
tags,
filterDirectory,
query: extras.fullInput,
includeEmbeddings,
});
if (results.length === 0) {
if (extras.config.disableIndexing) {
void extras.ide.showToast("warning", "No embeddings results found.");
void extras.ide.showToast("warning", "No results found.");
return [];
} else {
void extras.ide.showToast(
"warning",
"No embeddings results found. If you think this is an error, re-index your codebase.",
"No results found. If you think this is an error, re-index your codebase.",
);
// TODO - add "re-index" option to warning message which clears and reindexes codebase
}

View file

@ -40,7 +40,10 @@ export class ControlPlaneClient {
private readonly ideSettingsPromise: Promise<IdeSettings>,
) {}
async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> {
async resolveFQSNs(
fqsns: FQSN[],
orgScopeId: string | null,
): Promise<(SecretResult | undefined)[]> {
const userId = await this.userId;
if (!userId) {
throw new Error("No user id");
@ -48,7 +51,7 @@ export class ControlPlaneClient {
const resp = await this.request("ide/sync-secrets", {
method: "POST",
body: JSON.stringify({ fqsns }),
body: JSON.stringify({ fqsns, orgScopeId }),
});
return (await resp.json()) as any;
}
@ -183,21 +186,4 @@ export class ControlPlaneClient {
});
return ((await resp.json()) as any).settings;
}
async syncSecrets(secretNames: string[]): Promise<Record<string, string>> {
const userId = await this.userId;
if (!userId) {
throw new Error("No user id");
}
try {
const resp = await this.request("ide/sync-secrets", {
method: "POST",
body: JSON.stringify({ secretNames }),
});
return (await resp.json()) as any;
} catch (e) {
return {};
}
}
}

View file

@ -1,7 +1,9 @@
import fetch from "node-fetch";
import * as fs from "node:fs";
import { IdeSettings } from "..";
import { getStagingEnvironmentDotFilePath } from "../util/paths";
import {
getLocalEnvironmentDotFilePath,
getStagingEnvironmentDotFilePath,
} from "../util/paths";
export interface ControlPlaneEnv {
DEFAULT_CONTROL_PLANE_PROXY_URL: string;
@ -19,7 +21,7 @@ const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ";
const WORKOS_ENV_ID_PRODUCTION = "continue";
const WORKOS_ENV_ID_STAGING = "continue-staging";
const PRODUCTION_ENV: ControlPlaneEnv = {
export const PRODUCTION_ENV: ControlPlaneEnv = {
DEFAULT_CONTROL_PLANE_PROXY_URL:
"https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/",
CONTROL_PLANE_URL:
@ -62,30 +64,36 @@ const LOCAL_ENV: ControlPlaneEnv = {
};
export async function enableHubContinueDev() {
try {
const resp = await fetch("https://api.continue.dev/features/hub");
const data = (await resp.json()) as any;
if ("enabled" in data && data.enabled === true) {
return true;
}
} catch (e: any) {}
return false;
return true;
}
export async function getControlPlaneEnv(
ideSettingsPromise: Promise<IdeSettings>,
): Promise<ControlPlaneEnv> {
const ideSettings = await ideSettingsPromise;
return getControlPlaneEnvSync(ideSettings.continueTestEnvironment);
return getControlPlaneEnvSync(
ideSettings.continueTestEnvironment,
ideSettings.enableControlServerBeta,
);
}
export function getControlPlaneEnvSync(
ideTestEnvironment: IdeSettings["continueTestEnvironment"],
enableControlServerBeta: IdeSettings["enableControlServerBeta"],
): ControlPlaneEnv {
// Note .local overrides .staging
if (fs.existsSync(getLocalEnvironmentDotFilePath())) {
return LOCAL_ENV;
}
if (fs.existsSync(getStagingEnvironmentDotFilePath())) {
return STAGING_ENV;
}
if (enableControlServerBeta === true) {
return PRODUCTION_ENV;
}
const env =
ideTestEnvironment === "production"
? "hub"
@ -110,5 +118,8 @@ export async function useHub(
ideSettingsPromise: Promise<IdeSettings>,
): Promise<boolean> {
const ideSettings = await ideSettingsPromise;
if (ideSettings.enableControlServerBeta) {
return false;
}
return ideSettings.continueTestEnvironment !== "none";
}

View file

@ -1,7 +1,4 @@
import path from "path";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import ignore from "ignore";
import * as URI from "uri-js";
import { v4 as uuidv4 } from "uuid";
@ -14,31 +11,26 @@ import {
setupQuickstartConfig,
} from "./config/onboarding";
import { addContextProvider, addModel, deleteModel } from "./config/util";
import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache";
import { ContinueServerClient } from "./continueServer/stubs/client";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
import { ControlPlaneClient } from "./control-plane/client";
import { getControlPlaneEnv } from "./control-plane/env";
import { DevDataSqliteDb } from "./data/devdataSqlite";
import { DataLogger } from "./data/log";
import { streamDiffLines } from "./edit/streamDiffLines";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { getAllSuggestedDocs } from "./indexing/docs/suggestions";
import { defaultIgnoreFile } from "./indexing/ignore.js";
import Ollama from "./llm/llms/Ollama";
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
import { callTool } from "./tools/callTool";
import { ChatDescriber } from "./util/chatDescriber";
import { clipboardCache } from "./util/clipboardCache";
import { logDevData } from "./util/devdata";
import { DevDataSqliteDb } from "./util/devdataSqlite";
import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
import {
editConfigJson,
getConfigJsonPath,
setupInitialDotContinueDirectory,
} from "./util/paths";
import { localPathToUri } from "./util/pathToUri";
import { editConfigJson, migrateV1DevDataFiles } from "./util/paths";
import { Telemetry } from "./util/posthog";
import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
@ -52,8 +44,9 @@ import {
type IndexingProgressUpdate,
} from ".";
import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
import { isLocalAssistantFile } from "./config/loadLocalAssistants";
import { shouldIgnore } from "./indexing/shouldIgnore";
import { walkDirCache } from "./indexing/walkDir";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./protocol/messenger";
@ -63,7 +56,6 @@ export class Core {
completionProvider: CompletionProvider;
continueServerClientPromise: Promise<ContinueServerClient>;
codebaseIndexingState: IndexingProgressUpdate;
controlPlaneClient: ControlPlaneClient;
private docsService: DocsService;
private globalContext = new GlobalContext();
@ -96,7 +88,7 @@ export class Core {
private readonly onWrite: (text: string) => Promise<void> = async () => {},
) {
// Ensure .continue directory is created
setupInitialDotContinueDirectory();
migrateV1DevDataFiles();
this.codebaseIndexingState = {
status: "loading",
@ -104,22 +96,23 @@ export class Core {
progress: 0,
};
const ideInfoPromise = messenger.request("getIdeInfo", undefined);
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
silent: true,
useOnboarding: false,
});
this.controlPlaneClient = new ControlPlaneClient(
sessionInfoPromise,
ideSettingsPromise,
);
this.configHandler = new ConfigHandler(
this.ide,
ideSettingsPromise,
this.onWrite,
this.controlPlaneClient,
sessionInfoPromise,
(orgId: string | null) => {
void messenger.request("didSelectOrganization", {
orgId,
});
},
);
this.docsService = DocsService.createSingleton(
@ -135,12 +128,31 @@ export class Core {
profileId:
this.configHandler.currentProfile?.profileDescription.id ?? null,
});
// update additional submenu context providers registered via VSCode API
const additionalProviders =
this.configHandler.getAdditionalSubmenuContextProviders();
if (additionalProviders.length > 0) {
this.messenger.send("refreshSubmenuItems", {
providers: additionalProviders,
});
}
});
this.configHandler.onDidChangeAvailableProfiles((profiles) =>
this.messenger.send("didChangeAvailableProfiles", { profiles }),
this.configHandler.onDidChangeAvailableProfiles(
(profiles, selectedProfileId) =>
this.messenger.send("didChangeAvailableProfiles", {
profiles,
selectedProfileId,
}),
);
// Dev Data Logger
const dataLogger = DataLogger.getInstance();
dataLogger.core = this;
dataLogger.ideInfoPromise = ideInfoPromise;
dataLogger.ideSettingsPromise = ideSettingsPromise;
// Codebase Indexer and ContinueServerClient depend on IdeSettings
let codebaseIndexerResolve: (_: any) => void | undefined;
this.codebaseIndexerPromise = new Promise(
@ -187,12 +199,10 @@ export class Core {
const getLlm = async () => {
const { config } = await this.configHandler.loadConfig();
const selected = this.globalContext.get("selectedTabAutocompleteModel");
return (
config?.tabAutocompleteModels?.find(
(model) => model.title === selected,
) ?? config?.tabAutocompleteModels?.[0]
);
if (!config) {
return undefined;
}
return config.selectedModelByRole.autocomplete ?? undefined;
};
this.completionProvider = new CompletionProvider(
this.configHandler,
@ -226,11 +236,6 @@ export class Core {
}
});
on("update/selectTabAutocompleteModel", async (msg) => {
this.globalContext.update("selectedTabAutocompleteModel", msg.data);
void this.configHandler.reloadConfig();
});
// Special
on("abort", (msg) => {
this.abortedMessageIds.add(msg.messageId);
@ -261,8 +266,8 @@ export class Core {
});
// Dev data
on("devdata/log", (msg) => {
logDevData(msg.data.tableName, msg.data.data);
on("devdata/log", async (msg) => {
void DataLogger.getInstance().logDevData(msg.data);
});
// Edit config
@ -296,8 +301,15 @@ export class Core {
this.configHandler.updateIdeSettings(msg.data);
});
on("config/listProfiles", (msg) => {
return this.configHandler.listProfiles();
on("config/listProfiles", async (msg) => {
const profiles = this.configHandler.listProfiles();
const selectedProfileId =
this.configHandler.currentProfile?.profileDescription.id ?? null;
return { profiles, selectedProfileId };
});
on("config/refreshProfiles", async (msg) => {
await this.configHandler.loadAssistantsForSelectedOrg();
});
on("config/addContextProvider", async (msg) => {
@ -305,8 +317,19 @@ export class Core {
});
on("config/updateSharedConfig", async (msg) => {
this.globalContext.updateSharedConfig(msg.data);
const newSharedConfig = this.globalContext.updateSharedConfig(msg.data);
await this.configHandler.reloadConfig();
return newSharedConfig;
});
on("config/updateSelectedModel", async (msg) => {
const newSelectedModels = this.globalContext.updateSelectedModel(
msg.data.profileId,
msg.data.role,
msg.data.title,
);
await this.configHandler.reloadConfig();
return newSelectedModels;
});
on("controlPlane/openUrl", async (msg) => {
@ -319,7 +342,7 @@ export class Core {
});
on("controlPlane/listOrganizations", async (msg) => {
return await this.controlPlaneClient.listOrganizations();
return await this.configHandler.listOrganizations();
});
// Context providers
@ -386,11 +409,11 @@ export class Core {
const items = await provider.getContextItems(query, {
config,
llm,
embeddingsProvider: config.embeddingsProvider,
embeddingsProvider: config.selectedModelByRole.embed,
fullInput,
ide,
selectedCode,
reranker: config.reranker,
reranker: config.selectedModelByRole.rerank,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
});
@ -411,26 +434,25 @@ export class Core {
let knownError = false;
if (e instanceof Error) {
// A specific error where we're forcing the presence of embeddings provider on the config
// But Jetbrains doesn't support transformers JS
// So if a context provider needs it it will throw this error when the file isn't found
if (e.message.includes("all-MiniLM-L6-v2")) {
knownError = true;
const toastOption = "See Docs";
void this.ide
.showToast(
"error",
`Set up an embeddings model to use @${name}`,
toastOption,
)
.then((userSelection) => {
if (userSelection === toastOption) {
void this.ide.openUrl(
"https://docs.continue.dev/customize/model-types/embeddings",
);
}
});
}
// After removing transformers JS embeddings provider from jetbrains
// Should no longer see this error
// if (e.message.toLowerCase().includes("embeddings provider")) {
// knownError = true;
// const toastOption = "See Docs";
// void this.ide
// .showToast(
// "error",
// `Set up an embeddings model to use @${name}`,
// toastOption,
// )
// .then((userSelection) => {
// if (userSelection === toastOption) {
// void this.ide.openUrl(
// "https://docs.continue.dev/customize/model-roles/embeddings",
// );
// }
// });
// }
}
if (!knownError) {
void this.ide.showToast(
@ -636,6 +658,7 @@ export class Core {
params,
historyIndex,
selectedCode,
completionOptions,
} = msg.data;
const { config } = await configHandler.loadConfig();
@ -684,6 +707,7 @@ export class Core {
config,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
completionOptions,
})) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
@ -807,6 +831,11 @@ export class Core {
// Codebase indexing
on("index/forceReIndex", async ({ data }) => {
const { config } = await this.configHandler.loadConfig();
if (!config || config.disableIndexing) {
return; // TODO silent in case of commands?
}
walkDirCache.invalidate();
if (data?.shouldClearIndexes) {
const codebaseIndexer = await this.codebaseIndexerPromise;
await codebaseIndexer.clearIndexes();
@ -834,10 +863,12 @@ export class Core {
// TODO - remove remaining logic for these from IDEs where possible
on("files/changed", async ({ data }) => {
if (data?.uris?.length) {
walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes
for (const uri of data.uris) {
// Listen for file changes in the workspace
// URI TODO is this equality statement valid?
if (URI.equal(uri, localPathToUri(getConfigJsonPath()))) {
const currentProfileUri =
this.configHandler.currentProfile?.profileDescription.uri ?? "";
if (URI.equal(uri, currentProfileUri)) {
// Trigger a toast notification to provide UI feedback that config has been updated
const showToast =
this.globalContext.get("showConfigUpdateToast") ?? true;
@ -851,6 +882,8 @@ export class Core {
this.globalContext.update("showConfigUpdateToast", false);
}
}
await this.configHandler.reloadConfig();
continue;
}
if (
@ -864,32 +897,71 @@ export class Core {
uri.endsWith(".gitignore")
) {
// Reindex the workspaces
this.invoke("index/forceReIndex", undefined);
this.invoke("index/forceReIndex", {
shouldClearIndexes: true,
});
} else {
// Reindex the file
await this.refreshCodebaseIndexFiles([uri]);
const { config } = await this.configHandler.loadConfig();
if (config && !config.disableIndexing) {
// Reindex the file
const ignore = await shouldIgnore(uri, this.ide);
if (!ignore) {
await this.refreshCodebaseIndexFiles([uri]);
}
}
}
}
}
});
on("files/created", async ({ data }) => {
if (data?.uris?.length) {
const refreshIfNotIgnored = async (uris: string[]) => {
const toRefresh: string[] = [];
for (const uri of uris) {
const ignore = await shouldIgnore(uri, ide);
if (!ignore) {
toRefresh.push(uri);
}
}
if (toRefresh.length > 0) {
this.messenger.send("refreshSubmenuItems", {
providers: ["file"],
});
await this.refreshCodebaseIndexFiles(data.uris);
const { config } = await this.configHandler.loadConfig();
if (config && !config.disableIndexing) {
await this.refreshCodebaseIndexFiles(toRefresh);
}
}
};
on("files/created", async ({ data }) => {
if (data?.uris?.length) {
walkDirCache.invalidate();
void refreshIfNotIgnored(data.uris);
// If it's a local assistant being created, we want to reload all assistants so it shows up in the list
for (const uri of data.uris) {
if (isLocalAssistantFile(uri)) {
await this.configHandler.loadAssistantsForSelectedOrg();
}
}
}
});
on("files/deleted", async ({ data }) => {
if (data?.uris?.length) {
this.messenger.send("refreshSubmenuItems", {
providers: ["file"],
});
await this.refreshCodebaseIndexFiles(data.uris);
walkDirCache.invalidate();
void refreshIfNotIgnored(data.uris);
}
});
on("files/closed", async ({ data }) => {
if (data.uris) {
this.messenger.send("didCloseFiles", {
uris: data.uris,
});
}
});
on("files/opened", async ({ data }) => {
if (data?.uris?.length) {
// Do something on files opened
@ -928,15 +1000,21 @@ export class Core {
});
//
on("didChangeSelectedProfile", (msg) => {
void this.configHandler.setSelectedProfile(msg.data.id);
void this.configHandler.reloadConfig();
on("didChangeSelectedProfile", async (msg) => {
await this.configHandler.setSelectedProfile(msg.data.id);
await this.configHandler.reloadConfig();
});
on("didChangeSelectedOrg", (msg) => {
void this.configHandler.setSelectedOrgId(msg.data.id);
void this.configHandler.reloadConfig();
void this.configHandler.loadPlatformProfiles();
on("didChangeSelectedOrg", async (msg) => {
await this.configHandler.setSelectedOrgId(msg.data.id);
await this.configHandler.loadAssistantsForSelectedOrg();
if (msg.data.profileId) {
this.invoke("didChangeSelectedProfile", {
id: msg.data.profileId,
});
} else {
await this.configHandler.reloadConfig();
}
});
on("didChangeControlPlaneSessionInfo", async (msg) => {
@ -953,19 +1031,15 @@ export class Core {
});
on("didChangeActiveTextEditor", async ({ data: { filepath } }) => {
const ignoreInstance = ignore().add(defaultIgnoreFile);
let rootDirectory = await this.ide.getWorkspaceDirs();
const relativeFilePath = path.relative(rootDirectory[0], filepath);
try {
if (!ignoreInstance.ignores(relativeFilePath)) {
const ignore = shouldIgnore(filepath, this.ide);
if (!ignore) {
recentlyEditedFilesCache.set(filepath, filepath);
}
} catch (e) {
if (e instanceof RangeError) {
// do nothing, this can happen when editing a file outside the workspace such as `../extensions/.continue-debug/config.json`
} else {
console.debug("unhandled ignores error", relativeFilePath, e);
}
console.error(
`didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`,
);
}
});
@ -1086,6 +1160,7 @@ export class Core {
this.messenger.send("refreshSubmenuItems", {
providers: "dependsOnIndexing",
});
this.indexingCancellationController = undefined;
}
// private

View file

@ -5,8 +5,9 @@ import sqlite3 from "sqlite3";
import { DatabaseConnection } from "../indexing/refreshIndex.js";
import { getDevDataSqlitePath } from "./paths.js";
import { getDevDataSqlitePath } from "../util/paths.js";
/* The Dev Data SQLITE table is only used for local tokens generated */
export class DevDataSqliteDb {
static db: DatabaseConnection | null = null;

226
core/data/log.ts Normal file
View file

@ -0,0 +1,226 @@
import fs from "fs";
import path from "path";
import {
allDevEventNames,
DataLogLevel,
DevDataLogEvent,
devDataVersionedSchemas,
} from "@continuedev/config-yaml";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import * as URI from "uri-js";
import { fileURLToPath } from "url";
import { AnyZodObject } from "zod";
import { Core } from "../core.js";
import { IdeInfo, IdeSettings } from "../index.js";
import { getDevDataFilePath } from "../util/paths.js";
import { joinPathsToUri } from "../util/uri.js";
const DEFAULT_DEV_DATA_LEVEL: DataLogLevel = "all";
export const LOCAL_DEV_DATA_VERSION = "0.2.0";
export class DataLogger {
private static instance: DataLogger | null = null;
core?: Core;
ideSettingsPromise?: Promise<IdeSettings>;
ideInfoPromise?: Promise<IdeInfo>;
private constructor() {}
public static getInstance(): DataLogger {
if (DataLogger.instance === null) {
DataLogger.instance = new DataLogger();
}
return DataLogger.instance;
}
async addBaseValues(
body: Record<string, any>,
eventName: string,
schema: string,
zodSchema: AnyZodObject,
): Promise<Record<string, any>> {
const newBody = { ...body };
const ideSettings = await this.ideSettingsPromise;
const ideInfo = await this.ideInfoPromise;
if ("eventName" in zodSchema.shape) {
newBody.eventName = eventName;
}
if (!newBody.timestamp && "timestamp" in zodSchema.shape) {
newBody.timestamp = new Date().toISOString();
}
if ("schema" in zodSchema.shape) {
newBody.schema = schema;
}
if ("userAgent" in zodSchema.shape) {
newBody.userAgent = ideInfo
? `${ideInfo.name}/${ideInfo.version} (Continue/${ideInfo.extensionVersion})`
: "Unknown/Unknown (Continue/Unknown)";
}
if ("selectedProfileId" in zodSchema.shape) {
newBody.selectedProfileId =
this.core?.configHandler.currentProfile?.profileDescription.id ?? "";
}
if ("userId" in zodSchema.shape) {
newBody.userId = ideSettings?.userToken ?? "";
}
return newBody;
}
async logDevData(event: DevDataLogEvent) {
// Local logs (always on for all levels)
try {
const filepath: string = getDevDataFilePath(
event.name,
LOCAL_DEV_DATA_VERSION,
);
const localSchema =
devDataVersionedSchemas[LOCAL_DEV_DATA_VERSION]["all"][event.name];
if (!localSchema) {
throw new Error(
`Schema ${LOCAL_DEV_DATA_VERSION} doesn't exist at level "all"`,
);
}
const eventDataWithBaseValues = await this.addBaseValues(
event.data,
event.name,
LOCAL_DEV_DATA_VERSION,
localSchema,
);
const parsed = localSchema?.safeParse(eventDataWithBaseValues);
if (parsed?.success) {
fs.writeFileSync(filepath, `${JSON.stringify(parsed.data)}\n`, {
flag: "a",
});
}
} catch (error) {
console.error("Error logging local dev data:", error);
}
// Remote logs
const config = (await this.core?.configHandler.loadConfig())?.config;
if (config?.data?.length) {
await Promise.allSettled(
config.data.map(async (dataConfig) => {
try {
// First extract the data schema based on the version and level
const { schema } = dataConfig;
const level = dataConfig.level ?? DEFAULT_DEV_DATA_LEVEL;
// Skip event if `events` is specified and does not include the event
const events = dataConfig.events ?? allDevEventNames;
if (!events.includes(event.name)) {
return;
}
const versionSchemas = devDataVersionedSchemas[schema];
if (!versionSchemas) {
throw new Error(
`Attempting to log dev data to non-existent version ${schema}`,
);
}
const levelSchemas = versionSchemas[level];
if (!levelSchemas) {
throw new Error(
`Attempting to log dev data at level ${level} for version ${schema} which does not exist`,
);
}
const zodSchema = levelSchemas[event.name];
if (!zodSchema) {
throw new Error(
`Attempting to log dev data for event ${event.name} at level ${level} for version ${schema}: no schema found`,
);
}
const eventDataWithBaseValues = await this.addBaseValues(
event.data,
event.name,
schema,
zodSchema,
);
const parsed = zodSchema.safeParse(eventDataWithBaseValues);
if (!parsed.success) {
throw new Error(
`Failed to parse event data for event ${event.name} and schema ${schema}\n:${parsed.error.toString()}`,
);
}
const uriComponents = URI.parse(dataConfig.destination);
// Send to remote server
if (
uriComponents.scheme === "https" ||
uriComponents.scheme === "http"
) {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (dataConfig.apiKey) {
headers["Authorization"] = `Bearer ${dataConfig.apiKey}`;
}
// For events going to Continue, overwrite the access token
if (
uriComponents.host?.endsWith(".continue.dev") ||
uriComponents.host === "continue.dev"
) {
//
const accessToken =
await this.core?.configHandler.controlPlaneClient.getAccessToken();
headers["Authorization"] = `Bearer ${accessToken}`;
}
const profileId =
this.core?.configHandler.currentProfile?.profileDescription
.id ?? "";
const response = await fetchwithRequestOptions(
dataConfig.destination,
{
method: "POST",
headers,
body: JSON.stringify({
name: event.name,
data: parsed.data,
schema,
level,
profileId,
}),
},
dataConfig.requestOptions,
);
if (!response.ok) {
throw new Error(
`Post request failed. ${response.status}: ${response.statusText}`,
);
}
} else if (uriComponents.scheme === "file") {
// Write to jsonc file for local file URIs
const dirUri = joinPathsToUri(dataConfig.destination, schema);
const dirPath = fileURLToPath(dirUri);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
const filepath = path.join(dirPath, `${event.name}.jsonl`);
const jsonLine = JSON.stringify(event.data);
fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
} else {
throw new Error(`Unsupported URI scheme ${uriComponents.scheme}`);
}
} catch (error) {
console.error(
`Error logging data to ${dataConfig.destination}: ${error instanceof Error ? error.message : error}`,
);
}
}),
);
}
}
}

View file

@ -29,4 +29,16 @@ describe("Test myers diff function", () => {
{ type: "same", line: "E" },
]);
});
test("should ignore newline differences at end", () => {
const linesA = "A\nB\nC\n";
const linesB = "A\nB\nC";
const diffLines = myersDiff(linesA, linesB);
expect(diffLines).toEqual([
{ type: "same", line: "A" },
{ type: "same", line: "B" },
{ type: "same", line: "C" },
]);
});
});

View file

@ -10,7 +10,7 @@ export function convertMyersChangeToDiffLines(change: Change): DiffLine[] {
: "same";
const lines = change.value.split("\n");
// `diff` package is always adding an extra new line at the end of the array
// Ignore the \n at the end of the final line, if there is one
if (lines[lines.length - 1] === "") {
lines.pop();
}
@ -18,9 +18,27 @@ export function convertMyersChangeToDiffLines(change: Change): DiffLine[] {
return lines.map((line) => ({ type, line }));
}
// The interpretation of lines in oldContent and newContent is the same as jsdiff
// Lines are separated by \n, with the exception that a trailing \n does *not*
// represent an empty line.
//
// The default for jsdiff is that "foo" and "foo\n" are *different* single-line
// contents, but we can't represent that: to avoid a diff
// [ { type: "old", line: "foo" }, { type: "new", line: "foo" } ], we
// pass ignoreNewlineAtEof: true.
export function myersDiff(oldContent: string, newContent: string): DiffLine[] {
const theirFormat = diffLines(oldContent, newContent);
const theirFormat = diffLines(oldContent, newContent, {
ignoreNewlineAtEof: true,
});
const ourFormat = theirFormat.flatMap(convertMyersChangeToDiffLines);
while (
ourFormat.length > 0 &&
ourFormat[ourFormat.length - 1].type === "old" &&
ourFormat[ourFormat.length - 1].line === ""
) {
ourFormat.pop();
}
return ourFormat;
}

View file

@ -5,6 +5,7 @@ import { getUriFileExtension } from "../../util/uri";
import { deterministicApplyLazyEdit } from "./deterministic";
import { streamLazyApply } from "./streamLazyApply";
import { isUnifiedDiffFormat, applyUnifiedDiff } from "./unifiedDiffApply";
function canUseInstantApply(filename: string) {
const fileExtension = getUriFileExtension(filename);
@ -18,7 +19,8 @@ export async function applyCodeBlock(
llm: ILLM,
fastLlm: ILLM,
): Promise<[boolean, AsyncGenerator<DiffLine>]> {
if (canUseInstantApply(filename)) {
// This was buggy, removed for now, maybe forever
if (false && canUseInstantApply(filename)) {
const diffLines = await deterministicApplyLazyEdit(
oldFile,
newFile,
@ -32,5 +34,16 @@ export async function applyCodeBlock(
}
}
// If the code block is a diff
if (isUnifiedDiffFormat(newFile)) {
try {
const diffLines = applyUnifiedDiff(oldFile, newFile);
const diffGenerator = generateLines(diffLines!);
return [true, diffGenerator];
} catch (e) {
console.error("Failed to apply unified diff", e);
}
}
return [false, streamLazyApply(oldFile, filename, newFile, llm, fastLlm)];
}

View file

@ -0,0 +1,415 @@
import { applyUnifiedDiff, isUnifiedDiffFormat } from "./unifiedDiffApply";
describe("isUnifiedDiffFormat", () => {
it("should return true for valid unified diff format", () => {
const validDiff = `--- original.txt
+++ modified.txt
@@ -1,3 +1,4 @@
line1
-line2
+newline2
+newline3
line3`;
expect(isUnifiedDiffFormat(validDiff)).toBe(true);
});
it("should return false for empty diff", () => {
expect(isUnifiedDiffFormat("")).toBe(false);
});
it("should return false for diff without hunk header", () => {
const invalidDiff = `--- original.txt
+++ modified.txt
+line1
-line2
+line3`;
expect(isUnifiedDiffFormat(invalidDiff)).toBe(false);
});
it("should return false for diff without valid content", () => {
const invalidDiff = `--- original.txt
+++ modified.txt
@@ -1,3 +1,4 @@`;
expect(isUnifiedDiffFormat(invalidDiff)).toBe(false);
});
it("should return true even without file headers if hunk headers exist", () => {
const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@
line1
-line2
+newline2
+newline3
line3`;
expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true);
});
it("should return true in case of empty lines", () => {
const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@
line1
-line2
+newline2
line3`;
expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true);
});
});
describe("applyUnifiedDiff", () => {
it("should correctly apply a add line of unified diff", () => {
const sourceCode = `func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Calculator started! Available operations:")
fmt.Println(" + : Addition")
fmt.Println(" - : Subtraction")
fmt.Println(" * : Multiplication")
fmt.Println(" / : Division")
fmt.Println(" ^ : Power")
fmt.Println(" √ : Square root (use only one number)")
}
// End of file`;
const diffText = `--- original.go
+++ updated.go
@@ -30,6 +30,7 @@
fmt.Println(" / : Division")
fmt.Println(" ^ : Power")
fmt.Println(" √ : Square root (use only one number)")
+ fmt.Println(" log: Logarithm (use 'log base number')")
}`;
const result = applyUnifiedDiff(sourceCode, diffText);
const expected = [
{ type: "same", line: "func main() {" },
{ type: "same", line: " scanner := bufio.NewScanner(os.Stdin)" },
{ type: "same", line: " fmt.Println(\"Calculator started! Available operations:\")" },
{ type: "same", line: " fmt.Println(\" + : Addition\")" },
{ type: "same", line: " fmt.Println(\" - : Subtraction\")" },
{ type: "same", line: " fmt.Println(\" * : Multiplication\")" },
{ type: "same", line: " fmt.Println(\" / : Division\")" },
{ type: "same", line: " fmt.Println(\" ^ : Power\")" },
{ type: "same", line: " fmt.Println(\" √ : Square root (use only one number)\")" },
{ type: "new", line: " fmt.Println(\" log: Logarithm (use 'log base number')\")" },
{ type: "same", line: "}" },
{ type: "same", line: "// End of file" }
];
expect(result).toEqual(expected);
});
it("should correctly apply multiple insertions and deletions", () => {
const sourceCode = `package main
import "fmt"
func main() {
fmt.Println("Hello")
fmt.Println("World")
}`;
const diffText = `--- original.go
+++ updated.go
@@ -1,8 +1,11 @@
package main
-import "fmt"
+import (
+ "fmt"
+ "time"
+)
func main() {
- fmt.Println("Hello")
+ fmt.Printf("The time is: %v\\n", time.Now())
- fmt.Println("World")
+ fmt.Println("Goodbye!")
}`;
const result = applyUnifiedDiff(sourceCode, diffText);
const expected = [
{ type: "same", line: "package main" },
{ type: "same", line: "" },
{ type: "old", line: "import \"fmt\"" },
{ type: "new", line: "import (" },
{ type: "new", line: " \"fmt\"" },
{ type: "new", line: " \"time\"" },
{ type: "new", line: ")" },
{ type: "same", line: "" },
{ type: "same", line: "func main() {" },
{ type: "old", line: " fmt.Println(\"Hello\")" },
{ type: "new", line: " fmt.Printf(\"The time is: %v\\n\", time.Now())" },
{ type: "old", line: " fmt.Println(\"World\")" },
{ type: "new", line: " fmt.Println(\"Goodbye!\")" },
{ type: "same", line: "}" }
];
expect(result).toEqual(expected);
});
it("should correctly apply multiple diff blocks", () => {
const sourceCode = `package main
import (
"bufio"
"fmt"
"math"
"os"
"strconv"
"strings"
"testing"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Calculator started! Available operations:")
fmt.Println(" + : Addition")
fmt.Println(" - : Subtraction")
fmt.Println(" * : Multiplication")
fmt.Println(" / : Division")
fmt.Println(" ^ : Power")
fmt.Println(" √ : Square root (use only one number)")
for {
fmt.Print("Enter calculation (e.g., 5 + 3 or √ 16) or 'q' to quit: ")
scanner.Scan()
input := scanner.Text()
if strings.ToLower(input) == "q" {
fmt.Println("Goodbye!")
break
}
result, err := calculate(input)
if err != nil {
fmt.Printf("Error: %v\n", err)
continue
}
fmt.Printf("Result: %v\n", result)
}
}
func calculate(input string) (float64, error) {
parts := strings.Fields(input)
if len(parts) < 2 {
return 0, fmt.Errorf("invalid input format: please use 'number operator number' or '√ number'")
}
if parts[0] == "√" {
if len(parts) != 2 {
return 0, fmt.Errorf("square root operation requires exactly one number")
}
num, err := strconv.ParseFloat(parts[1], 64)
if err != nil {
return 0, fmt.Errorf("invalid number for square root: %v", err)
}
if num < 0 {
return 0, fmt.Errorf("cannot calculate square root of a negative number")
}
return math.Sqrt(num), nil
}
if len(parts) != 3 {
return 0, fmt.Errorf("invalid input format: please use 'number operator number'")
}
num1, err := strconv.ParseFloat(parts[0], 64)
if err != nil {
return 0, fmt.Errorf("invalid first number: %v", err)
}
operator := parts[1]
num2, err := strconv.ParseFloat(parts[2], 64)
if err != nil {
return 0, fmt.Errorf("invalid second number: %v", err)
}
switch operator {
case "+":
return num1 + num2, nil
case "-":
return num1 - num2, nil
case "*":
return num1 * num2, nil
case "/":
if num2 == 0 {
return 0, fmt.Errorf("division by zero is not allowed")
}
return num1 / num2, nil
case "^":
return math.Pow(num1, num2), nil
default:
return 0, fmt.Errorf("invalid operator: must be +, -, *, /, ^, or √")
}
}
func TestCalculate(t *testing.T) {
tests := []struct {
input string
expected float64
hasError bool
}{
{"2 + 3", 5, false},
{"10 - 5", 5, false},
{"4 * 3", 12, false},
{"15 / 3", 5, false},
{"2 ^ 3", 8, false},
{"√ 16", 4, false},
{"2 + a", 0, true},
{"15 / 0", 0, true},
{"√ -4", 0, true},
{"3 $ 4", 0, true},
{"", 0, true},
{"1", 0, true},
{"1 +", 0, true},
{"+ 1", 0, true},
{"√ 2 3", 0, true},
}
for _, test := range tests {
result, err := calculate(test.input)
if test.hasError && err == nil {
t.Errorf("Expected error for input '%s', but got none", test.input)
continue
}
if !test.hasError && err != nil {
t.Errorf("Unexpected error for input '%s': %v", test.input, err)
continue
}
if !test.hasError && result != test.expected {
t.Errorf("For input '%s': expected %f, but got %f", test.input, test.expected, result)
}
}
}
func TestSpecialCases(t *testing.T) {
result, err := calculate("2.5 + 2.5")
if err != nil {
t.Errorf("Unexpected error for floating point addition: %v", err)
}
if result != 5.0 {
t.Errorf("Floating point addition failed: expected 5.0, got %f", result)
}
result, err = calculate("2.5 ^ 2")
if err != nil {
t.Errorf("Unexpected error for power operation: %v", err)
}
expected := 6.25
if math.Abs(result-expected) > 0.0001 {
t.Errorf("Power operation failed: expected %f, got %f", expected, result)
}
result, err = calculate("√ 2")
if err != nil {
t.Errorf("Unexpected error for square root: %v", err)
}
expected = math.Sqrt(2)
if math.Abs(result-expected) > 0.0001 {
t.Errorf("Square root operation failed: expected %f, got %f", expected, result)
}
}
func TestLargeNumbers(t *testing.T) {
result, err := calculate("1000000000 + 1000000000")
if err != nil {
t.Errorf("Unexpected error for adding large numbers: %v", err)
}
if result != 2000000000 {
t.Errorf("Adding large numbers failed: expected 2000000000, got %f", result)
}
result, err = calculate("1000000 * 1000000")
if err != nil {
t.Errorf("Unexpected error for multiplying large numbers: %v", err)
}
if result != 1000000000000 {
t.Errorf("Multiplying large numbers failed: expected 1000000000000, got %f", result)
}
result, err = calculate("2 ^ 30")
if err != nil {
t.Errorf("Unexpected error for large exponent operation: %v", err)
}
expected := math.Pow(2, 30)
if result != expected {
t.Errorf("Power operation with large exponent failed: expected %f, got %f", expected, result)
}
result, err = calculate("1000000000000 / 1000000")
if err != nil {
t.Errorf("Unexpected error for dividing large numbers: %v", err)
}
if result != 1000000 {
t.Errorf("Dividing large numbers failed: expected 1000000, got %f", result)
}
}`;
const diffText = `--- original.go
+++ updated.go
@@ -30,6 +30,7 @@
fmt.Println(" / : Division")
fmt.Println(" ^ : Power")
fmt.Println(" √ : Square root (use only one number)")
+ fmt.Println(" log: Logarithm (use 'log base number')")
+ fmt.Println(" Base must be > 0 and != 1, number must be > 0")
for {
fmt.Print("Enter calculation (e.g., 5 + 3 or √ 16) or 'q' to quit: ")
@@ -73,6 +74,8 @@
}
return math.Sqrt(num), nil
}
+
+ // Handle logarithmic operations
+ if parts[0] == "log" {
+ if len(parts) != 3 {
+ return 0, fmt.Errorf("logarithm operation requires exactly two arguments: 'log base number'")
+ }
+ base, err := strconv.ParseFloat(parts[1], 64)
+ if err != nil || base <= 0 || base == 1 {
+ return 0, fmt.Errorf("invalid base for logarithm: must be > 0 and != 1")
+ }
+ num, err := strconv.ParseFloat(parts[2], 64)
+ if err != nil || num <= 0 {
+ return 0, fmt.Errorf("invalid number for logarithm: must be > 0")
+ }
+ return math.Log(num) / math.Log(base), nil
+ }
+
if len(parts) != 3 {
return 0, fmt.Errorf("invalid input format: please use 'number operator number'")
@@ -155,6 +158,15 @@
}
}
}
+
+func TestLogarithmicCases(t *testing.T) {
+ tests := []struct {
+ input string
+ expected float64
+ hasError bool
+ }{
+ {"log 2 8", 3, false},
+ {"log 10 100", 2, false},
+ {"log 10 -5", 0, true},
+ {"log 1 100", 0, true},
+ {"log 0.5 0.25", 2, false},
+ }`;
const result = applyUnifiedDiff(sourceCode, diffText);
expect(result[0].line).toEqual("package main");
// 1st block
expect(result[18].line).toEqual("\tfmt.Println(\" √ : Square root (use only one number)\")");
expect(result[19].line).toEqual(" fmt.Println(\" log: Logarithm (use 'log base number')\")");
expect(result[20].line).toEqual(" fmt.Println(\" Base must be > 0 and != 1, number must be > 0\")");
// 2nd block
expect(result[56]).toEqual({type: "same", line: "\t}"});
expect(result[57]).toEqual({type: "new", line: "\t"});
expect(result[58]).toEqual({type: "new", line: "\t// Handle logarithmic operations"});
expect(result[73]).toEqual({type: "new", line: ""});
expect(result[74]).toEqual({type: "same", line: "\tif len(parts) != 3 {"});
// 3rd block
expect(result[140]).toEqual({type: "same", line: "}"});
expect(result[141]).toEqual({type: "new", line: ""});
expect(result[142]).toEqual({type: "new", line: "func TestLogarithmicCases(t *testing.T) {"});
expect(result[153]).toEqual({type: "new", line: "\t}"});
expect(result[154]).toEqual({type: "same", line: "func TestSpecialCases(t *testing.T) {"});
});
it("should throw error when hunk cannot be matched to source", () => {
const sourceCode = `line1
line2
line3`;
const diffText = `--- a.txt
+++ b.txt
@@ -1,3 +1,4 @@
missing1
-missing2
+newline2
missing3`;
expect(() => applyUnifiedDiff(sourceCode, diffText))
.toThrow("Hunk could not be applied cleanly to source code.");
});
});

View file

@ -0,0 +1,152 @@
import { DiffLine } from "../../index";
/**
* Checks if a string matches unified diff format by validating:
* 1. Has at least one hunk header (@@ -n,m +n,m @@)
* 2. Contains valid diff content lines (starting with +, -, or space) which are not header lines
*/
export function isUnifiedDiffFormat(diff: string): boolean {
const lines = diff.trim().split("\n");
if (lines.length < 3) {return false;}
let hasHunkHeader = false;
let hasValidContent = false;
for (const line of lines) {
if (line.startsWith("---") || line.startsWith("+++")) {
// ignore file headers - they are not required or useful
} else if (line.match(/^@@ -\d+,?\d* \+\d+,?\d* @@/)) {
hasHunkHeader = true;
} else if (line.match(/^[+ -]/) || line === "") {
hasValidContent = true;
}
}
return hasHunkHeader && hasValidContent;
}
function extractBeforeLines(hunkLines: string[]): string[] {
return hunkLines
.filter((line) => line.startsWith("-") || !line.startsWith("+"))
.map((line) => line.substring(1));
}
/**
* Applies a unified diff to source code and returns an array of DiffLine objects.
* Each DiffLine contains a type ("same", "new", or "old") and the line content.
*
* @throws Error if the diff cannot be cleanly applied to the source
*/
export function applyUnifiedDiff(sourceCode: string, unifiedDiffText: string): DiffLine[] {
const sourceLines = sourceCode.split(/\r?\n/);
const hunks = parseUnifiedDiff(unifiedDiffText);
const diffResult: DiffLine[] = [];
let currentPos = 0; // pointer in sourceLines
for (const hunk of hunks) {
const hunkBeforeLines = extractBeforeLines(hunk.lines);
const hunkStart = findHunkInSource(sourceLines, hunkBeforeLines, currentPos);
if (hunkStart === -1) {
// All hunks must be found in the source code. If not, throw an error.
throw new Error("Hunk could not be applied cleanly to source code.");
}
// Emit any unchanged lines that come before this hunk.
for (let i = currentPos; i < hunkStart; i++) {
diffResult.push({ type: "same", line: sourceLines[i] });
}
let hunkSourcePos = hunkStart;
for (const dline of hunk.lines) {
const srcLine = sourceLines[hunkSourcePos];
if (dline.startsWith("+")) {
// Insertion: output new line (strip the '+' marker)
diffResult.push({ type: "new", line: dline.substring(1) });
} else if (dline.startsWith("-")) {
// Removal: output the removed (old) line and advance the pointer.
diffResult.push({ type: "old", line: srcLine });
hunkSourcePos++;
} else {
// Context line: use the source line (in case the diff’s context has a minor whitespace error)
// and advance the pointer.
diffResult.push({ type: "same", line: srcLine });
hunkSourcePos++;
}
}
currentPos = hunkSourcePos;
}
for (let i = currentPos; i < sourceLines.length; i++) {
diffResult.push({ type: "same", line: sourceLines[i] });
}
return diffResult;
}
interface Hunk {
lines: string[];
}
/**
* Parses a unified diff string into an array of hunks.
* It skips the file header lines (starting with "---" or "+++") and hunk header lines (starting with "@@"),
* then collects the remaining lines (which may start with '+' or '-' or have no prefix).
*/
function parseUnifiedDiff(diffText: string): Hunk[] {
const lines = diffText.split(/\r?\n/);
const hunks: Hunk[] = [];
let currentHunk: Hunk | null = null;
for (const line of lines) {
if (line.startsWith("---") || line.startsWith("+++")) {
// Skip file header lines.
continue;
}
if (line.startsWith("@@")) {
if (currentHunk) {
hunks.push(currentHunk);
}
currentHunk = { lines: [] };
continue;
}
currentHunk?.lines.push(line);
}
if (currentHunk) {
hunks.push(currentHunk);
}
return hunks;
}
/**
* Searches for an occurrence of the block of lines (the “before” block) in sourceLines,
* starting at startIndex. Comparison is done by checking if the lines are exactly equal,
* or if their trimmed versions are equal.
*
* Returns the index in sourceLines where the block begins, or -1 if no match is found.
*/
function findHunkInSource(sourceLines: string[], hunkBeforeLines: string[], startIndex: number): number {
for (let i = startIndex; i <= sourceLines.length - hunkBeforeLines.length; i++) {
let match = true;
for (let j = 0; j < hunkBeforeLines.length; j++) {
const sl = sourceLines[i + j];
const hl = hunkBeforeLines[j];
if (!linesMatch(sl, hl)) {
match = false;
break;
}
}
if (match) {
return i;
}
}
return -1;
}
/**
* Returns true if the two lines are either exactly equal or equal after trimming whitespace and tabs.
*/
function linesMatch(a: string, b: string): boolean {
const trimmedA = a.replace(/^\s+/, "");
const trimmedB = b.replace(/^\s+/, "");
return trimmedA === trimmedB;
}

72
core/index.d.ts vendored
View file

@ -1,4 +1,4 @@
import { ModelRole } from "@continuedev/config-yaml";
import { DataDestination, ModelRole } from "@continuedev/config-yaml";
import Parser from "web-tree-sitter";
import { GetGhTokenArgs } from "./protocol/ide";
declare global {
@ -60,7 +60,7 @@ export interface IndexingStatus {
progress: number;
description: string;
status: "indexing" | "complete" | "paused" | "failed" | "aborted" | "pending";
embeddingsProviderId: string;
embeddingsProviderId?: string;
isReindexing?: boolean;
debugInfo?: string;
title: string;
@ -163,6 +163,10 @@ export interface ILLM extends LLMOptions {
): string | ChatMessage[];
}
export interface ModelInstaller {
installModel(modelName: string, signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void): Promise<any>;
}
export type ContextProviderType = "normal" | "query" | "submenu";
export interface ContextProviderDescription {
@ -179,8 +183,8 @@ export type FetchFunction = (url: string | URL, init?: any) => Promise<any>;
export interface ContextProviderExtras {
config: ContinueConfig;
fullInput: string;
embeddingsProvider: ILLM;
reranker: ILLM | undefined;
embeddingsProvider: ILLM | null;
reranker: ILLM | null;
llm: ILLM;
ide: IDE;
selectedCode: RangeInFile[];
@ -308,7 +312,7 @@ export interface CompletionOptions extends BaseCompletionOptions {
model: string;
}
export type ChatMessageRole = "user" | "assistant" | "system" | "tool";
export type ChatMessageRole = "user" | "assistant" | "thinking" | "system" | "tool";
export type TextMessagePart = {
type: "text";
@ -353,6 +357,14 @@ export interface UserChatMessage {
content: MessageContent;
}
export interface ThinkingChatMessage {
role: "thinking";
content: MessageContent;
signature?: string;
redactedThinking?: string;
toolCalls?: ToolCallDelta[];
}
export interface AssistantChatMessage {
role: "assistant";
content: MessageContent;
@ -367,6 +379,7 @@ export interface SystemChatMessage {
export type ChatMessage =
| UserChatMessage
| AssistantChatMessage
| ThinkingChatMessage
| SystemChatMessage
| ToolResultChatMessage;
@ -478,9 +491,15 @@ export interface LLMOptions {
writeLog?: (str: string) => Promise<void>;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
// continueProperties
apiKeyLocation?: string;
aiGatewaySlug?: string;
apiBase?: string;
orgScopeId?: string | null;
onPremProxyUrl?: string | null;
aiGatewaySlug?: string;
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
roles?: ModelRole[];
@ -504,14 +523,16 @@ export interface LLMOptions {
profile?: string;
modelArn?: string;
// AWS and GCP Options
// AWS and VertexAI Options
region?: string;
// GCP and Watsonx Options
// VertexAI and Watsonx Options
projectId?: string;
// IBM watsonx Options
deploymentId?: string;
env?: Record<string, string | number | boolean>;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
@ -535,7 +556,7 @@ export interface CustomLLMWithOptionals {
signal: AbortSignal,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
) => AsyncGenerator<ChatMessage | string>;
listModels?: (
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => Promise<string[]>;
@ -730,6 +751,7 @@ export interface ContinueSDK {
selectedCode: RangeInFile[];
config: ContinueConfig;
fetch: FetchFunction;
completionOptions?: LLMFullCompletionOptions;
}
export interface SlashCommand {
@ -908,6 +930,8 @@ export interface BaseCompletionOptions {
prediction?: Prediction;
tools?: Tool[];
toolChoice?: ToolChoice;
reasoning?: boolean;
reasoningBudgetTokens?: number;
}
export interface ModelCapability {
@ -920,8 +944,14 @@ export interface ModelDescription {
provider: string;
model: string;
apiKey?: string;
// continueProperties
apiKeyLocation?: string;
apiBase?: string;
orgScopeId?: string | null;
onPremProxyUrl?: string | null;
contextLength?: number;
maxStopWords?: number;
template?: TemplateType;
@ -942,15 +972,16 @@ export interface EmbedOptions {
apiType?: string;
apiVersion?: string;
requestOptions?: RequestOptions;
maxChunkSize?: number;
maxBatchSize?: number;
maxEmbeddingChunkSize?: number;
maxEmbeddingBatchSize?: number;
// AWS options
profile?: string;
// AWS and GCP Options
// AWS and VertexAI Options
region?: string;
// GCP and Watsonx Options
// VertexAI and Watsonx Options
projectId?: string;
}
@ -1017,6 +1048,7 @@ export interface ContinueUIConfig {
displayRawMarkdown?: boolean;
showChatScrollbar?: boolean;
codeWrap?: boolean;
showSessionTabs?: boolean;
}
export interface ContextMenuConfig {
@ -1028,9 +1060,9 @@ export interface ContextMenuConfig {
}
export interface ExperimentalModelRoles {
repoMapFileSelection?: string;
inlineEdit?: string;
applyCodeBlock?: string;
repoMapFileSelection?: string;
}
export type EditStatus =
@ -1147,6 +1179,7 @@ export interface SerializedContinueConfig {
experimental?: ExperimentalConfig;
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
data?: DataDestination[];
}
export type ConfigMergeType = "merge" | "overwrite";
@ -1199,6 +1232,7 @@ export interface Config {
experimental?: ExperimentalConfig;
/** Analytics configuration */
analytics?: AnalyticsConfig;
data?: DataDestination[];
}
// in the actual Continue source code
@ -1213,15 +1247,15 @@ export interface ContinueConfig {
disableSessionTitles?: boolean;
disableIndexing?: boolean;
userToken?: string;
embeddingsProvider: ILLM;
tabAutocompleteModels?: ILLM[];
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
ui?: ContinueUIConfig;
reranker?: ILLM;
experimental?: ExperimentalConfig;
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
tools: Tool[];
modelsByRole: Record<ModelRole, ILLM[]>;
selectedModelByRole: Record<ModelRole, ILLM | null>;
data?: DataDestination[];
}
export interface BrowserSerializedContinueConfig {
@ -1235,15 +1269,15 @@ export interface BrowserSerializedContinueConfig {
disableIndexing?: boolean;
disableSessionTitles?: boolean;
userToken?: string;
embeddingsProvider?: string;
ui?: ContinueUIConfig;
reranker?: RerankerDescription;
experimental?: ExperimentalConfig;
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
tools: Tool[];
usePlatform: boolean;
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
modelsByRole: Record<ModelRole, ModelDescription[]>;
selectedModelByRole: Record<ModelRole, ModelDescription | null>;
}
// DOCS SUGGESTIONS AND PACKAGE INFO

View file

@ -7,12 +7,7 @@ import {
getQueryForFile,
} from "../util/treeSitter";
import {
DatabaseConnection,
SqliteDb,
tagToString,
truncateSqliteLikePattern,
} from "./refreshIndex";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
import {
IndexResultType,
MarkCompleteCallback,
@ -398,18 +393,23 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
static async getPathsAndSignatures(
workspaceDirs: string[],
offset: number = 0,
batchSize: number = 100,
uriOffset: number = 0,
uriBatchSize: number = 100,
snippetOffset: number = 0,
snippetBatchSize: number = 100,
): Promise<{
groupedByUri: { [path: string]: string[] };
hasMore: boolean;
hasMoreSnippets: boolean;
hasMoreUris: boolean;
}> {
const db = await SqliteDb.get();
await CodeSnippetsCodebaseIndex._createTables(db);
const likePatterns = workspaceDirs.map((dir) =>
truncateSqliteLikePattern(`${dir}%`),
);
const endIndex = uriOffset + uriBatchSize;
const uriBatch = workspaceDirs.slice(uriOffset, endIndex);
const likePatterns = uriBatch.map((dir) => `${dir}%`);
const placeholders = likePatterns.map(() => "?").join(" OR path LIKE ");
const query = `
@ -420,7 +420,11 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
LIMIT ? OFFSET ?
`;
const rows = await db.all(query, [...likePatterns, batchSize, offset]);
const rows = await db.all(query, [
...likePatterns,
snippetBatchSize,
snippetOffset,
]);
const groupedByUri: { [path: string]: string[] } = {};
@ -431,8 +435,9 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
groupedByUri[path].push(signature);
}
const hasMore = rows.length === batchSize;
const hasMoreUris = endIndex < workspaceDirs.length;
const hasMoreSnippets = rows.length === snippetBatchSize;
return { groupedByUri, hasMore };
return { groupedByUri, hasMoreUris, hasMoreSnippets };
}
}

View file

@ -14,12 +14,12 @@ import {
} from "../test/testDir.js";
import { getIndexSqlitePath } from "../util/paths.js";
import { localPathToUri } from "../util/pathToUri.js";
import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
import { CodebaseIndex } from "./types.js";
import { walkDir } from "./walkDir.js";
import { localPathToUri } from "../util/pathToUri.js";
import { walkDir, walkDirCache } from "./walkDir.js";
jest.useFakeTimers();
@ -87,6 +87,10 @@ describe("CodebaseIndexer", () => {
tearDownTestDir();
});
afterEach(() => {
walkDirCache.invalidate();
});
async function refreshIndex() {
const abortController = new AbortController();
const abortSignal = abortController.signal;

View file

@ -5,8 +5,8 @@ import { IContinueServerClient } from "../continueServer/interface.js";
import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
@ -15,6 +15,7 @@ import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import {
CodebaseIndex,
IndexResultType,
PathAndCacheKey,
RefreshIndexResults,
} from "./types.js";
import { walkDirAsync } from "./walkDir.js";
@ -80,24 +81,65 @@ export class CodebaseIndexer {
return [];
}
const indexes = [
const embeddingsModel = config.selectedModelByRole.embed;
if (!embeddingsModel) {
return [];
}
const indexes: CodebaseIndex[] = [
new ChunkCodebaseIndex(
this.ide.readFile.bind(this.ide),
this.continueServerClient,
config.embeddingsProvider.maxEmbeddingChunkSize,
embeddingsModel.maxEmbeddingChunkSize,
), // Chunking must come first
new LanceDbIndex(
config.embeddingsProvider,
this.ide.readFile.bind(this.ide),
this.continueServerClient,
),
new FullTextSearchCodebaseIndex(),
new CodeSnippetsCodebaseIndex(this.ide),
];
const lanceDbIndex = await LanceDbIndex.create(
embeddingsModel,
this.ide.readFile.bind(this.ide),
);
if (lanceDbIndex) {
indexes.push(lanceDbIndex);
}
indexes.push(
new FullTextSearchCodebaseIndex(),
new CodeSnippetsCodebaseIndex(this.ide),
);
return indexes;
}
private totalIndexOps(results: RefreshIndexResults): number {
return (
results.compute.length +
results.del.length +
results.addTag.length +
results.removeTag.length
);
}
private singleFileIndexOps(
results: RefreshIndexResults,
lastUpdated: PathAndCacheKey[],
filePath: string,
): [RefreshIndexResults, PathAndCacheKey[]] {
const filterFn = (item: PathAndCacheKey) => item.path === filePath;
const compute = results.compute.filter(filterFn);
const del = results.del.filter(filterFn);
const addTag = results.addTag.filter(filterFn);
const removeTag = results.removeTag.filter(filterFn);
const newResults = {
compute,
del,
addTag,
removeTag,
};
const newLastUpdated = lastUpdated.filter(filterFn);
return [newResults, newLastUpdated];
}
public async refreshFile(
file: string,
workspaceDirs: string[],
@ -115,26 +157,28 @@ export class CodebaseIndexer {
const repoName = await this.ide.getRepoName(foundInDir);
const indexesToBuild = await this.getIndexesToBuild();
const stats = await this.ide.getFileStats([file]);
const filePath = Object.keys(stats)[0];
for (const index of indexesToBuild) {
const tag = {
directory: foundInDir,
branch,
artifactId: index.artifactId,
};
const [results, lastUpdated, markComplete] =
const [fullResults, fullLastUpdated, markComplete] =
await getComputeDeleteAddRemove(
tag,
{ ...stats },
(filepath) => this.ide.readFile(filepath),
repoName,
);
// since this is only a single file update / save we do not want to actualy remove anything, we just want to recompute for our single file
results.removeTag = [];
results.addTag = [];
results.del = [];
const [results, lastUpdated] = this.singleFileIndexOps(
fullResults,
fullLastUpdated,
filePath,
);
// Don't update if nothing to update. Some of the indices might do unnecessary setup work
if (results.compute.length === 0) {
if (this.totalIndexOps(results) + lastUpdated.length === 0) {
continue;
}
@ -237,7 +281,9 @@ export class CodebaseIndexer {
status: "indexing",
};
const directoryFiles = [];
for await (const p of walkDirAsync(directory, this.ide)) {
for await (const p of walkDirAsync(directory, this.ide, {
source: "codebase indexing: refresh dirs",
})) {
directoryFiles.push(p);
if (abortSignal.aborted) {
yield {
@ -415,11 +461,7 @@ export class CodebaseIndexer {
(filepath) => this.ide.readFile(filepath),
repoName,
);
const totalOps =
results.compute.length +
results.del.length +
results.addTag.length +
results.removeTag.length;
const totalOps = this.totalIndexOps(results);
let completedOps = 0;
// Don't update if nothing to update. Some of the indices might do unnecessary setup work

View file

@ -97,13 +97,15 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
// Delete
for (const item of results.del) {
await db.run(`
DELETE FROM fts WHERE rowid IN (
SELECT id FROM fts_metadata WHERE path = ? AND cacheKey = ?
)
`,[item.path, item.cacheKey]);
await db.run("DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [
item.path,
item.cacheKey,
]);
await db.run("DELETE FROM fts WHERE path = ?", [item.path]);
await markComplete([item], IndexResultType.Delete);
}
}

View file

@ -3,15 +3,14 @@ import lance from "vectordb";
import { testConfigHandler, testIde } from "../test/fixtures";
import { getLanceDbPath } from "../util/paths";
import {
mockPathAndCacheKey,
mockTag,
testContinueServerClient,
updateIndexAndAwaitGenerator,
} from "./test/indexing";
import { LanceDbIndex } from "./LanceDbIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import {
mockPathAndCacheKey,
mockTag,
updateIndexAndAwaitGenerator,
} from "./test/indexing";
import { IndexResultType } from "./types";
jest.useFakeTimers();
@ -30,12 +29,14 @@ describe.skip("ChunkCodebaseIndex", () => {
if (!mockConfig) {
throw new Error("Failed to load config");
}
if (!mockConfig.selectedModelByRole.embed) {
throw new Error("No embeddings model selected");
}
index = new LanceDbIndex(
mockConfig.embeddingsProvider,
index = (await LanceDbIndex.create(
mockConfig.selectedModelByRole.embed,
testIde.readFile.bind(testIde),
testContinueServerClient,
);
))!;
sqliteDb = await SqliteDb.get();
lanceDb = await lance.connect(getLanceDbPath());

View file

@ -1,20 +1,19 @@
// NOTE: vectordb requirement must be listed in extensions/vscode to avoid error
import { RunResult } from "sqlite3";
import { v4 as uuidv4 } from "uuid";
import lance, { Table } from "vectordb";
import { IContinueServerClient } from "../continueServer/interface.js";
import { isSupportedLanceDbCpuTargetForLinux } from "../config/util";
import {
BranchAndDir,
Chunk,
ILLM,
IndexTag,
IndexingProgressUpdate,
} from "../index.js";
import { getLanceDbPath, migrate } from "../util/paths.js";
} from "../index";
import { getLanceDbPath, migrate } from "../util/paths";
import { getUriPathBasename } from "../util/uri";
import { chunkDocument, shouldChunk } from "./chunk/chunk.js";
import { basicChunker } from "./chunk/basic.js";
import { chunkDocument, shouldChunk } from "./chunk/chunk.js";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js";
import {
CodebaseIndex,
@ -22,10 +21,10 @@ import {
MarkCompleteCallback,
PathAndCacheKey,
RefreshIndexResults,
} from "./types.js";
import { getUriPathBasename } from "../util/uri.js";
} from "./types";
import type * as LanceType from "vectordb";
// LanceDB converts to lowercase, so names must all be lowercase
interface LanceDbRow {
uuid: string;
path: string;
@ -39,16 +38,47 @@ type ItemWithChunks = { item: PathAndCacheKey; chunks: Chunk[] };
type ChunkMap = Map<string, ItemWithChunks>;
export class LanceDbIndex implements CodebaseIndex {
private static lance: typeof LanceType | null = null;
relativeExpectedTime: number = 13;
get artifactId(): string {
return `vectordb::${this.embeddingsProvider.embeddingId}`;
return `vectordb::${this.embeddingsProvider?.embeddingId}`;
}
constructor(
/**
* Factory method for creating LanceDbIndex instances.
*
* We dynamically import LanceDB only when supported to avoid native module loading errors
* on incompatible platforms. LanceDB has CPU-specific native dependencies that can crash
* the application if loaded on unsupported architectures.
*
* See isSupportedLanceDbCpuTargetForLinux() for platform compatibility details.
*/
static async create(
embeddingsProvider: ILLM,
readFile: (filepath: string) => Promise<string>,
): Promise<LanceDbIndex | null> {
if (!isSupportedLanceDbCpuTargetForLinux()) {
return null;
}
try {
this.lance = await import("vectordb");
return new LanceDbIndex(embeddingsProvider, readFile);
} catch (err) {
console.error("Failed to load LanceDB:", err);
return null;
}
}
private constructor(
private readonly embeddingsProvider: ILLM,
private readonly readFile: (filepath: string) => Promise<string>,
private readonly continueServerClient?: IContinueServerClient,
) {}
) {
if (!LanceDbIndex.lance) {
throw new Error("LanceDB not initialized");
}
}
tableNameForTag(tag: IndexTag) {
return tagToString(tag).replace(/[^\w-_.]/g, "");
@ -98,12 +128,10 @@ export class LanceDbIndex implements CodebaseIndex {
);
const embeddings = await this.getEmbeddings(allChunks);
// Remove undefined embeddings and their corresponding chunks
for (let i = embeddings.length - 1; i >= 0; i--) {
if (embeddings[i] === undefined) {
const chunk = allChunks[i];
const chunks = chunkMap.get(chunk.filepath)?.chunks;
if (chunks) {
const index = chunks.findIndex((c) => c === chunk);
if (index !== -1) {
@ -143,6 +171,9 @@ export class LanceDbIndex implements CodebaseIndex {
item: PathAndCacheKey,
content: string,
): Promise<Chunk[]> {
if (!this.embeddingsProvider) {
return [];
}
const chunks: Chunk[] = [];
const chunkParams = {
@ -164,6 +195,9 @@ export class LanceDbIndex implements CodebaseIndex {
}
private async getEmbeddings(chunks: Chunk[]): Promise<number[][]> {
if (!this.embeddingsProvider) {
return [];
}
try {
return await this.embeddingsProvider.embed(chunks.map((c) => c.content));
} catch (err) {
@ -205,6 +239,7 @@ export class LanceDbIndex implements CodebaseIndex {
markComplete: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate> {
const lance = LanceDbIndex.lance!;
const sqliteDb = await SqliteDb.get();
await this.createSqliteCacheTable(sqliteDb);
@ -212,15 +247,13 @@ export class LanceDbIndex implements CodebaseIndex {
const lanceDb = await lance.connect(getLanceDbPath());
const existingLanceTables = await lanceDb.tableNames();
let lanceTable: Table<number[]> | undefined = undefined;
let lanceTable: LanceType.Table<number[]> | undefined = undefined;
let needToCreateLanceTable = !existingLanceTables.includes(lanceTableName);
// Compute
const addComputedLanceDbRows = async (
pathAndCacheKeys: PathAndCacheKey[],
computedRows: LanceDbRow[],
) => {
// Create table if needed, add computed rows
if (lanceTable) {
if (computedRows.length > 0) {
await lanceTable.add(computedRows);
@ -236,68 +269,9 @@ export class LanceDbIndex implements CodebaseIndex {
needToCreateLanceTable = false;
}
// Mark item complete
await markComplete(pathAndCacheKeys, IndexResultType.Compute);
};
// Check remote cache
if (this.continueServerClient?.connected) {
try {
const keys = results.compute.map(({ cacheKey }) => cacheKey);
const resp = await this.continueServerClient.getFromIndexCache(
keys,
"embeddings",
repoName,
);
for (const [cacheKey, chunks] of Object.entries(resp.files)) {
// Get path for cacheKey
const path = results.compute.find(
(item) => item.cacheKey === cacheKey,
)?.path;
if (!path) {
console.warn(
"Continue server sent a cacheKey that wasn't requested",
cacheKey,
);
continue;
}
// Build LanceDbRow objects
const rows: LanceDbRow[] = [];
for (const chunk of chunks) {
const row = {
path,
cachekey: cacheKey,
uuid: uuidv4(),
vector: chunk.vector,
};
rows.push(row);
await sqliteDb.run(
"INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
row.uuid,
row.cachekey,
row.path,
this.artifactId,
JSON.stringify(row.vector),
chunk.startLine,
chunk.endLine,
chunk.contents,
);
}
await addComputedLanceDbRows([{ cacheKey, path }], rows);
}
// Remove items that don't need to be recomputed
results.compute = results.compute.filter(
(item) => !resp.files[item.cacheKey],
);
} catch (e) {
console.log("Error checking remote cache: ", e);
}
}
yield {
progress: 0,
desc: `Computing embeddings for ${
@ -311,12 +285,10 @@ export class LanceDbIndex implements CodebaseIndex {
await addComputedLanceDbRows(results.compute, dbRows);
let accumulatedProgress = 0;
// Add tag - retrieve the computed info from lance sqlite cache
for (const { path, cacheKey } of results.addTag) {
const stmt = await sqliteDb.prepare(
"SELECT * FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?",
"SELECT * FROM lance_db_cache WHERE cacheKey = ? AND artifact_id = ?",
cacheKey,
path,
this.artifactId,
);
const cachedItems = await stmt.all();
@ -355,7 +327,6 @@ export class LanceDbIndex implements CodebaseIndex {
};
}
// Delete or remove tag - remove from lance table)
if (!needToCreateLanceTable) {
const toDel = [...results.removeTag, ...results.del];
@ -364,7 +335,6 @@ export class LanceDbIndex implements CodebaseIndex {
}
for (const { path, cacheKey } of toDel) {
// This is where the aforementioned lowercase conversion problem shows
await lanceTable.delete(
`cachekey = '${cacheKey}' AND path = '${path}'`,
);
@ -380,7 +350,6 @@ export class LanceDbIndex implements CodebaseIndex {
await markComplete(results.removeTag, IndexResultType.RemoveTag);
// Delete - also remove from sqlite cache
for (const { path, cacheKey } of results.del) {
await sqliteDb.run(
"DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ? AND artifact_id = ?",
@ -410,7 +379,7 @@ export class LanceDbIndex implements CodebaseIndex {
n: number,
directory: string | undefined,
vector: number[],
db: any, /// lancedb.Connection
db: any,
): Promise<LanceDbRow[]> {
const tableName = this.tableNameForTag(tag);
const tableNames = await db.tableNames();
@ -422,7 +391,6 @@ export class LanceDbIndex implements CodebaseIndex {
const table = await db.openTable(tableName);
let query = table.search(vector);
if (directory) {
// seems like lancedb is only post-filtering, so have to return a bunch of results and slice after
query = query.where(`path LIKE '${directory}%'`).limit(300);
} else {
query = query.limit(n);
@ -437,6 +405,12 @@ export class LanceDbIndex implements CodebaseIndex {
tags: BranchAndDir[],
filterDirectory: string | undefined,
): Promise<Chunk[]> {
const lance = LanceDbIndex.lance!;
if (!this.embeddingsProvider) {
return [];
}
// Use just the first chunk of the user query in case it is too long
const chunks = [];
for await (const chunk of basicChunker(
query,

View file

@ -8,6 +8,7 @@ import Gemini from "../llm/llms/Gemini.js";
import HuggingFaceTEIEmbeddingsProvider from "../llm/llms/HuggingFaceTEI.js";
import LMStudio from "../llm/llms/LMStudio.js";
import Mistral from "../llm/llms/Mistral.js";
import NCompass from "../llm/llms/NCompass.js";
import Nebius from "../llm/llms/Nebius.js";
import Nvidia from "../llm/llms/Nvidia.js";
import Ollama from "../llm/llms/Ollama.js";
@ -39,6 +40,7 @@ export const allEmbeddingsProviders: Record<
gemini: Gemini,
"continue-proxy": ContinueProxy,
deepinfra: DeepInfra,
ncompass: NCompass,
nvidia: Nvidia,
voyage: Voyage,
mistral: Mistral,

View file

@ -80,9 +80,9 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
`
INSERT INTO chunk_tags (chunkId, tag)
SELECT id, ? FROM chunks
WHERE cacheKey = ? AND path = ?
WHERE cacheKey = ?
`,
[tagString, item.cacheKey, item.path],
[tagString, item.cacheKey],
);
await markComplete([item], IndexResultType.AddTag);
accumulatedProgress += 1 / results.addTag.length / 4;
@ -158,7 +158,8 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
id INTEGER PRIMARY KEY AUTOINCREMENT,
tag TEXT NOT NULL,
chunkId INTEGER NOT NULL,
FOREIGN KEY (chunkId) REFERENCES chunks (id)
FOREIGN KEY (chunkId) REFERENCES chunks (id),
UNIQUE (tag, chunkId)
)`);
}

View file

@ -2,7 +2,6 @@
* @jest-environment jsdom
*/
import { ConfigHandler } from "../../config/ConfigHandler.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { SiteIndexingConfig } from "../../index.js";
import FileSystemIde from "../../util/filesystem.js";
import { editConfigJson } from "../../util/paths.js";
@ -50,16 +49,7 @@ describe.skip("DocsService Integration Tests", () => {
ide,
ideSettingsPromise,
async () => {},
new ControlPlaneClient(
Promise.resolve({
accessToken: "",
account: {
id: "",
label: "",
},
}),
ideSettingsPromise,
),
Promise.resolve(undefined),
);
docsService = DocsService.createSingleton(configHandler, ide);

View file

@ -1,6 +1,6 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { open, type Database } from "sqlite";
import sqlite3 from "sqlite3";
import lancedb, { Connection } from "vectordb";
import {
Chunk,
@ -13,12 +13,16 @@ import {
SiteIndexingConfig,
} from "../..";
import { ConfigHandler } from "../../config/ConfigHandler";
import { addContextProvider } from "../../config/util";
import {
addContextProvider,
isSupportedLanceDbCpuTargetForLinux,
} from "../../config/util";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol";
import { IMessenger } from "../../protocol/messenger";
import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon";
import { GlobalContext } from "../../util/GlobalContext";
import {
editConfigJson,
getDocsSqlitePath,
@ -26,8 +30,6 @@ import {
} from "../../util/paths";
import { Telemetry } from "../../util/posthog";
import { ConfigResult } from "@continuedev/config-yaml";
import { GlobalContext } from "../../util/GlobalContext";
import {
ArticleWithChunks,
htmlPageToArticleWithChunks,
@ -43,6 +45,8 @@ import {
} from "./preIndexed";
import preIndexedDocs from "./preIndexedDocs";
import type * as LanceType from "vectordb";
// Purposefully lowercase because lancedb converts
export interface LanceDbDocsRow {
title: string;
@ -81,6 +85,7 @@ export type AddParams = {
- add/index one
*/
export default class DocsService {
private static lance: typeof LanceType | null = null;
static lanceTableName = "docs";
static sqlitebTableName = "docs";
@ -112,6 +117,22 @@ export default class DocsService {
this.githubToken = token;
}
private async initLanceDb() {
if (!isSupportedLanceDbCpuTargetForLinux()) {
return null;
}
try {
if (!DocsService.lance) {
DocsService.lance = await import("vectordb");
}
return DocsService.lance;
} catch (err) {
console.error("Failed to load LanceDB:", err);
return null;
}
}
// Singleton pattern: only one service globally
private static instance?: DocsService;
static createSingleton(
@ -161,16 +182,22 @@ export default class DocsService {
return;
}
const sharedStatus = {
type: "docs" as IndexingStatus["type"],
const sharedStatus: Omit<
IndexingStatus,
"progress" | "description" | "status"
> = {
type: "docs",
id: doc.startUrl,
embeddingsProviderId: this.config.embeddingsProvider.embeddingId,
isReindexing: false,
title: doc.title,
debugInfo: `max depth: ${doc.maxDepth}`,
icon: doc.faviconUrl,
url: doc.startUrl,
};
if (this.config.selectedModelByRole.embed) {
sharedStatus.embeddingsProviderId =
this.config.selectedModelByRole.embed.embeddingId;
}
const indexedStatus: IndexingStatus = metadata.find(
(meta) => meta.startUrl === doc.startUrl,
)
@ -214,7 +241,9 @@ export default class DocsService {
}
// Handle embeddings provider change mid-indexing
if (this.config.embeddingsProvider.embeddingId !== startedWithEmbedder) {
if (
this.config.selectedModelByRole.embed?.embeddingId !== startedWithEmbedder
) {
this.abort(startUrl);
return true;
}
@ -234,14 +263,6 @@ export default class DocsService {
return true;
}
async isUsingUnsupportedPreIndexedEmbeddingsProvider() {
const isPreIndexedDocsProvider =
this.config.embeddingsProvider.embeddingId ===
DocsService.preIndexedDocsEmbeddingsProvider.embeddingId;
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
return isPreIndexedDocsProvider && !canUsePreindexedDocs;
}
// Determines if using preIndexed and returns proper embeddings provider
async getEmbeddingsProvider(startUrl: string) {
// Conditions for using a pre-indexed doc
@ -262,7 +283,7 @@ export default class DocsService {
}
}
return {
provider: this.config.embeddingsProvider,
provider: this.config.selectedModelByRole.embed,
isPreindexed: false,
};
}
@ -282,9 +303,7 @@ export default class DocsService {
// Skip docs indexing if not supported
// No warning message here because would show on ANY config update
const unsupported =
await this.isUsingUnsupportedPreIndexedEmbeddingsProvider();
if (unsupported) {
if (!this.config.selectedModelByRole.embed) {
return;
}
@ -323,18 +342,21 @@ export default class DocsService {
// Returns true if startUrl has been indexed with current embeddingsProvider
async hasMetadata(startUrl: string): Promise<boolean> {
if (!this.config.selectedModelByRole.embed) {
return false;
}
const db = await this.getOrCreateSqliteDb();
const title = await db.get(
`SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
startUrl,
this.config.embeddingsProvider.embeddingId,
this.config.selectedModelByRole.embed.embeddingId,
);
return !!title;
}
async listMetadata() {
const embeddingsProvider = this.config.embeddingsProvider;
const embeddingsProvider = this.config.selectedModelByRole.embed;
if (!embeddingsProvider) {
return [];
}
@ -376,6 +398,11 @@ export default class DocsService {
console.warn("Attempted to indexAndAdd pre-indexed doc");
return;
}
if (!provider) {
console.warn("@docs indexAndAdd: no embeddings provider found");
return;
}
const startedWithEmbedder = provider.embeddingId;
// Check if doc has been successfully indexed with the given embedder
@ -716,21 +743,18 @@ export default class DocsService {
startUrl: string,
nRetrieve: number,
) {
if (await this.isUsingUnsupportedPreIndexedEmbeddingsProvider()) {
await this.ide.showToast(
"error",
`${DocsService.preIndexedDocsEmbeddingsProvider.embeddingId} is configured as ` +
"the embeddings provider, but it cannot be used with JetBrains. " + // TODO "with this IDE"
"Please select a different embeddings provider to use the '@docs' " +
"context provider.",
);
return [];
}
const { isPreindexed, provider } =
await this.getEmbeddingsProvider(startUrl);
if (!provider) {
void this.ide.showToast(
"error",
"Set up an embeddings model to use the @docs context provider. See: " +
"https://docs.continue.dev/customize/model-roles/embeddings",
);
return [];
}
if (isPreindexed) {
void Telemetry.capture("docs_pre_indexed_doc_used", {
doc: preIndexedDocs[startUrl]!["title"],
@ -761,8 +785,10 @@ export default class DocsService {
try {
const { isPreindexed, provider } =
await this.getEmbeddingsProvider(startUrl);
const preIndexedDoc = preIndexedDocs[startUrl];
const isPreIndexedDoc = !!preIndexedDoc;
if (!provider) {
throw new Error("No embeddings model set");
}
const result = await db.get(
`SELECT startUrl, title, favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
@ -793,7 +819,7 @@ export default class DocsService {
config: siteIndexingConfig,
indexingStatus: this.statuses.get(startUrl),
chunks: rows.map(this.lanceDBRowToChunk),
isPreIndexedDoc,
isPreIndexedDoc: isPreindexed,
};
} catch (e) {
console.warn("Error getting details", e);
@ -867,7 +893,7 @@ export default class DocsService {
}
async getFavicon(startUrl: string) {
if (!this.config.embeddingsProvider) {
if (!this.config.selectedModelByRole.embed) {
console.warn(
"Attempting to get favicon without embeddings provider specified",
);
@ -877,7 +903,7 @@ export default class DocsService {
const result = await db.get(
`SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
startUrl,
this.config.embeddingsProvider.embeddingId,
this.config.selectedModelByRole.embed.embeddingId,
);
if (!result) {
@ -941,7 +967,7 @@ export default class DocsService {
type: "docs",
id: doc.startUrl,
embeddingsProviderId:
this.config.embeddingsProvider.embeddingId,
this.config.selectedModelByRole.embed?.embeddingId,
isReindexing: false,
title: doc.title,
debugInfo: "Config sync: not changed",
@ -983,7 +1009,7 @@ export default class DocsService {
// Lance DB Initialization
private async createLanceDocsTable(
connection: Connection,
connection: LanceType.Connection,
initializationVector: number[],
tableName: string,
) {
@ -1030,9 +1056,21 @@ export default class DocsService {
initializationVector: number[];
startUrl: string;
}) {
const conn = await lancedb.connect(getLanceDbPath());
const lance = await this.initLanceDb();
if (!lance) {
throw new Error("LanceDB not available on this platform");
}
const conn = await lance.connect(getLanceDbPath());
const tableNames = await conn.tableNames();
const { provider } = await this.getEmbeddingsProvider(startUrl);
if (!provider) {
throw new Error(
"Could not retrieve @docs Lance Table: no embeddings provider specified",
);
}
const tableNameFromEmbeddingsProvider =
await this.getLanceTableName(provider);
@ -1089,13 +1127,19 @@ export default class DocsService {
siteIndexingConfig: { title, startUrl },
favicon,
}: AddParams) {
if (!this.config.selectedModelByRole.embed) {
console.warn(
`Attempting to add metadata for ${startUrl} without embeddings provider specified`,
);
return;
}
const db = await this.getOrCreateSqliteDb();
await db.run(
`INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon, embeddingsProviderId) VALUES (?, ?, ?, ?)`,
title,
startUrl,
favicon,
this.config.embeddingsProvider.embeddingId,
this.config.selectedModelByRole.embed.embeddingId,
);
}
@ -1139,15 +1183,20 @@ export default class DocsService {
// Delete methods
private async deleteEmbeddingsFromLance(startUrl: string) {
const lance = await this.initLanceDb();
if (!lance) {
return;
}
for (const tableName of this.lanceTableNamesSet) {
const conn = await lancedb.connect(getLanceDbPath());
const conn = await lance.connect(getLanceDbPath());
const table = await conn.openTable(tableName);
await table.delete(`starturl = '${startUrl}'`);
}
}
private async deleteMetadataFromSqlite(startUrl: string) {
if (!this.config.embeddingsProvider) {
if (!this.config.selectedModelByRole.embed) {
console.warn(
`Attempting to delete metadata for ${startUrl} without embeddings provider specified`,
);
@ -1158,7 +1207,7 @@ export default class DocsService {
await db.run(
`DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
startUrl,
this.config.embeddingsProvider.embeddingId,
this.config.selectedModelByRole.embed.embeddingId,
);
}

View file

@ -139,24 +139,35 @@ export async function htmlPageToArticleWithChunks(
return undefined;
}
const title = readability.title || subpath;
const titles = Array.from(dom.window.document.querySelectorAll("h2"));
const article_components = titles.map((titleElement) => {
const title = titleElement.textContent || "";
let body = "";
let nextSibling = titleElement.nextElementSibling;
while (nextSibling && nextSibling.tagName !== "H2") {
body += nextSibling.textContent || "";
nextSibling = nextSibling.nextElementSibling;
}
const article_components =
titles.length > 0
? titles.map((titleElement) => {
const title = titleElement.textContent || "";
let body = "";
let nextSibling = titleElement.nextElementSibling;
return { title, body };
});
while (nextSibling && nextSibling.tagName !== "H2") {
body += nextSibling.textContent || "";
nextSibling = nextSibling.nextElementSibling;
}
return { title, body };
})
: [
{
title: title,
body: readability.textContent,
},
];
const article = {
url,
subpath,
title: readability.title,
title: title,
article_components,
};
return {

View file

@ -1,5 +1,5 @@
import { type Database } from "sqlite";
import { Table } from "vectordb";
import { type Table } from "vectordb";
import { editConfigJson, migrate } from "../../util/paths.js";

View file

@ -358,6 +358,11 @@ const preIndexedDocs: Record<
startUrl: "https://angular.dev/",
rootUrl: "https://angular.dev/",
},
"https://docs.djangoproject.com/": {
title: "Django",
startUrl: "https://docs.djangoproject.com/",
rootUrl: "https://docs.djangoproject.com/",
}
};
export default preIndexedDocs;

View file

@ -114,6 +114,10 @@ export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS);
export const DEFAULT_IGNORE =
DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n");
export const defaultIgnoreFileAndDir = ignore()
.add(defaultIgnoreFile)
.add(defaultIgnoreDir);
export function gitIgArrayFromFile(file: string) {
return file
.split(/\r?\n/) // Split on new line

View file

@ -157,32 +157,64 @@ async function getAddRemoveForTag(
const remove: PathAndCacheKey[] = [];
const updateLastUpdated: PathAndCacheKey[] = [];
for (const item of saved) {
const { lastUpdated, ...pathAndCacheKey } = item;
// First, group items by path and find latest timestamp for each
const pathGroups = new Map<string, {
latest: { lastUpdated: number, cacheKey: string },
allVersions: Array<{ cacheKey: string }>
}>();
if (files[item.path] === undefined) {
// Was indexed, but no longer exists. Remove
remove.push(pathAndCacheKey);
for (const item of saved) {
const { lastUpdated, path, cacheKey } = item;
if (!pathGroups.has(path)) {
pathGroups.set(path, {
latest: { lastUpdated, cacheKey },
allVersions: [{ cacheKey }]
});
} else {
const group = pathGroups.get(path)!;
group.allVersions.push({ cacheKey });
if (lastUpdated > group.latest.lastUpdated) {
group.latest = { lastUpdated, cacheKey };
}
}
}
// Now process each unique path
for (const [path, group] of pathGroups) {
if (files[path] === undefined) {
// Was indexed, but no longer exists. Remove all versions
for (const version of group.allVersions) {
remove.push({ path, cacheKey: version.cacheKey });
}
} else {
// Exists in old and new, so determine whether it was updated
if (lastUpdated < files[item.path].lastModified) {
if (group.latest.lastUpdated < files[path].lastModified) {
// Change was made after last update
const newHash = calculateHash(await readFile(pathAndCacheKey.path));
if (pathAndCacheKey.cacheKey !== newHash) {
const newHash = calculateHash(await readFile(path));
if (group.latest.cacheKey !== newHash) {
updateNewVersion.push({
path: pathAndCacheKey.path,
path,
cacheKey: newHash,
});
updateOldVersion.push(pathAndCacheKey);
for (const version of group.allVersions) {
updateOldVersion.push({ path, cacheKey: version.cacheKey });
}
} else {
updateLastUpdated.push(pathAndCacheKey);
// File contents did not change
updateLastUpdated.push({ path, cacheKey: group.latest.cacheKey });
for (const version of group.allVersions) {
if (version.cacheKey !== group.latest.cacheKey) {
updateOldVersion.push({ path, cacheKey: version.cacheKey });
}
}
}
} else {
// Already updated, do nothing
}
// Remove so we can check leftovers afterward
delete files[item.path];
// Remove path, so that only newly created paths remain
delete files[path];
}
}

View file

@ -0,0 +1,167 @@
// Generated by continue
import { testIde } from "../test/fixtures";
import {
TEST_DIR,
addToTestDir,
setUpTestDir,
tearDownTestDir,
} from "../test/testDir";
import { shouldIgnore } from "./shouldIgnore";
// Test for the shouldIgnore function
describe("shouldIgnore", () => {
beforeEach(() => {
setUpTestDir();
});
afterEach(() => {
tearDownTestDir();
});
test("should return true if a file is ignored by .gitignore", async () => {
addToTestDir([
["ignored-file.txt", "content"],
[".gitignore", "ignored-file.txt"],
]);
const result = await shouldIgnore(TEST_DIR + "/ignored-file.txt", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
});
test("should return true if a folder is ignored by .continueignore", async () => {
addToTestDir([
["ignored-folder/file.txt", "content"],
[".continueignore", "ignored-folder/"],
]);
const result = await shouldIgnore(
TEST_DIR + "/ignored-folder/file.txt",
testIde,
[TEST_DIR],
);
expect(result).toBe(true);
});
test("should return false if a file is not ignored", async () => {
addToTestDir([["kept-file.txt", "contents"]]);
const result = await shouldIgnore(TEST_DIR + "/kept-file.txt", testIde, [
TEST_DIR,
]);
expect(result).toBe(false);
});
test("should return true if a file is ignored by .gitignore with spaces in file name", async () => {
addToTestDir([
["ignored file.txt", "content"],
[".gitignore", "ignored file.txt"],
]);
const result = await shouldIgnore(TEST_DIR + "/ignored file.txt", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
});
test("should return true if a .continueignore override ignores file", async () => {
addToTestDir([
["override-file.txt", "content"],
[".gitignore", "override-file.txt"],
[".continueignore", "!override-file.txt"],
]);
const result = await shouldIgnore(
TEST_DIR + "/override-file.txt",
testIde,
[TEST_DIR],
);
expect(result).toBe(false);
});
test("should return true for deeply nested file ignored by ignore files at multiple levels", async () => {
addToTestDir([
["level1/level2/level3/ignored-file.txt", "content"],
["level1/.gitignore", "level2/"],
["level1/level2/.continueignore", "level3/"],
]);
const result = await shouldIgnore(
TEST_DIR + "/level1/level2/level3/ignored-file.txt",
testIde,
[TEST_DIR],
);
expect(result).toBe(true);
});
test("should return false if a file with spaces is not ignored", async () => {
addToTestDir([["kept file.txt", "contents"]]);
const result = await shouldIgnore(TEST_DIR + "/kept file.txt", testIde, [
TEST_DIR,
]);
expect(result).toBe(false);
});
test("should handle multiple levels of directories with some files ignored", async () => {
addToTestDir([
["nested/dir1/.gitignore", "ignored.txt"],
["nested/dir1/ignored.txt", "content"],
["nested/dir2/kept.txt", "content"],
]);
const ignoredResult = await shouldIgnore(
TEST_DIR + "/nested/dir1/ignored.txt",
testIde,
[TEST_DIR],
);
expect(ignoredResult).toBe(true);
const keptResult = await shouldIgnore(
TEST_DIR + "/nested/dir2/kept.txt",
testIde,
[TEST_DIR],
);
expect(keptResult).toBe(false);
});
test("should respect default file and folder ignores top level", async () => {
addToTestDir([
[".env", "contents"],
["go.sum", "contents"],
".idea/",
[".idea/test.xml", "contents"],
]);
let result = await shouldIgnore(TEST_DIR + "/.env", testIde, [TEST_DIR]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/go.sum", testIde, [TEST_DIR]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/.idea", testIde, [TEST_DIR]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/.idea/test.xml", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
});
test("should respect default file and folder ignores at nested level", async () => {
addToTestDir([
"nested/.idea/test.xml",
["nested/.env", "contents"],
["nested/go.sum", "contents"],
]);
let result = await shouldIgnore(TEST_DIR + "/nested/.idea", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/nested/.idea/test.xml", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/nested/.env", testIde, [TEST_DIR]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/nested/go.sum", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
});
});

View file

@ -0,0 +1,73 @@
import ignore from "ignore";
import type { FileType, IDE } from "../";
import { findUriInDirs, getUriPathBasename } from "../util/uri";
import { defaultIgnoreFileAndDir, getGlobalContinueIgArray } from "./ignore";
import { getIgnoreContext } from "./walkDir";
/*
Process:
1. Check global/default ignores
2. Walk UP tree from file, checking ignores at each level
TODO there might be issues with symlinks here
*/
export async function shouldIgnore(
fileUri: string,
ide: IDE,
rootDirCandidates?: string[],
): Promise<boolean> {
const rootDirUris = rootDirCandidates ?? (await ide.getWorkspaceDirs());
const { foundInDir: rootDir, uri } = findUriInDirs(fileUri, rootDirUris);
if (!rootDir) {
return true;
}
const defaultAndGlobalIgnores = ignore()
.add(defaultIgnoreFileAndDir)
.add(getGlobalContinueIgArray());
let currentDir = uri;
let directParent = true;
let fileType = 1 as FileType.File as FileType;
while (currentDir !== rootDir) {
// Go to parent dir of file
const splitUri = currentDir.split("/");
splitUri.pop();
currentDir = splitUri.join("/");
// Get all files in the dir
const dirEntries = await ide.listDir(currentDir);
// Check if the file is a symbolic link, ignore if so
if (directParent) {
directParent = false;
const baseName = getUriPathBasename(fileUri);
const entry = dirEntries.find(([name, _]) => name === baseName);
if (entry) {
fileType = entry[1];
if (fileType === (64 as FileType.SymbolicLink)) {
return true;
}
}
}
const ignoreContext = await getIgnoreContext(
currentDir,
dirEntries,
ide,
defaultAndGlobalIgnores,
);
let relativePath = uri.substring(currentDir.length + 1);
if (fileType === (2 as FileType.Directory)) {
relativePath += "/";
}
if (ignoreContext.ignores(relativePath)) {
return true;
}
}
return false;
}

View file

@ -1,14 +1,19 @@
// Generated by continue
import { testIde } from "../test/fixtures";
import {
setUpTestDir,
tearDownTestDir,
addToTestDir,
TEST_DIR_PATH,
} from "../test/testDir";
import { walkDir, walkDirAsync, walkDirs } from "../indexing/walkDir";
import fs from "fs";
import path from "path";
import {
walkDir,
walkDirAsync,
walkDirCache,
walkDirs,
} from "../indexing/walkDir";
import { testIde } from "../test/fixtures";
import {
addToTestDir,
setUpTestDir,
tearDownTestDir,
TEST_DIR_PATH,
} from "../test/testDir";
describe("walkDir functions", () => {
beforeEach(async () => {
@ -17,8 +22,30 @@ describe("walkDir functions", () => {
afterEach(async () => {
tearDownTestDir();
walkDirCache.invalidate();
});
// describe.only("test speed", () => {
// it("should walk a simple directory structure", async () => {
// addToTestDir([
// "src/",
// ["src/file1.ts", "content1"],
// ["src/file2.ts", "content2"],
// "src/nested/",
// ["src/nested/file3.ts", "content3"],
// ]);
// const dir = await testIde.getWorkspaceDirs();
// const start = Date.now();
// for (let i = 0; i < 10000; i++) {
// await walkDir(dir[0], testIde);
// }
// const passed = Date.now() - start;
// console.log(`Test took ${passed} ms`);
// });
// });
describe("walkDir", () => {
it("should walk a simple directory structure", async () => {
addToTestDir([
@ -171,12 +198,7 @@ describe("walkDir functions", () => {
it("should skip symlinks", async () => {
const filePath = path.join(TEST_DIR_PATH, "real.ts");
addToTestDir([["real.ts", "content"]]);
fs.symlink(
filePath,
path.join(TEST_DIR_PATH, "symlink.ts"),
"file",
() => {},
);
fs.symlinkSync(filePath, path.join(TEST_DIR_PATH, "symlink.ts"), "file");
const files = await walkDirs(testIde);
@ -313,6 +335,9 @@ describe("walkDir functions", () => {
["node_modules/package/index.js", "content"],
["dist/bundle.js", "content"],
["coverage/lcov.env", "content"],
["nested/node_modules/package/index.js", "content"],
["nested/dist/bundle.js", "content"],
["nested/coverage/lcov.env", "content"],
]);
const files = await walkDir(
@ -327,6 +352,9 @@ describe("walkDir functions", () => {
expect(files).not.toContain(".git/config");
expect(files).not.toContain("node_modules/package/index.js");
expect(files).not.toContain("coverage/lcov.info");
expect(files).not.toContain("nested/node_modules/package/index.js");
expect(files).not.toContain("nested/dist/bundle.js");
expect(files).not.toContain("nested/coverage/lcov.env");
});
it("should handle directory-specific ignore patterns correctly", async () => {

View file

@ -2,27 +2,28 @@ import ignore, { Ignore } from "ignore";
import type { FileType, IDE } from "..";
import { joinPathsToUri } from "../util/uri";
import {
DEFAULT_IGNORE_DIRS,
DEFAULT_IGNORE_FILETYPES,
defaultIgnoreDir,
defaultIgnoreFile,
defaultIgnoreFileAndDir,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "./ignore";
import { joinPathsToUri } from "../util/uri";
export interface WalkerOptions {
ignoreFiles?: string[];
onlyDirs?: boolean;
returnRelativeUrisPaths?: boolean;
additionalIgnoreRules?: string[];
source?: string;
overrideDefaultIgnores?: Ignore;
}
type Entry = [string, FileType];
const LIST_DIR_CACHE_TIME = 30_000; // 30 seconds
const IGNORE_FILE_CACHE_TIME = 30_000; // 30 seconds
// helper struct used for the DFS walk
type WalkableEntry = {
name: string;
relativeUriPath: string;
uri: string;
type: FileType;
@ -40,144 +41,210 @@ type IgnoreContext = {
dirname: string;
};
class DFSWalker {
private readonly ignoreFileNames: Set<string>;
class WalkDirCache {
dirListCache: Map<
string,
{
time: number;
entries: Promise<[string, FileType][]>;
}
> = new Map();
dirIgnoreCache: Map<
string,
{
time: number;
ignore: Promise<Ignore>;
}
> = new Map();
// The super safe approach for now
invalidate() {
this.dirListCache.clear();
this.dirIgnoreCache.clear();
}
// invalidateIgnore(uri: string) {
// this.dirIgnoreCache.delete(uri);
// }
// invalidateParent(uri: string) {
// const splitUri = fileUri.split("/");
// splitUri.pop();
// const parent = splitUri.join("/");
// this.dirListCache.delete(uri);
// }
}
export const walkDirCache = new WalkDirCache(); // TODO - singleton approach better?
class DFSWalker {
constructor(
private readonly uri: string,
private readonly ide: IDE,
private readonly options: WalkerOptions,
) {
this.ignoreFileNames = new Set<string>(options.ignoreFiles);
}
) {}
// walk is a depth-first search implementation
public async *walk(): AsyncGenerator<string> {
const root = this.newRootWalkContext();
const stack = [root];
for (let cur = stack.pop(); cur; cur = stack.pop()) {
const walkableEntries = await this.listDirForWalking(cur.walkableEntry);
const ignoreContexts = await this.getIgnoreToApplyInDir(
cur,
walkableEntries,
);
for (const w of walkableEntries) {
if (!this.shouldInclude(w, ignoreContexts)) {
continue;
}
if (this.entryIsDirectory(w.entry)) {
stack.push({
walkableEntry: w,
ignoreContexts: ignoreContexts,
});
if (this.options.onlyDirs) {
// when onlyDirs is enabled the walker will only return directory names
if (this.options.returnRelativeUrisPaths) {
yield w.relativeUriPath;
} else {
yield w.uri;
}
}
} else {
// Note that shouldInclude handles skipping files if options.onlyDirs is true
if (this.options.returnRelativeUrisPaths) {
yield w.relativeUriPath;
} else {
yield w.uri;
}
}
}
}
}
const start = Date.now();
let ignoreFileTime = 0;
let ignoreTime = 0;
let listDirTime = 0;
let dirs = 0;
let listDirCacheHits = 0;
let ignoreCacheHits = 0;
private newRootWalkContext(): WalkContext {
const globalIgnoreFile = getGlobalContinueIgArray();
return {
let section = Date.now();
const defaultAndGlobalIgnores = ignore()
.add(this.options.overrideDefaultIgnores ?? defaultIgnoreFileAndDir)
.add(getGlobalContinueIgArray());
ignoreFileTime += Date.now() - section;
const rootContext: WalkContext = {
walkableEntry: {
name: "",
relativeUriPath: "",
uri: this.uri,
type: 2 as FileType.Directory,
entry: ["", 2 as FileType.Directory],
},
ignoreContexts: [
ignoreContexts: [],
};
const stack = [rootContext];
for (let cur = stack.pop(); cur; cur = stack.pop()) {
// Previous no caching approach:
// const entries = await this.ide.listDir(cur.walkableEntry.uri);
// const newIgnore = await getIgnoreContext(
// cur.walkableEntry.uri,
// entries,
// this.ide,
// defaultAndGlobalIgnores,
// );
// Only directories will be added to the stack
dirs++;
section = Date.now();
let entries: [string, FileType][] = [];
const cachedListdir = walkDirCache.dirListCache.get(
cur.walkableEntry.uri,
);
if (
cachedListdir &&
cachedListdir.time > Date.now() - LIST_DIR_CACHE_TIME
) {
entries = await cachedListdir.entries;
listDirCacheHits++;
} else {
const promise = this.ide.listDir(cur.walkableEntry.uri);
walkDirCache.dirListCache.set(cur.walkableEntry.uri, {
time: Date.now(),
entries: promise,
});
entries = await promise;
}
listDirTime += Date.now() - section;
section = Date.now();
let newIgnore: Ignore;
const cachedIgnore = walkDirCache.dirIgnoreCache.get(
cur.walkableEntry.uri,
);
if (
cachedIgnore &&
cachedIgnore.time > Date.now() - IGNORE_FILE_CACHE_TIME
) {
newIgnore = await cachedIgnore.ignore;
ignoreCacheHits++;
} else {
const ignorePromise = getIgnoreContext(
cur.walkableEntry.uri,
entries,
this.ide,
defaultAndGlobalIgnores,
);
walkDirCache.dirIgnoreCache.set(cur.walkableEntry.uri, {
time: Date.now(),
ignore: ignorePromise,
});
newIgnore = await ignorePromise;
}
const ignoreContexts = [
...cur.ignoreContexts,
{
ignore: ignore()
.add(defaultIgnoreDir)
.add(defaultIgnoreFile)
.add(globalIgnoreFile),
dirname: "",
ignore: newIgnore,
dirname: cur.walkableEntry.relativeUriPath,
},
],
};
}
];
ignoreFileTime += Date.now() - section;
private async listDirForWalking(
walkableEntry: WalkableEntry,
): Promise<WalkableEntry[]> {
const entries = await this.ide.listDir(walkableEntry.uri);
return entries.map((e) => ({
relativeUriPath: `${walkableEntry.relativeUriPath}${walkableEntry.relativeUriPath ? "/" : ""}${e[0]}`,
uri: joinPathsToUri(walkableEntry.uri, e[0]),
type: e[1],
entry: e,
}));
}
for (const entry of entries) {
if (this.entryIsSymlink(entry)) {
// If called from the root, a symlink either links to a real file in this repository,
// and therefore will be walked OR it links to something outside of the repository and
// we do not want to index it
continue;
}
const walkableEntry = {
name: entry[0],
relativeUriPath: `${cur.walkableEntry.relativeUriPath}${cur.walkableEntry.relativeUriPath ? "/" : ""}${entry[0]}`,
uri: joinPathsToUri(cur.walkableEntry.uri, entry[0]),
type: entry[1],
entry: entry,
};
private async getIgnoreToApplyInDir(
curDir: WalkContext,
entriesInDir: WalkableEntry[],
): Promise<IgnoreContext[]> {
const ignoreFilesInDir = await this.loadIgnoreFiles(entriesInDir);
if (ignoreFilesInDir.length === 0) {
return curDir.ignoreContexts;
}
const patterns = ignoreFilesInDir.map((c) => gitIgArrayFromFile(c)).flat();
const newIgnoreContext = {
ignore: ignore().add(patterns),
dirname: curDir.walkableEntry.relativeUriPath,
};
return [...curDir.ignoreContexts, newIgnoreContext];
}
let relPath = walkableEntry.relativeUriPath;
if (this.entryIsDirectory(entry)) {
relPath = `${relPath}/`;
} else {
if (this.options.onlyDirs) {
continue;
}
}
let shouldIgnore = false;
for (const ig of ignoreContexts) {
if (shouldIgnore) {
continue;
}
// remove the directory name and path separator from the match path, unless this an ignore file
// in the root directory
const prefixLength =
ig.dirname.length === 0 ? 0 : ig.dirname.length + 1;
// The ignore library expects a path relative to the ignore file location
const matchPath = relPath.substring(prefixLength);
section = Date.now();
if (ig.ignore.ignores(matchPath)) {
shouldIgnore = true;
}
ignoreTime += Date.now() - section;
}
if (shouldIgnore) {
continue;
}
private async loadIgnoreFiles(entries: WalkableEntry[]): Promise<string[]> {
const ignoreEntries = entries.filter((w) =>
this.entryIsIgnoreFile(w.entry),
);
const promises = ignoreEntries.map(async (w) => {
return await this.ide.readFile(w.uri);
});
return Promise.all(promises);
}
private shouldInclude(
walkableEntry: WalkableEntry,
ignoreContexts: IgnoreContext[],
) {
if (this.entryIsSymlink(walkableEntry.entry)) {
// If called from the root, a symlink either links to a real file in this repository,
// and therefore will be walked OR it links to something outside of the repository and
// we do not want to index it
return false;
}
let relPath = walkableEntry.relativeUriPath;
if (this.entryIsDirectory(walkableEntry.entry)) {
relPath = `${relPath}/`;
} else {
if (this.options.onlyDirs) {
return false;
if (this.entryIsDirectory(entry)) {
stack.push({
walkableEntry,
ignoreContexts,
});
if (this.options.onlyDirs) {
// when onlyDirs is enabled the walker will only return directory names
if (this.options.returnRelativeUrisPaths) {
yield walkableEntry.relativeUriPath;
} else {
yield walkableEntry.uri;
}
}
} else {
if (this.options.returnRelativeUrisPaths) {
yield walkableEntry.relativeUriPath;
} else {
yield walkableEntry.uri;
}
}
}
}
for (const ig of ignoreContexts) {
// remove the directory name and path separator from the match path, unless this an ignore file
// in the root directory
const prefixLength = ig.dirname.length === 0 ? 0 : ig.dirname.length + 1;
// The ignore library expects a path relative to the ignore file location
const matchPath = relPath.substring(prefixLength);
if (ig.ignore.ignores(matchPath)) {
return false;
}
}
return true;
// console.log(
// `Walk Dir Result:\nSource: ${this.options.source ?? "unknown"}\nDir: ${this.uri}\nDuration: ${Date.now() - start}ms:\n\tList dir: ${listDirTime}ms (${listDirCacheHits}/${dirs} cache hits)\n\tIgnore files: ${ignoreFileTime}ms (${ignoreCacheHits}/${dirs} cache hits)\n\tIgnoring: ${ignoreTime}ms`,
// );
}
private entryIsDirectory(entry: Entry) {
@ -187,25 +254,22 @@ class DFSWalker {
private entryIsSymlink(entry: Entry) {
return entry[1] === (64 as FileType.SymbolicLink);
}
private entryIsIgnoreFile(e: Entry): boolean {
if (
e[1] === (2 as FileType.Directory) ||
e[1] === (64 as FileType.SymbolicLink)
) {
return false;
}
return this.ignoreFileNames.has(e[0]);
}
}
const defaultOptions: WalkerOptions = {
ignoreFiles: [".gitignore", ".continueignore"],
additionalIgnoreRules: [...DEFAULT_IGNORE_DIRS, ...DEFAULT_IGNORE_FILETYPES],
onlyDirs: false,
returnRelativeUrisPaths: false,
};
export async function* walkDirAsync(
path: string,
ide: IDE,
_optionOverrides?: WalkerOptions,
): AsyncGenerator<string> {
const options = { ...defaultOptions, ..._optionOverrides };
yield* new DFSWalker(path, ide, options).walk();
}
export async function walkDir(
uri: string,
ide: IDE,
@ -218,15 +282,6 @@ export async function walkDir(
return urisOrRelativePaths;
}
export async function* walkDirAsync(
path: string,
ide: IDE,
_optionOverrides?: WalkerOptions,
): AsyncGenerator<string> {
const options = { ...defaultOptions, ..._optionOverrides };
yield* new DFSWalker(path, ide, options).walk();
}
export async function walkDirs(
ide: IDE,
_optionOverrides?: WalkerOptions,
@ -238,3 +293,53 @@ export async function walkDirs(
);
return results.flat();
}
export async function getIgnoreContext(
currentDir: string,
currentDirEntries: Entry[],
ide: IDE,
defaultAndGlobalIgnores: Ignore,
) {
const dirFiles = currentDirEntries
.filter(([_, entryType]) => entryType === (1 as FileType.File))
.map(([name, _]) => name);
// Find ignore files and get ignore arrays from their contexts
// These are done separately so that .continueignore can override .gitignore
const gitIgnoreFile = dirFiles.find((name) => name === ".gitignore");
const continueIgnoreFile = dirFiles.find(
(name) => name === ".continueignore",
);
const getGitIgnorePatterns = async () => {
if (gitIgnoreFile) {
const contents = await ide.readFile(`${currentDir}/.gitignore`);
return gitIgArrayFromFile(contents);
}
return [];
};
const getContinueIgnorePatterns = async () => {
if (continueIgnoreFile) {
const contents = await ide.readFile(`${currentDir}/.continueignore`);
return gitIgArrayFromFile(contents);
}
return [];
};
const ignoreArrays = await Promise.all([
getGitIgnorePatterns(),
getContinueIgnorePatterns(),
]);
if (ignoreArrays[0].length === 0 && ignoreArrays[1].length === 0) {
return defaultAndGlobalIgnores;
}
// Note precedence here!
const ignoreContext = ignore()
.add(ignoreArrays[0]) // gitignore
.add(defaultAndGlobalIgnores) // default file/folder ignores followed by global .continueignore - this is combined for speed
.add(ignoreArrays[1]); // local .continueignore
return ignoreContext;
}

View file

@ -71,6 +71,7 @@ const PROVIDER_SUPPORTS_IMAGES: string[] = [
"sagemaker",
"continue-proxy",
"openrouter",
"sambanova",
"vertexai",
"azure",
"scaleway",
@ -92,6 +93,7 @@ const MODEL_SUPPORTS_IMAGES: string[] = [
"haiku",
"pixtral",
"llama3.2",
"llama-3.2",
];
function modelSupportsTools(modelDescription: ModelDescription) {

View file

@ -8,88 +8,22 @@ import { normalizeToMessageParts } from "../util/messageContent";
import { modelSupportsTools } from "./autodetect";
const CUSTOM_SYS_MSG_MODEL_FAMILIES = ["sonnet"];
const SYSTEM_MESSAGE = `When generating new code:
1. Always produce a single code block.
2. Never separate the code into multiple code blocks.
3. Only include the code that is being added.
4. Replace existing code with a "lazy" comment like this: "// ... existing code ..."
5. The "lazy" comment must always be a valid comment in the current context (e.g. "<!-- ... existing code ... -->" for HTML, "// ... existing code ..." for JavaScript, "{/* ... existing code */}" for TSX, etc.)
6. You must always provide 1-2 lines of context above and below a "lazy" comment
7. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block.
Example 1:
Input:
\`\`\`test.js
import addition from "addition"
class Calculator {
constructor() {
this.result = 0;
}
add(number) {
this.result += number;
return this;
}
}
\`\`\`
User request: Add a subtract method
Output:
\`\`\`javascript test.js
// ... existing code ...
import subtraction from "subtraction"
class Calculator {
// ... existing code ...
subtract(number) {
this.result -= number;
return this;
}
}
\`\`\`
Example 2:
Input:
\`\`\`javascript test.js (6-9)
function helloWorld() {}
\`\`\`
Output:
\`\`\`javascript test.js
function helloWorld() {
// New code here
}
\`\`\`
Always follow these guidelines when generating code responses.`;
const TOOL_USE_RULES = `When using tools, follow the following guidelines:
- Avoid calling tools unless they are absolutely necessary. For example, if you are asked a simple programming question you do not need web search. As another example, if the user asks you to explain something about code, do not create a new file.`;
const TOOL_USE_RULES = `<tool_use_rules>
When using tools, follow the following guidelines:
- Avoid calling tools unless they are absolutely necessary. For example, if you are asked a simple programming question you do not need web search. As another example, if the user asks you to explain something about code, do not create a new file.
</tool_use_rules>`;
function constructSystemPrompt(
modelDescription: ModelDescription,
useTools: boolean,
): string | null {
let systemMessage = "";
if (
CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) =>
modelDescription.model.includes(family),
)
) {
systemMessage = SYSTEM_MESSAGE;
}
let systemMessage = `<important_rules>
Always include the language and file name in the info string when you write code blocks. If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'.
</important_rules>`;
if (useTools && modelSupportsTools(modelDescription)) {
if (systemMessage) {
systemMessage += "\n\n";
}
systemMessage += TOOL_USE_RULES;
systemMessage += "\n\n" + TOOL_USE_RULES;
}
return systemMessage || null;
return systemMessage;
}
const CANCELED_TOOL_CALL_MESSAGE =

View file

@ -27,9 +27,9 @@ class LlamaEncoding implements Encoding {
}
class NonWorkerAsyncEncoder implements AsyncEncoder {
constructor(private readonly encoding: Encoding) {}
constructor(private readonly encoding: Encoding) { }
async close(): Promise<void> {}
async close(): Promise<void> { }
async encode(text: string): Promise<number[]> {
return this.encoding.encode(text);
@ -366,6 +366,7 @@ function chatMessageIsEmpty(message: ChatMessage): boolean {
message.content.trim() === "" &&
!message.toolCalls
);
case "thinking":
case "tool":
return false;
}
@ -383,8 +384,8 @@ function compileChatMessages(
): ChatMessage[] {
let msgsCopy = msgs
? msgs
.map((msg) => ({ ...msg }))
.filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system")
.map((msg) => ({ ...msg }))
.filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system")
: [];
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
@ -469,5 +470,6 @@ export {
pruneLinesFromTop,
pruneRawPromptFromTop,
pruneStringFromBottom,
pruneStringFromTop,
pruneStringFromTop
};

View file

@ -1,3 +1,4 @@
import { ModelRole } from "@continuedev/config-yaml";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import { findLlmInfo } from "@continuedev/llm-info";
import {
@ -7,6 +8,8 @@ import {
} from "@continuedev/openai-adapters";
import Handlebars from "handlebars";
import { DevDataSqliteDb } from "../data/devdataSqlite.js";
import { DataLogger } from "../data/log.js";
import {
CacheBehavior,
ChatMessage,
@ -16,13 +19,12 @@ import {
LLMFullCompletionOptions,
LLMOptions,
ModelCapability,
ModelInstaller,
PromptLog,
PromptTemplate,
RequestOptions,
TemplateType,
} from "../index.js";
import { logDevData } from "../util/devdata.js";
import { DevDataSqliteDb } from "../util/devdataSqlite.js";
import mergeJson from "../util/merge.js";
import { renderChatMessage } from "../util/messageContent.js";
import { isOllamaInstalled } from "../util/ollamaHelper.js";
@ -56,7 +58,19 @@ import {
toCompleteBody,
toFimBody,
} from "./openaiTypeConverters.js";
import { ModelRole } from "@continuedev/config-yaml";
export class LLMError extends Error {
constructor(
message: string,
public llm: ILLM,
) {
super(message);
}
}
export function isModelInstaller(provider: any): provider is ModelInstaller {
return provider && typeof provider.installModel === "function";
}
export abstract class BaseLLM implements ILLM {
static providerName: string;
@ -118,8 +132,14 @@ export abstract class BaseLLM implements ILLM {
writeLog?: (str: string) => Promise<void>;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
// continueProperties
apiKeyLocation?: string;
apiBase?: string;
orgScopeId?: string | null;
onPremProxyUrl?: string | null;
cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
roles?: ModelRole[];
@ -175,11 +195,11 @@ export abstract class BaseLLM implements ILLM {
options.completionOptions?.maxTokens ??
(llmInfo?.maxCompletionTokens
? Math.min(
llmInfo.maxCompletionTokens,
// Even if the model has a large maxTokens, we don't want to use that every time,
// because it takes away from the context length
this.contextLength / 4,
)
llmInfo.maxCompletionTokens,
// Even if the model has a large maxTokens, we don't want to use that every time,
// because it takes away from the context length
this.contextLength / 4,
)
: DEFAULT_MAX_TOKENS),
};
this.requestOptions = options.requestOptions;
@ -198,9 +218,15 @@ export abstract class BaseLLM implements ILLM {
this.writeLog = options.writeLog;
this.llmRequestHook = options.llmRequestHook;
this.apiKey = options.apiKey;
// continueProperties
this.apiKeyLocation = options.apiKeyLocation;
this.aiGatewaySlug = options.aiGatewaySlug;
this.orgScopeId = options.orgScopeId;
this.apiBase = options.apiBase;
this.onPremProxyUrl = options.onPremProxyUrl;
this.aiGatewaySlug = options.aiGatewaySlug;
this.cacheBehavior = options.cacheBehavior;
// watsonx deploymentId
@ -288,7 +314,7 @@ export abstract class BaseLLM implements ILLM {
return this.templateMessages(msgs);
}
private _compileLogMessage(
private _compilePromptForLog(
prompt: string,
completionOptions: CompletionOptions,
): string {
@ -343,11 +369,14 @@ export abstract class BaseLLM implements ILLM {
generatedTokens,
);
logDevData("tokens_generated", {
model: model,
provider: this.providerName,
promptTokens: promptTokens,
generatedTokens: generatedTokens,
void DataLogger.getInstance().logDevData({
name: "tokensGenerated",
data: {
model: model,
provider: this.providerName,
promptTokens: promptTokens,
generatedTokens: generatedTokens,
},
});
}
@ -365,9 +394,11 @@ export abstract class BaseLLM implements ILLM {
if (!resp.ok) {
let text = await resp.text();
if (resp.status === 404 && !resp.url.includes("/v1")) {
if (text.includes("try pulling it first")) {
const model = JSON.parse(text).error.split(" ")[1].slice(1, -1);
const error = JSON.parse(text)?.error?.replace(/"/g, "'");
let model = error?.match(/model '(.*)' not found/)?.[1];
if (model && resp.url.match("127.0.0.1:11434")) {
text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`;
throw new LLMError(text, this); // No need to add HTTP status details
} else if (text.includes("/api/chat")) {
text =
"The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue.";
@ -427,6 +458,10 @@ export abstract class BaseLLM implements ILLM {
throw new Error(message);
}
}
//if e instance of LLMError, rethrow
if (e instanceof LLMError) {
throw e;
}
throw new Error(e.message);
}
};
@ -447,7 +482,7 @@ export abstract class BaseLLM implements ILLM {
options,
);
return { completionOptions, log, raw };
return { completionOptions, logEnabled: log, raw };
}
private _formatChatMessages(messages: ChatMessage[]): string {
@ -500,12 +535,15 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
): AsyncGenerator<string> {
const { completionOptions, log } = this._parseCompletionOptions(options);
const { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
const fimLog = `Prefix: ${prefix}\nSuffix: ${suffix}`;
if (log) {
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(fimLog, completionOptions));
await this.writeLog(
this._compilePromptForLog(fimLog, completionOptions),
);
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, fimLog);
@ -541,7 +579,7 @@ export abstract class BaseLLM implements ILLM {
this._logTokensGenerated(completionOptions.model, fimLog, completion);
if (log && this.writeLog) {
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
}
@ -557,7 +595,7 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
) {
const { completionOptions, log, raw } =
const { completionOptions, logEnabled, raw } =
this._parseCompletionOptions(options);
let prompt = pruneRawPromptFromTop(
@ -571,9 +609,11 @@ export abstract class BaseLLM implements ILLM {
prompt = this._templatePromptLikeMessages(prompt);
}
if (log) {
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(prompt, completionOptions));
await this.writeLog(
this._compilePromptForLog(prompt, completionOptions),
);
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
@ -618,7 +658,7 @@ export abstract class BaseLLM implements ILLM {
} finally {
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
}
}
@ -636,7 +676,7 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
) {
const { completionOptions, log, raw } =
const { completionOptions, logEnabled, raw } =
this._parseCompletionOptions(options);
let prompt = pruneRawPromptFromTop(
@ -650,9 +690,11 @@ export abstract class BaseLLM implements ILLM {
prompt = this._templatePromptLikeMessages(prompt);
}
if (log) {
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(prompt, completionOptions));
await this.writeLog(
this._compilePromptForLog(prompt, completionOptions),
);
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
@ -675,7 +717,7 @@ export abstract class BaseLLM implements ILLM {
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
}
@ -719,7 +761,8 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
): AsyncGenerator<ChatMessage, PromptLog> {
let { completionOptions, log } = this._parseCompletionOptions(options);
let { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
completionOptions = this._modifyCompletionOptions(completionOptions);
@ -728,16 +771,20 @@ export abstract class BaseLLM implements ILLM {
const prompt = this.templateMessages
? this.templateMessages(messages)
: this._formatChatMessages(messages);
if (log) {
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(prompt, completionOptions));
await this.writeLog(
this._compilePromptForLog(prompt, completionOptions),
);
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
}
}
let thinking = "";
let completion = "";
let citations: null | string[] = null;
try {
if (this.templateMessages) {
@ -775,8 +822,16 @@ export abstract class BaseLLM implements ILLM {
for await (const chunk of stream) {
const result = fromChatCompletionChunk(chunk);
if (result) {
completion += result.content;
yield result;
}
if (
!citations &&
(chunk as any).citations &&
Array.isArray((chunk as any).citations)
) {
citations = (chunk as any).citations;
}
}
}
} else {
@ -785,8 +840,16 @@ export abstract class BaseLLM implements ILLM {
signal,
completionOptions,
)) {
completion += chunk.content;
yield chunk;
if (chunk.role === "assistant") {
completion += chunk.content;
yield chunk;
}
if (chunk.role === "thinking") {
thinking += chunk.content;
yield chunk;
}
}
}
}
@ -797,8 +860,26 @@ export abstract class BaseLLM implements ILLM {
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
if (logEnabled && this.writeLog) {
if (thinking) {
await this.writeLog(`Thinking:\n${thinking}\n\n`);
}
/*
TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
During tool use, you must pass thinking and redacted_thinking blocks back to the API,
and you must include the complete unmodified block back to the API. This is critical
for maintaining the model's reasoning flow and conversation integrity.
On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent
requests when not using tools, so it's the simplest option to always add to history.
*/
await this.writeLog(`Completion:\n${completion}\n\n`);
if (citations) {
await this.writeLog(
`Citations:\n${citations.map((c, i) => `${i + 1}: ${c}`).join("\n")}\n\n`,
);
}
}
return {
@ -867,7 +948,7 @@ export abstract class BaseLLM implements ILLM {
);
}
protected async *_streamComplete(
protected async * _streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
@ -875,7 +956,7 @@ export abstract class BaseLLM implements ILLM {
throw new Error("Not implemented");
}
protected async *_streamChat(
protected async * _streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,

View file

@ -205,10 +205,11 @@ describe("LLM", () => {
});
testLLM(
new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1-preview" }),
{ skip: false, timeout: 20000 },
{ skip: false, timeout: 60000 },
);
testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1" }), {
skip: false,
timeout: 60000,
});
testLLM(
new Gemini({

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