Merge branch 'main' into config-page-palette
2
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -481,7 +481,7 @@ jobs:
|
|||
|
||||
# Run Qodana inspections
|
||||
- name: Qodana - Code Inspection
|
||||
uses: JetBrains/qodana-action@v2024.3.2
|
||||
uses: JetBrains/qodana-action@v2025.1.0
|
||||
with:
|
||||
cache-default-branch-only: true
|
||||
|
||||
|
|
|
|||
49
.github/workflows/pr_checks.yaml
vendored
|
|
@ -1,5 +1,6 @@
|
|||
name: PR checks
|
||||
|
||||
# PR Checks run on all PRs to the main branch and must pass before merging.
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
|
|
@ -415,6 +416,30 @@ jobs:
|
|||
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
|
||||
AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }}
|
||||
|
||||
package-tests:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: core/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm ci
|
||||
|
||||
- name: Run config-yaml tests
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm test
|
||||
|
||||
vscode-get-test-file-matrix:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [install-root, install-vscode, install-config-yaml]
|
||||
|
|
@ -551,7 +576,7 @@ jobs:
|
|||
path: extensions/vscode/e2e/storage
|
||||
|
||||
vscode-e2e-tests:
|
||||
name: ${{ matrix.test_file }} (${{ matrix.command }})
|
||||
name: ${{ matrix.test_file || 'unknown' }} (${{ matrix.command }})
|
||||
needs:
|
||||
[
|
||||
vscode-download-e2e-dependencies,
|
||||
|
|
@ -652,6 +677,27 @@ jobs:
|
|||
name: e2e-failure-screenshots
|
||||
path: extensions/vscode/e2e/storage/screenshots
|
||||
|
||||
- name: Sanitize test file name
|
||||
id: sanitize_filename
|
||||
if: always()
|
||||
run: |
|
||||
FILENAME="${{ matrix.test_file }}"
|
||||
SANITIZED_FILENAME="${FILENAME//\//-}" # Replace / with - using bash parameter expansion
|
||||
echo "sanitized_test_file=${SANITIZED_FILENAME}" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Find e2e log file
|
||||
if: always()
|
||||
run: |
|
||||
echo "Searching for e2e.log file..."
|
||||
find $GITHUB_WORKSPACE -name "e2e.log" -type f
|
||||
|
||||
- name: Upload e2e logs
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-logs-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ matrix.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }}
|
||||
path: extensions/vscode/e2e.log
|
||||
|
||||
gui-tests:
|
||||
needs: [install-gui, install-core, install-config-yaml]
|
||||
runs-on: ubuntu-latest
|
||||
|
|
@ -820,6 +866,7 @@ jobs:
|
|||
- install-vscode
|
||||
- vscode-checks
|
||||
- core-tests
|
||||
- package-tests
|
||||
- vscode-get-test-file-matrix
|
||||
- vscode-package-extension
|
||||
- vscode-download-e2e-dependencies
|
||||
|
|
|
|||
10
.gitignore
vendored
|
|
@ -83,16 +83,6 @@ ipython_config.py
|
|||
# pyenv
|
||||
.python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
|
|
|||
3
.idea/compiler.xml
generated
|
|
@ -3,4 +3,7 @@
|
|||
<component name="CompilerConfiguration">
|
||||
<bytecodeTargetLevel target="17" />
|
||||
</component>
|
||||
<component name="TypeScriptCompiler">
|
||||
<option name="useTypesFromServer" value="true" />
|
||||
</component>
|
||||
</project>
|
||||
1
.idea/gradle.xml
generated
|
|
@ -5,6 +5,7 @@
|
|||
<option name="linkedExternalProjectsSettings">
|
||||
<GradleProjectSettings>
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
|
||||
<option name="gradleJvm" value="homebrew-17" />
|
||||
<option name="modules">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$/extensions/intellij" />
|
||||
|
|
|
|||
2
.idea/scopes/Continue.xml
generated
|
|
@ -1,3 +1,3 @@
|
|||
<component name="DependencyValidationManager">
|
||||
<scope name="Continue" pattern="file[continue-intellij-extension]:*/&&!file[continue-intellij-extension]:binary/bin//*&&!file[continue-intellij-extension]:binary/build//*&&!file[continue-intellij-extension]:binary/out//*&&!file[continue-intellij-extension]:gui/dist//*&&!file[continue-intellij-extension]:extensions/intellij/build//*&&!file[continue-intellij-extension]:extensions/vscode/bin//*&&!file[continue-intellij-extension]:extensions/vscode/build//*&&!file[continue-intellij-extension]:extensions/vscode/out//*" />
|
||||
<scope name="Continue" pattern="file:*/&&!file:binary/bin//*&&!file:binary/build//*&&!file:binary/out//*&&!file:gui/dist//*&&!file:extensions/intellij/build//*&&!file:extensions/vscode/bin//*&&!file:extensions/vscode/build//*&&!file:extensions/vscode/out//*&&!file:**/*.coverage&&!file:**/*.coveragedata&&!file:**/coverage//*&&!file:**/.coverage//*&&!file:**/assets//**" />
|
||||
</component>
|
||||
|
|
@ -1 +1 @@
|
|||
20.11.0
|
||||
20.19.0
|
||||
2
.nvmrc
|
|
@ -1 +1 @@
|
|||
v20.11.0
|
||||
v20.19.0
|
||||
|
|
@ -102,7 +102,7 @@ We welcome contributions from developers of all experience levels - from first-t
|
|||
|
||||
#### Pre-requisites
|
||||
|
||||
You should have Node.js version 20.11.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
|
||||
You should have Node.js version 20.19.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
|
||||
|
||||
```bash
|
||||
nvm use
|
||||
|
|
|
|||
|
|
@ -9,17 +9,20 @@ const {
|
|||
autodetectPlatformAndArch,
|
||||
} = require("../scripts/util");
|
||||
|
||||
// Clean slate
|
||||
const bin = path.join(__dirname, "bin");
|
||||
const out = path.join(__dirname, "out");
|
||||
const build = path.join(__dirname, "build");
|
||||
rimrafSync(bin);
|
||||
rimrafSync(out);
|
||||
rimrafSync(build);
|
||||
rimrafSync(path.join(__dirname, "tmp"));
|
||||
fs.mkdirSync(bin);
|
||||
fs.mkdirSync(out);
|
||||
fs.mkdirSync(build);
|
||||
|
||||
function cleanSlate() {
|
||||
// Clean slate
|
||||
rimrafSync(bin);
|
||||
rimrafSync(out);
|
||||
rimrafSync(build);
|
||||
rimrafSync(path.join(__dirname, "tmp"));
|
||||
fs.mkdirSync(bin);
|
||||
fs.mkdirSync(out);
|
||||
fs.mkdirSync(build);
|
||||
}
|
||||
|
||||
const esbuildOutputFile = "out/index.js";
|
||||
let targets = [
|
||||
|
|
@ -56,6 +59,39 @@ const targetToLanceDb = {
|
|||
"win32-arm64": "@lancedb/vectordb-win32-arm64-msvc",
|
||||
};
|
||||
|
||||
// Bundles the extension into one file
|
||||
async function buildWithEsbuild() {
|
||||
console.log("[info] Building with esbuild...");
|
||||
await esbuild.build({
|
||||
entryPoints: ["src/index.ts"],
|
||||
bundle: true,
|
||||
outfile: esbuildOutputFile,
|
||||
external: [
|
||||
"esbuild",
|
||||
"./xhr-sync-worker.js",
|
||||
"llamaTokenizerWorkerPool.mjs",
|
||||
"tiktokenWorkerPool.mjs",
|
||||
"vscode",
|
||||
"./index.node",
|
||||
],
|
||||
format: "cjs",
|
||||
platform: "node",
|
||||
sourcemap: true,
|
||||
minify: true,
|
||||
treeShaking: true,
|
||||
loader: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
".node": "file",
|
||||
},
|
||||
|
||||
// To allow import.meta.path for transformers.js
|
||||
// https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483
|
||||
inject: ["./importMetaUrl.js"],
|
||||
define: { "import.meta.url": "importMetaUrl" },
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
|
||||
console.log(`Copying ${packageName} to ${toCopy}`);
|
||||
// This is a way to install only one package without npm trying to install all the dependencies
|
||||
|
|
@ -118,6 +154,13 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
|
|||
}
|
||||
|
||||
(async () => {
|
||||
if (esbuildOnly) {
|
||||
await buildWithEsbuild();
|
||||
return;
|
||||
}
|
||||
|
||||
cleanSlate()
|
||||
|
||||
// Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
|
||||
// This is only needed for our `pkg` command at build time
|
||||
fs.writeFileSync(
|
||||
|
|
@ -192,35 +235,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
|
|||
fs.rmSync(assetPath, { force: true });
|
||||
}
|
||||
|
||||
// Bundles the extension into one file
|
||||
console.log("[info] Building with esbuild...");
|
||||
await esbuild.build({
|
||||
entryPoints: ["src/index.ts"],
|
||||
bundle: true,
|
||||
outfile: esbuildOutputFile,
|
||||
external: [
|
||||
"esbuild",
|
||||
"./xhr-sync-worker.js",
|
||||
"llamaTokenizerWorkerPool.mjs",
|
||||
"tiktokenWorkerPool.mjs",
|
||||
"vscode",
|
||||
"./index.node",
|
||||
],
|
||||
format: "cjs",
|
||||
platform: "node",
|
||||
sourcemap: true,
|
||||
minify: true,
|
||||
treeShaking: true,
|
||||
loader: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
".node": "file",
|
||||
},
|
||||
|
||||
// To allow import.meta.path for transformers.js
|
||||
// https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483
|
||||
inject: ["./importMetaUrl.js"],
|
||||
define: { "import.meta.url": "importMetaUrl" },
|
||||
});
|
||||
await buildWithEsbuild();
|
||||
|
||||
// Copy over any worker files
|
||||
fs.cpSync(
|
||||
|
|
@ -233,10 +248,6 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
|
|||
"out/llamaTokenizerWorkerPool.mjs",
|
||||
);
|
||||
|
||||
if (esbuildOnly) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("[info] Building binaries with pkg...");
|
||||
for (const target of targets) {
|
||||
const targetDir = `bin/${target}`;
|
||||
|
|
|
|||
2
binary/package-lock.json
generated
|
|
@ -140,7 +140,7 @@
|
|||
"typescript": "^5.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.11.0"
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@75lb/deep-merge": {
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@
|
|||
"scripts": {
|
||||
"test": "jest",
|
||||
"build": "node build.js",
|
||||
"rebuild": "node build.js --esbuild-only",
|
||||
"build:darwin-x64": "node build.js --os darwin-x64"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@
|
|||
"@typescript-eslint/semi": "off",
|
||||
"eqeqeq": "error",
|
||||
"complexity": ["error", { "max": 36 }],
|
||||
"max-lines-per-function": ["error", { "max": 472 }],
|
||||
"max-lines-per-function": ["error", { "max": 500 }],
|
||||
"max-statements": ["error", { "max": 108 }],
|
||||
"max-depth": ["error", { "max": 6 }],
|
||||
"max-nested-callbacks": ["error", { "max": 4 }],
|
||||
|
|
|
|||
|
|
@ -154,6 +154,10 @@ export class CompletionProvider {
|
|||
return undefined;
|
||||
}
|
||||
|
||||
if (llm.promptTemplates?.autocomplete) {
|
||||
options.template = llm.promptTemplates.autocomplete as string;
|
||||
}
|
||||
|
||||
const helper = await HelperVars.create(
|
||||
input,
|
||||
options,
|
||||
|
|
|
|||
|
|
@ -15,7 +15,12 @@ import {
|
|||
} from "../index.js";
|
||||
import { GlobalContext } from "../util/GlobalContext.js";
|
||||
|
||||
import { getAllAssistantFiles } from "./loadLocalAssistants.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
import {
|
||||
ASSISTANTS,
|
||||
getAllDotContinueYamlFiles,
|
||||
LoadAssistantFilesOptions,
|
||||
} from "./loadLocalAssistants.js";
|
||||
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
|
||||
import PlatformProfileLoader from "./profile/PlatformProfileLoader.js";
|
||||
import {
|
||||
|
|
@ -185,7 +190,11 @@ export class ConfigHandler {
|
|||
private async getNonPersonalHubOrg(
|
||||
org: OrganizationDescription,
|
||||
): Promise<OrgWithProfiles> {
|
||||
const profiles = await this.getHubProfiles(org.id);
|
||||
const localProfiles = await this.getLocalProfiles({
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
});
|
||||
const profiles = [...(await this.getHubProfiles(org.id)), ...localProfiles];
|
||||
return this.rectifyProfilesForOrg(org, profiles);
|
||||
}
|
||||
|
||||
|
|
@ -196,15 +205,21 @@ export class ConfigHandler {
|
|||
slug: undefined,
|
||||
};
|
||||
private async getPersonalHubOrg() {
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
const localProfiles = await this.getLocalProfiles({
|
||||
includeGlobal: true,
|
||||
includeWorkspace: true,
|
||||
});
|
||||
const hubProfiles = await this.getHubProfiles(null);
|
||||
const profiles = [...hubProfiles, ...allLocalProfiles];
|
||||
const profiles = [...hubProfiles, ...localProfiles];
|
||||
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles);
|
||||
}
|
||||
|
||||
private async getLocalOrg() {
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, allLocalProfiles);
|
||||
const localProfiles = await this.getLocalProfiles({
|
||||
includeGlobal: true,
|
||||
includeWorkspace: true,
|
||||
});
|
||||
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, localProfiles);
|
||||
}
|
||||
|
||||
private async rectifyProfilesForOrg(
|
||||
|
|
@ -251,24 +266,41 @@ export class ConfigHandler {
|
|||
};
|
||||
}
|
||||
|
||||
async getAllLocalProfiles() {
|
||||
async getLocalProfiles(options: LoadAssistantFilesOptions) {
|
||||
/**
|
||||
* Users can define as many local assistants as they want in a `.continue/assistants` folder
|
||||
*/
|
||||
const assistantFiles = await getAllAssistantFiles(this.ide);
|
||||
const profiles = assistantFiles.map((assistant) => {
|
||||
return new LocalProfileLoader(
|
||||
const localProfiles: ProfileLifecycleManager[] = [];
|
||||
|
||||
if (options.includeGlobal) {
|
||||
localProfiles.push(this.globalLocalProfileManager);
|
||||
}
|
||||
|
||||
if (options.includeWorkspace) {
|
||||
const assistantFiles = await getAllDotContinueYamlFiles(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.llmLogger,
|
||||
assistant,
|
||||
{
|
||||
...options,
|
||||
includeGlobal: false, // Because the global comes from above
|
||||
},
|
||||
ASSISTANTS,
|
||||
);
|
||||
});
|
||||
const localAssistantProfiles = profiles.map(
|
||||
(profile) => new ProfileLifecycleManager(profile, this.ide),
|
||||
);
|
||||
return [this.globalLocalProfileManager, ...localAssistantProfiles];
|
||||
const profiles = assistantFiles.map((assistant) => {
|
||||
return new LocalProfileLoader(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.llmLogger,
|
||||
assistant,
|
||||
);
|
||||
});
|
||||
const localAssistantProfiles = profiles.map(
|
||||
(profile) => new ProfileLifecycleManager(profile, this.ide),
|
||||
);
|
||||
localProfiles.push(...localAssistantProfiles);
|
||||
}
|
||||
|
||||
return localProfiles;
|
||||
}
|
||||
|
||||
//////////////////
|
||||
|
|
@ -421,9 +453,14 @@ export class ConfigHandler {
|
|||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
return await this.currentProfile.loadConfig(
|
||||
const config = await this.currentProfile.loadConfig(
|
||||
this.additionalContextProviders,
|
||||
);
|
||||
|
||||
if (config.errors?.length) {
|
||||
logger.warn("Errors loading config: ", config.errors);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
async openConfigProfile(profileId?: string) {
|
||||
|
|
|
|||
|
|
@ -95,7 +95,10 @@ export class ProfileLifecycleManager {
|
|||
try {
|
||||
result = await this.profileLoader.doLoadConfig();
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : "Error loading config";
|
||||
const message =
|
||||
e instanceof Error
|
||||
? `${e.message}\n${e.stack ? e.stack : ""}`
|
||||
: "Error loading config";
|
||||
result = {
|
||||
errors: [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -5,11 +5,12 @@ import {
|
|||
DEFAULT_IGNORE_FILETYPES,
|
||||
} from "../indexing/ignore";
|
||||
import { walkDir } from "../indexing/walkDir";
|
||||
import { getGlobalAssistantsPath } from "../util/paths";
|
||||
import { getGlobalFolderWithName } from "../util/paths";
|
||||
import { localPathToUri } from "../util/pathToUri";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
|
||||
export const ASSISTANTS_FOLDER = ".continue/assistants";
|
||||
export const ASSISTANTS = "assistants";
|
||||
export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`;
|
||||
|
||||
export function isLocalAssistantFile(uri: string): boolean {
|
||||
if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) {
|
||||
|
|
@ -20,7 +21,7 @@ export function isLocalAssistantFile(uri: string): boolean {
|
|||
return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
|
||||
}
|
||||
|
||||
export async function getAssistantFilesFromDir(
|
||||
export async function listYamlFilesInDir(
|
||||
ide: IDE,
|
||||
dir: string,
|
||||
): Promise<{ path: string; content: string }[]> {
|
||||
|
|
@ -53,21 +54,56 @@ export async function getAssistantFilesFromDir(
|
|||
}
|
||||
}
|
||||
|
||||
export async function getAllAssistantFiles(
|
||||
export interface LoadAssistantFilesOptions {
|
||||
includeGlobal: boolean;
|
||||
includeWorkspace: boolean;
|
||||
}
|
||||
|
||||
export function getDotContinueSubDirs(
|
||||
ide: IDE,
|
||||
options: LoadAssistantFilesOptions,
|
||||
workspaceDirs: string[],
|
||||
subDirName: string,
|
||||
): string[] {
|
||||
let fullDirs: string[] = [];
|
||||
|
||||
// Workspace .continue/<subDirName>
|
||||
if (options.includeWorkspace) {
|
||||
fullDirs = workspaceDirs.map((dir) =>
|
||||
joinPathsToUri(dir, ".continue", subDirName),
|
||||
);
|
||||
}
|
||||
|
||||
// ~/.continue/<subDirName>
|
||||
if (options.includeGlobal) {
|
||||
fullDirs.push(localPathToUri(getGlobalFolderWithName(subDirName)));
|
||||
}
|
||||
|
||||
return fullDirs;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method searches in both ~/.continue and workspace .continue
|
||||
* for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts
|
||||
*/
|
||||
export async function getAllDotContinueYamlFiles(
|
||||
ide: IDE,
|
||||
options: LoadAssistantFilesOptions,
|
||||
subDirName: string,
|
||||
): 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();
|
||||
// Get all directories to check for assistant files
|
||||
const fullDirs = getDotContinueSubDirs(
|
||||
ide,
|
||||
options,
|
||||
workspaceDirs,
|
||||
subDirName,
|
||||
);
|
||||
|
||||
fullDirs.push(localPathToUri(getGlobalAssistantsPath()));
|
||||
|
||||
assistantFiles = (
|
||||
await Promise.all(fullDirs.map((dir) => getAssistantFilesFromDir(ide, dir)))
|
||||
// Get all assistant files from the directories
|
||||
const assistantFiles = (
|
||||
await Promise.all(fullDirs.map((dir) => listYamlFilesInDir(ide, dir)))
|
||||
).flat();
|
||||
|
||||
return await Promise.all(
|
||||
|
|
|
|||
|
|
@ -60,12 +60,14 @@ export default class LocalProfileLoader implements IProfileLoader {
|
|||
ideSettingsPromise: this.ideSettingsPromise,
|
||||
controlPlaneClient: this.controlPlaneClient,
|
||||
llmLogger: this.llmLogger,
|
||||
overrideConfigJson: undefined,
|
||||
overrideConfigYaml: undefined,
|
||||
platformConfigMetadata: undefined,
|
||||
profileId: this.description.id,
|
||||
overrideConfigYamlByPath: this.overrideAssistantFile?.path,
|
||||
orgScopeId: null,
|
||||
packageIdentifier: {
|
||||
uriType: "file",
|
||||
filePath:
|
||||
this.overrideAssistantFile?.path ?? getPrimaryConfigFilePath(),
|
||||
},
|
||||
});
|
||||
|
||||
this.description.errors = result.errors;
|
||||
|
|
|
|||
|
|
@ -142,15 +142,17 @@ export default class PlatformProfileLoader implements IProfileLoader {
|
|||
ideSettingsPromise: this.ideSettingsPromise,
|
||||
controlPlaneClient: this.controlPlaneClient,
|
||||
llmLogger: this.llmLogger,
|
||||
overrideConfigJson: undefined,
|
||||
overrideConfigYaml: this.configResult.config,
|
||||
platformConfigMetadata: {
|
||||
ownerSlug: this.ownerSlug,
|
||||
packageSlug: this.packageSlug,
|
||||
},
|
||||
profileId: this.description.id,
|
||||
overrideConfigYamlByPath: undefined,
|
||||
orgScopeId: this.orgScopeId,
|
||||
packageIdentifier: {
|
||||
uriType: "slug",
|
||||
fullSlug: {
|
||||
ownerSlug: this.ownerSlug,
|
||||
packageSlug: this.packageSlug,
|
||||
versionSlug: this.versionSlug,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
ConfigResult,
|
||||
ConfigValidationError,
|
||||
ModelRole,
|
||||
PackageIdentifier,
|
||||
} from "@continuedev/config-yaml";
|
||||
|
||||
import {
|
||||
|
|
@ -29,37 +30,37 @@ import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
|
|||
import { localPathOrUriToPath } from "../../util/pathToUri";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
import { TTS } from "../../util/tts";
|
||||
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
|
||||
import { loadContinueConfigFromJson } from "../load";
|
||||
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
|
||||
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
|
||||
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
|
||||
|
||||
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
|
||||
import { PlatformConfigMetadata } from "./PlatformProfileLoader";
|
||||
|
||||
export default async function doLoadConfig({
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
controlPlaneClient,
|
||||
llmLogger,
|
||||
overrideConfigJson,
|
||||
overrideConfigYaml,
|
||||
platformConfigMetadata,
|
||||
profileId,
|
||||
overrideConfigYamlByPath,
|
||||
orgScopeId,
|
||||
}: {
|
||||
export default async function doLoadConfig(options: {
|
||||
ide: IDE;
|
||||
ideSettingsPromise: Promise<IdeSettings>;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
llmLogger: ILLMLogger;
|
||||
overrideConfigJson: SerializedContinueConfig | undefined;
|
||||
overrideConfigYaml: AssistantUnrolled | undefined;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
overrideConfigJson?: SerializedContinueConfig;
|
||||
overrideConfigYaml?: AssistantUnrolled;
|
||||
profileId: string;
|
||||
overrideConfigYamlByPath: string | undefined;
|
||||
overrideConfigYamlByPath?: string;
|
||||
orgScopeId: string | null;
|
||||
packageIdentifier: PackageIdentifier;
|
||||
}): Promise<ConfigResult<ContinueConfig>> {
|
||||
const {
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
controlPlaneClient,
|
||||
llmLogger,
|
||||
overrideConfigJson,
|
||||
overrideConfigYaml,
|
||||
profileId,
|
||||
overrideConfigYamlByPath,
|
||||
orgScopeId,
|
||||
packageIdentifier,
|
||||
} = options;
|
||||
|
||||
const workspaceConfigs = await getWorkspaceConfigs(ide);
|
||||
const ideInfo = await ide.getIdeInfo();
|
||||
const uniqueId = await ide.getUniqueId();
|
||||
|
|
@ -89,10 +90,10 @@ export default async function doLoadConfig({
|
|||
uniqueId,
|
||||
llmLogger,
|
||||
overrideConfigYaml,
|
||||
platformConfigMetadata,
|
||||
controlPlaneClient,
|
||||
configYamlPath,
|
||||
orgScopeId,
|
||||
packageIdentifier,
|
||||
workOsAccessToken,
|
||||
});
|
||||
newConfig = result.config;
|
||||
errors = result.errors;
|
||||
|
|
@ -236,13 +237,13 @@ export default async function doLoadConfig({
|
|||
};
|
||||
|
||||
if (newConfig.analytics) {
|
||||
await TeamAnalytics.setup(
|
||||
newConfig.analytics,
|
||||
uniqueId,
|
||||
ideInfo.extensionVersion,
|
||||
controlPlaneClient,
|
||||
controlPlaneProxyInfo,
|
||||
);
|
||||
// await TeamAnalytics.setup(
|
||||
// newConfig.analytics,
|
||||
// uniqueId,
|
||||
// ideInfo.extensionVersion,
|
||||
// controlPlaneClient,
|
||||
// controlPlaneProxyInfo,
|
||||
// );
|
||||
} else {
|
||||
await TeamAnalytics.shutdown();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -403,6 +403,7 @@ declare global {
|
|||
| "generated"
|
||||
| "calling"
|
||||
| "done"
|
||||
| "errored"
|
||||
| "canceled";
|
||||
|
||||
// Will exist only on "assistant" messages with tool calls
|
||||
|
|
|
|||
106
core/config/yaml/LocalPlatformClient.ts
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
import {
|
||||
FQSN,
|
||||
PlatformClient,
|
||||
SecretResult,
|
||||
SecretType,
|
||||
} from "@continuedev/config-yaml";
|
||||
import * as dotenv from "dotenv";
|
||||
import { IDE } from "../..";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import { getContinueDotEnv } from "../../util/paths";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
|
||||
export class LocalPlatformClient implements PlatformClient {
|
||||
constructor(
|
||||
private orgScopeId: string | null,
|
||||
private readonly client: ControlPlaneClient,
|
||||
private readonly ide: IDE,
|
||||
) {}
|
||||
|
||||
private async findSecretInEnvFiles(
|
||||
fqsn: FQSN,
|
||||
): Promise<SecretResult | undefined> {
|
||||
const secretValue =
|
||||
this.findSecretInLocalEnvFile(fqsn) ??
|
||||
(await this.findSecretInWorkspaceEnvFiles(fqsn));
|
||||
|
||||
if (secretValue) {
|
||||
return {
|
||||
found: true,
|
||||
fqsn,
|
||||
value: secretValue,
|
||||
secretLocation: {
|
||||
secretName: fqsn.secretName,
|
||||
secretType: SecretType.LocalEnv,
|
||||
},
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private findSecretInLocalEnvFile(fqsn: FQSN): string | undefined {
|
||||
try {
|
||||
const dotEnv = getContinueDotEnv();
|
||||
return dotEnv[fqsn.secretName];
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`Error reading ~/.continue/.env file: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private async findSecretInWorkspaceEnvFiles(
|
||||
fqsn: FQSN,
|
||||
): Promise<string | undefined> {
|
||||
try {
|
||||
const workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
|
||||
for (const folder of workspaceDirs) {
|
||||
const envFilePath = joinPathsToUri(folder, ".env");
|
||||
try {
|
||||
const fileExists = await this.ide.fileExists(envFilePath);
|
||||
if (fileExists) {
|
||||
const envContent = await this.ide.readFile(envFilePath);
|
||||
const env = dotenv.parse(envContent);
|
||||
if (fqsn.secretName in env) {
|
||||
return env[fqsn.secretName];
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`Error reading workspace .env file at ${envFilePath}: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
// Continue to next workspace folder
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`Error searching workspace .env files: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> {
|
||||
if (fqsns.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const results = await this.client.resolveFQSNs(fqsns, this.orgScopeId);
|
||||
|
||||
// For any secret that isn't found, look in .env files
|
||||
for (let i = 0; i < results.length; i++) {
|
||||
if (!results[i]?.found) {
|
||||
const secretFromEnv = await this.findSecretInEnvFiles(fqsns[i]);
|
||||
if (secretFromEnv?.found) {
|
||||
results[i] = secretFromEnv;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,20 +1,18 @@
|
|||
import fs from "node:fs";
|
||||
|
||||
import {
|
||||
AssistantUnrolled,
|
||||
BLOCK_TYPES,
|
||||
ConfigResult,
|
||||
ConfigValidationError,
|
||||
FQSN,
|
||||
isAssistantUnrolledNonNullable,
|
||||
MCPServer,
|
||||
ModelRole,
|
||||
PlatformClient,
|
||||
PackageIdentifier,
|
||||
RegistryClient,
|
||||
Rule,
|
||||
SecretResult,
|
||||
unrollAssistantFromContent,
|
||||
unrollAssistant,
|
||||
validateConfigYaml,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
import {
|
||||
ContinueConfig,
|
||||
|
|
@ -39,29 +37,15 @@ import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandF
|
|||
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
|
||||
import { allTools } from "../../tools";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
import { getConfigYamlPath } from "../../util/paths";
|
||||
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
|
||||
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
||||
|
||||
import { getControlPlaneEnvSync } from "../../control-plane/env";
|
||||
import { logger } from "../../util/logger";
|
||||
import { getCleanUriPath } from "../../util/uri";
|
||||
import { getAllDotContinueYamlFiles } from "../loadLocalAssistants";
|
||||
import { LocalPlatformClient } from "./LocalPlatformClient";
|
||||
import { llmsFromModelConfig } from "./models";
|
||||
|
||||
export class LocalPlatformClient implements PlatformClient {
|
||||
constructor(
|
||||
private orgScopeId: string | null,
|
||||
private readonly client: ControlPlaneClient,
|
||||
) {}
|
||||
|
||||
async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> {
|
||||
if (fqsns.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const response = await this.client.resolveFQSNs(fqsns, this.orgScopeId);
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
|
||||
if (typeof rule === "string") {
|
||||
return {
|
||||
|
|
@ -72,7 +56,7 @@ function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
|
|||
return {
|
||||
source: "rules-block",
|
||||
rule: rule.rule,
|
||||
if: rule.if,
|
||||
globs: rule.globs,
|
||||
name: rule.name,
|
||||
};
|
||||
}
|
||||
|
|
@ -91,35 +75,70 @@ function convertYamlMcpToContinueMcp(
|
|||
};
|
||||
}
|
||||
|
||||
async function loadConfigYaml(
|
||||
rawYaml: string,
|
||||
overrideConfigYaml: AssistantUnrolled | undefined,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
orgScopeId: string | null,
|
||||
ideSettings: IdeSettings,
|
||||
): Promise<ConfigResult<AssistantUnrolled>> {
|
||||
async function loadConfigYaml(options: {
|
||||
overrideConfigYaml: AssistantUnrolled | undefined;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
orgScopeId: string | null;
|
||||
ideSettings: IdeSettings;
|
||||
ide: IDE;
|
||||
packageIdentifier: PackageIdentifier;
|
||||
}): Promise<ConfigResult<AssistantUnrolled>> {
|
||||
const {
|
||||
overrideConfigYaml,
|
||||
controlPlaneClient,
|
||||
orgScopeId,
|
||||
ideSettings,
|
||||
ide,
|
||||
packageIdentifier,
|
||||
} = options;
|
||||
|
||||
// Add local .continue blocks
|
||||
const allLocalBlocks: PackageIdentifier[] = [];
|
||||
for (const blockType of BLOCK_TYPES) {
|
||||
const localBlocks = await getAllDotContinueYamlFiles(
|
||||
ide,
|
||||
{ includeGlobal: true, includeWorkspace: true },
|
||||
blockType,
|
||||
);
|
||||
allLocalBlocks.push(
|
||||
...localBlocks.map((b) => ({
|
||||
uriType: "file" as const,
|
||||
filePath: b.path,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
const rootPath =
|
||||
packageIdentifier.uriType === "file"
|
||||
? dirname(getCleanUriPath(packageIdentifier.filePath))
|
||||
: undefined;
|
||||
|
||||
logger.info(
|
||||
`Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
|
||||
);
|
||||
|
||||
let config =
|
||||
overrideConfigYaml ??
|
||||
// This is how we allow use of blocks locally
|
||||
(await unrollAssistantFromContent(
|
||||
{
|
||||
ownerSlug: "",
|
||||
packageSlug: "",
|
||||
versionSlug: "",
|
||||
},
|
||||
rawYaml,
|
||||
new RegistryClient(
|
||||
await controlPlaneClient.getAccessToken(),
|
||||
getControlPlaneEnvSync(
|
||||
ideSettings.continueTestEnvironment,
|
||||
).CONTROL_PLANE_URL,
|
||||
),
|
||||
(await unrollAssistant(
|
||||
packageIdentifier,
|
||||
new RegistryClient({
|
||||
accessToken: await controlPlaneClient.getAccessToken(),
|
||||
apiBase: getControlPlaneEnvSync(ideSettings.continueTestEnvironment)
|
||||
.CONTROL_PLANE_URL,
|
||||
rootPath,
|
||||
}),
|
||||
{
|
||||
currentUserSlug: "",
|
||||
onPremProxyUrl: null,
|
||||
orgScopeId,
|
||||
platformClient: new LocalPlatformClient(orgScopeId, controlPlaneClient),
|
||||
platformClient: new LocalPlatformClient(
|
||||
orgScopeId,
|
||||
controlPlaneClient,
|
||||
ide,
|
||||
),
|
||||
renderSecrets: true,
|
||||
injectBlocks: allLocalBlocks,
|
||||
},
|
||||
));
|
||||
|
||||
|
|
@ -148,25 +167,27 @@ async function loadConfigYaml(
|
|||
};
|
||||
}
|
||||
|
||||
async function configYamlToContinueConfig({
|
||||
config,
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
allowFreeTrial = true,
|
||||
}: {
|
||||
async function configYamlToContinueConfig(options: {
|
||||
config: AssistantUnrolled;
|
||||
ide: IDE;
|
||||
ideSettings: IdeSettings;
|
||||
ideInfo: IdeInfo;
|
||||
uniqueId: string;
|
||||
llmLogger: ILLMLogger;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
allowFreeTrial: boolean;
|
||||
workOsAccessToken: string | undefined;
|
||||
allowFreeTrial?: boolean;
|
||||
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
|
||||
let {
|
||||
config,
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
allowFreeTrial,
|
||||
} = options;
|
||||
allowFreeTrial = allowFreeTrial ?? true;
|
||||
|
||||
const localErrors: ConfigValidationError[] = [];
|
||||
|
||||
const continueConfig: ContinueConfig = {
|
||||
|
|
@ -275,7 +296,6 @@ async function configYamlToContinueConfig({
|
|||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
config: continueConfig,
|
||||
});
|
||||
|
||||
|
|
@ -431,44 +451,39 @@ async function configYamlToContinueConfig({
|
|||
return { config: continueConfig, errors: localErrors };
|
||||
}
|
||||
|
||||
export async function loadContinueConfigFromYaml({
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
overrideConfigYaml,
|
||||
platformConfigMetadata,
|
||||
controlPlaneClient,
|
||||
configYamlPath,
|
||||
orgScopeId,
|
||||
}: {
|
||||
export async function loadContinueConfigFromYaml(options: {
|
||||
ide: IDE;
|
||||
ideSettings: IdeSettings;
|
||||
ideInfo: IdeInfo;
|
||||
uniqueId: string;
|
||||
llmLogger: ILLMLogger;
|
||||
workOsAccessToken: string | undefined;
|
||||
overrideConfigYaml: AssistantUnrolled | undefined;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
configYamlPath: string | undefined;
|
||||
orgScopeId: string | null;
|
||||
packageIdentifier: PackageIdentifier;
|
||||
}): Promise<ConfigResult<ContinueConfig>> {
|
||||
const rawYaml =
|
||||
overrideConfigYaml === undefined
|
||||
? fs.readFileSync(
|
||||
configYamlPath ?? getConfigYamlPath(ideInfo.ideType),
|
||||
"utf-8",
|
||||
)
|
||||
: "";
|
||||
const {
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
workOsAccessToken,
|
||||
overrideConfigYaml,
|
||||
controlPlaneClient,
|
||||
orgScopeId,
|
||||
packageIdentifier,
|
||||
} = options;
|
||||
|
||||
const configYamlResult = await loadConfigYaml(
|
||||
rawYaml,
|
||||
const configYamlResult = await loadConfigYaml({
|
||||
overrideConfigYaml,
|
||||
controlPlaneClient,
|
||||
orgScopeId,
|
||||
ideSettings,
|
||||
);
|
||||
ide,
|
||||
packageIdentifier,
|
||||
});
|
||||
|
||||
if (!configYamlResult.config || configYamlResult.configLoadInterrupted) {
|
||||
return {
|
||||
|
|
@ -486,8 +501,7 @@ export async function loadContinueConfigFromYaml({
|
|||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
allowFreeTrial: true,
|
||||
workOsAccessToken,
|
||||
});
|
||||
|
||||
// Apply shared config
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ import {
|
|||
} from "../..";
|
||||
import { BaseLLM } from "../../llm";
|
||||
import { LLMClasses } from "../../llm/llms";
|
||||
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
|
||||
|
||||
const AUTODETECT = "AUTODETECT";
|
||||
|
||||
|
|
@ -32,14 +31,12 @@ async function modelConfigToBaseLLM({
|
|||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
config,
|
||||
}: {
|
||||
model: ModelConfig;
|
||||
uniqueId: string;
|
||||
ideSettings: IdeSettings;
|
||||
llmLogger: ILLMLogger;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
config: ContinueConfig;
|
||||
}): Promise<BaseLLM | undefined> {
|
||||
const cls = getModelClass(model);
|
||||
|
|
@ -147,7 +144,6 @@ async function autodetectModels({
|
|||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
config,
|
||||
}: {
|
||||
llm: BaseLLM;
|
||||
|
|
@ -156,7 +152,6 @@ async function autodetectModels({
|
|||
uniqueId: string;
|
||||
ideSettings: IdeSettings;
|
||||
llmLogger: ILLMLogger;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
config: ContinueConfig;
|
||||
}): Promise<BaseLLM[]> {
|
||||
try {
|
||||
|
|
@ -177,7 +172,6 @@ async function autodetectModels({
|
|||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
config,
|
||||
});
|
||||
}),
|
||||
|
|
@ -195,7 +189,6 @@ export async function llmsFromModelConfig({
|
|||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
config,
|
||||
}: {
|
||||
model: ModelConfig;
|
||||
|
|
@ -203,7 +196,6 @@ export async function llmsFromModelConfig({
|
|||
uniqueId: string;
|
||||
ideSettings: IdeSettings;
|
||||
llmLogger: ILLMLogger;
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined;
|
||||
config: ContinueConfig;
|
||||
}): Promise<BaseLLM[]> {
|
||||
const baseLlm = await modelConfigToBaseLLM({
|
||||
|
|
@ -211,7 +203,6 @@ export async function llmsFromModelConfig({
|
|||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
config,
|
||||
});
|
||||
if (!baseLlm) {
|
||||
|
|
@ -226,7 +217,6 @@ export async function llmsFromModelConfig({
|
|||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
platformConfigMetadata,
|
||||
config,
|
||||
});
|
||||
return models;
|
||||
|
|
|
|||
118
core/core.ts
|
|
@ -408,15 +408,21 @@ export class Core {
|
|||
if (!config) {
|
||||
return [];
|
||||
}
|
||||
const items = await config.contextProviders
|
||||
?.find((provider) => provider.description.title === msg.data.title)
|
||||
?.loadSubmenuItems({
|
||||
config,
|
||||
ide: this.ide,
|
||||
fetch: (url, init) =>
|
||||
fetchwithRequestOptions(url, init, config.requestOptions),
|
||||
});
|
||||
return items || [];
|
||||
|
||||
try {
|
||||
const items = await config.contextProviders
|
||||
?.find((provider) => provider.description.title === msg.data.title)
|
||||
?.loadSubmenuItems({
|
||||
config,
|
||||
ide: this.ide,
|
||||
fetch: (url, init) =>
|
||||
fetchwithRequestOptions(url, init, config.requestOptions),
|
||||
});
|
||||
return items || [];
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return [];
|
||||
}
|
||||
});
|
||||
|
||||
on("context/getContextItems", this.getContextItems.bind(this));
|
||||
|
|
@ -665,7 +671,7 @@ export class Core {
|
|||
|
||||
on("didChangeActiveTextEditor", async ({ data: { filepath } }) => {
|
||||
try {
|
||||
const ignore = shouldIgnore(filepath, this.ide);
|
||||
const ignore = await shouldIgnore(filepath, this.ide);
|
||||
if (!ignore) {
|
||||
recentlyEditedFilesCache.set(filepath, filepath);
|
||||
}
|
||||
|
|
@ -676,59 +682,44 @@ export class Core {
|
|||
}
|
||||
});
|
||||
|
||||
on(
|
||||
"tools/call",
|
||||
async ({ data: { toolCall, selectedModelTitle }, messageId }) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Config not loaded");
|
||||
}
|
||||
on("tools/call", async ({ data: { toolCall } }) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Config not loaded");
|
||||
}
|
||||
|
||||
const tool = config.tools.find(
|
||||
(t) => t.function.name === toolCall.function.name,
|
||||
);
|
||||
const tool = config.tools.find(
|
||||
(t) => t.function.name === toolCall.function.name,
|
||||
);
|
||||
|
||||
if (!tool) {
|
||||
throw new Error(`Tool ${toolCall.function.name} not found`);
|
||||
}
|
||||
if (!tool) {
|
||||
throw new Error(`Tool ${toolCall.function.name} not found`);
|
||||
}
|
||||
|
||||
if (!config.selectedModelByRole.chat) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
if (!config.selectedModelByRole.chat) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
// Define a callback for streaming output updates
|
||||
const onPartialOutput = (params: {
|
||||
toolCallId: string;
|
||||
contextItems: ContextItem[];
|
||||
}) => {
|
||||
this.messenger.send("toolCallPartialOutput", params);
|
||||
};
|
||||
// Define a callback for streaming output updates
|
||||
const onPartialOutput = (params: {
|
||||
toolCallId: string;
|
||||
contextItems: ContextItem[];
|
||||
}) => {
|
||||
this.messenger.send("toolCallPartialOutput", params);
|
||||
};
|
||||
|
||||
const contextItems = await callTool(
|
||||
tool,
|
||||
JSON.parse(toolCall.function.arguments || "{}"),
|
||||
{
|
||||
ide: this.ide,
|
||||
llm: config.selectedModelByRole.chat,
|
||||
fetch: (url, init) =>
|
||||
fetchwithRequestOptions(url, init, config.requestOptions),
|
||||
tool,
|
||||
toolCallId: toolCall.id,
|
||||
onPartialOutput,
|
||||
},
|
||||
);
|
||||
return await callTool(tool, toolCall.function.arguments, {
|
||||
ide: this.ide,
|
||||
llm: config.selectedModelByRole.chat,
|
||||
fetch: (url, init) =>
|
||||
fetchwithRequestOptions(url, init, config.requestOptions),
|
||||
tool,
|
||||
toolCallId: toolCall.id,
|
||||
onPartialOutput,
|
||||
});
|
||||
});
|
||||
|
||||
if (tool.faviconUrl) {
|
||||
contextItems.forEach((item) => {
|
||||
item.icon = tool.faviconUrl;
|
||||
});
|
||||
}
|
||||
|
||||
return { contextItems };
|
||||
},
|
||||
);
|
||||
|
||||
on("isItemTooBig", async ({ data: { item, selectedModelTitle } }) => {
|
||||
on("isItemTooBig", async ({ data: { item } }) => {
|
||||
return this.isItemTooBig(item);
|
||||
});
|
||||
|
||||
|
|
@ -748,19 +739,16 @@ export class Core {
|
|||
|
||||
private async isItemTooBig(item: ContextItemWithId) {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
|
||||
if (!config) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const llm = (await this.configHandler.loadConfig()).config
|
||||
?.selectedModelByRole.chat;
|
||||
|
||||
|
||||
const llm = config?.selectedModelByRole.chat;
|
||||
if (!llm) {
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
const tokens = countTokens(item.content);
|
||||
const tokens = countTokens(item.content, llm.model);
|
||||
|
||||
if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) {
|
||||
return true;
|
||||
|
|
@ -832,7 +820,8 @@ export class Core {
|
|||
if (
|
||||
uri.endsWith(".continuerc.json") ||
|
||||
uri.endsWith(".prompt") ||
|
||||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE)
|
||||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
|
||||
(uri.includes(".continue") && uri.endsWith(".yaml"))
|
||||
) {
|
||||
await this.configHandler.reloadConfig();
|
||||
} else if (
|
||||
|
|
@ -926,7 +915,6 @@ export class Core {
|
|||
query: string;
|
||||
fullInput: string;
|
||||
selectedCode: RangeInFile[];
|
||||
selectedModelTitle: string;
|
||||
}>,
|
||||
) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import {
|
|||
ILLM,
|
||||
Prediction,
|
||||
RuleWithSource,
|
||||
ToolResultChatMessage,
|
||||
UserChatMessage,
|
||||
} from "../";
|
||||
import {
|
||||
|
|
@ -104,18 +105,18 @@ export async function* streamDiffLines({
|
|||
|
||||
// Rules will be included with edit prompt
|
||||
// If any rules are present this will result in using chat instead of legacy completion
|
||||
const lastUserMessage: UserChatMessage | undefined =
|
||||
const lastUserMessage =
|
||||
typeof prompt === "string"
|
||||
? {
|
||||
? ({
|
||||
role: "user",
|
||||
content: prompt,
|
||||
}
|
||||
: (findLast(prompt, (msg) => msg.role === "user") as
|
||||
| UserChatMessage
|
||||
| undefined);
|
||||
} as UserChatMessage)
|
||||
: (findLast(
|
||||
prompt,
|
||||
(msg) => msg.role === "user" || msg.role === "tool",
|
||||
) as UserChatMessage | ToolResultChatMessage | undefined);
|
||||
|
||||
const systemMessage = getSystemMessageWithRules({
|
||||
currentModel: llm.model,
|
||||
rules,
|
||||
userMessage: lastUserMessage,
|
||||
baseSystemMessage: undefined,
|
||||
|
|
|
|||
12
core/index.d.ts
vendored
|
|
@ -1,4 +1,8 @@
|
|||
import { DataDestination, ModelRole } from "@continuedev/config-yaml";
|
||||
import {
|
||||
DataDestination,
|
||||
ModelRole,
|
||||
PromptTemplates,
|
||||
} from "@continuedev/config-yaml";
|
||||
import Parser from "web-tree-sitter";
|
||||
import { LLMConfigurationStatuses } from "./llm/constants";
|
||||
import { GetGhTokenArgs } from "./protocol/ide";
|
||||
|
|
@ -428,6 +432,7 @@ export type ToolStatus =
|
|||
| "generating"
|
||||
| "generated"
|
||||
| "calling"
|
||||
| "errored"
|
||||
| "done"
|
||||
| "canceled";
|
||||
|
||||
|
|
@ -566,7 +571,7 @@ export interface LLMOptions {
|
|||
completionOptions?: CompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
template?: TemplateType;
|
||||
promptTemplates?: Record<string, PromptTemplate>;
|
||||
promptTemplates?: Partial<Record<keyof PromptTemplates, PromptTemplate>>;
|
||||
templateMessages?: (messages: ChatMessage[]) => string;
|
||||
logger?: ILLMLogger;
|
||||
llmRequestHook?: (model: string, prompt: string) => any;
|
||||
|
|
@ -1211,6 +1216,7 @@ export type EditStatus =
|
|||
| "done";
|
||||
|
||||
export type ApplyStateStatus =
|
||||
| "not-started" // Apply state created but not necessarily streaming
|
||||
| "streaming" // Changes are being applied to the file
|
||||
| "done" // All changes have been applied, awaiting user to accept/reject
|
||||
| "closed"; // All changes have been applied. Note that for new files, we immediately set the status to "closed"
|
||||
|
|
@ -1501,7 +1507,7 @@ export interface RuleWithSource {
|
|||
| "rules-block"
|
||||
| "json-systemMessage"
|
||||
| ".continuerules";
|
||||
if?: string;
|
||||
globs?: string | string[];
|
||||
rule: string;
|
||||
description?: string;
|
||||
ruleFile?: string;
|
||||
|
|
|
|||
|
|
@ -7,26 +7,6 @@ const DEFAULT_ARGS = {
|
|||
temperature: DEFAULT_TEMPERATURE,
|
||||
};
|
||||
|
||||
const GPT_4_CTX_LEN = 128_000;
|
||||
|
||||
const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = {
|
||||
"gpt-3.5-turbo": 4096,
|
||||
"gpt-3.5-turbo-0613": 4096,
|
||||
"gpt-3.5-turbo-16k": 16_384,
|
||||
"gpt-35-turbo-16k": 16_384,
|
||||
"gpt-35-turbo-0613": 4096,
|
||||
"gpt-35-turbo": 4096,
|
||||
"gpt-4": 4096,
|
||||
"gpt-4-32k": 32_000,
|
||||
"gpt-4-turbo-preview": 32_000,
|
||||
"gpt-4o": GPT_4_CTX_LEN,
|
||||
"gpt-4o-mini": GPT_4_CTX_LEN,
|
||||
"gpt-4-vision": GPT_4_CTX_LEN,
|
||||
"gpt-4-0125-preview": GPT_4_CTX_LEN,
|
||||
"gpt-4-1106-preview": GPT_4_CTX_LEN,
|
||||
};
|
||||
|
||||
const TOKEN_BUFFER_FOR_SAFETY = 350;
|
||||
const PROXY_URL = "http://localhost:65433";
|
||||
|
||||
const DEFAULT_MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers)
|
||||
|
|
@ -38,12 +18,10 @@ export enum LLMConfigurationStatuses {
|
|||
}
|
||||
|
||||
export {
|
||||
CONTEXT_LENGTH_FOR_MODEL,
|
||||
DEFAULT_ARGS,
|
||||
DEFAULT_CONTEXT_LENGTH,
|
||||
DEFAULT_MAX_BATCH_SIZE,
|
||||
DEFAULT_MAX_CHUNK_SIZE,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
PROXY_URL,
|
||||
TOKEN_BUFFER_FOR_SAFETY,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -3,15 +3,16 @@ import {
|
|||
ChatMessage,
|
||||
RuleWithSource,
|
||||
TextMessagePart,
|
||||
ToolResultChatMessage,
|
||||
UserChatMessage,
|
||||
} from "../";
|
||||
import { findLast } from "../util/findLast";
|
||||
import { normalizeToMessageParts } from "../util/messageContent";
|
||||
import { messageIsEmpty } from "./messages";
|
||||
import { isUserOrToolMsg } from "./messages";
|
||||
import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
|
||||
|
||||
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
|
||||
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L8";
|
||||
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
|
||||
|
||||
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
|
||||
<important_rules>
|
||||
|
|
@ -57,14 +58,10 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
|
|||
of changes unless the user specifically asks for code only.
|
||||
</important_rules>`;
|
||||
|
||||
const CANCELED_TOOL_CALL_MESSAGE =
|
||||
"This tool call was cancelled by the user. You should clarify next steps, as they don't wish for you to use this tool.";
|
||||
|
||||
export function constructMessages(
|
||||
history: ChatHistoryItem[],
|
||||
baseChatSystemMessage: string | undefined,
|
||||
rules: RuleWithSource[],
|
||||
modelName: string,
|
||||
): ChatMessage[] {
|
||||
const filteredHistory = history.filter(
|
||||
(item) => item.message.role !== "system",
|
||||
|
|
@ -92,26 +89,22 @@ export function constructMessages(
|
|||
...historyItem.message,
|
||||
content,
|
||||
});
|
||||
} else if (historyItem.toolCallState?.status === "canceled") {
|
||||
// Canceled tool call
|
||||
msgs.push({
|
||||
...historyItem.message,
|
||||
content: CANCELED_TOOL_CALL_MESSAGE,
|
||||
});
|
||||
} else {
|
||||
msgs.push(historyItem.message);
|
||||
}
|
||||
}
|
||||
|
||||
const userMessage = findLast(msgs, (msg) => msg.role === "user") as
|
||||
const lastUserMsg = findLast(msgs, isUserOrToolMsg) as
|
||||
| UserChatMessage
|
||||
| ToolResultChatMessage
|
||||
| undefined;
|
||||
|
||||
const systemMessage = getSystemMessageWithRules({
|
||||
baseSystemMessage: baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE,
|
||||
rules,
|
||||
userMessage,
|
||||
currentModel: modelName,
|
||||
userMessage: lastUserMsg,
|
||||
});
|
||||
|
||||
if (systemMessage.trim()) {
|
||||
msgs.unshift({
|
||||
role: "system",
|
||||
|
|
@ -119,16 +112,6 @@ export function constructMessages(
|
|||
});
|
||||
}
|
||||
|
||||
// We dispatch an empty assistant chat message to the history on submission. Don't send it
|
||||
const lastMessage = msgs.at(-1);
|
||||
if (
|
||||
lastMessage &&
|
||||
lastMessage.role === "assistant" &&
|
||||
messageIsEmpty(lastMessage)
|
||||
) {
|
||||
msgs.pop();
|
||||
}
|
||||
|
||||
// Remove the "id" from all of the messages
|
||||
return msgs.map((msg) => {
|
||||
const { id, ...rest } = msg as any;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
|
||||
|
||||
import { ChatMessage, MessageContent, MessagePart } from "../index.js";
|
||||
import { ChatMessage, MessageContent, MessagePart, Tool } from "../index.js";
|
||||
|
||||
import { renderChatMessage } from "../util/messageContent.js";
|
||||
import {
|
||||
|
|
@ -9,13 +9,13 @@ import {
|
|||
LlamaAsyncEncoder,
|
||||
} from "./asyncEncoder.js";
|
||||
import { autodetectTemplateType } from "./autodetect.js";
|
||||
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js";
|
||||
import llamaTokenizer from "./llamaTokenizer.js";
|
||||
import {
|
||||
addSpaceToAnyEmptyMessages,
|
||||
chatMessageIsEmpty,
|
||||
flattenMessages,
|
||||
messageHasToolCalls,
|
||||
isUserOrToolMsg,
|
||||
messageHasToolCallId,
|
||||
} from "./messages.js";
|
||||
interface Encoding {
|
||||
encode: Tiktoken["encode"];
|
||||
|
|
@ -124,6 +124,51 @@ function countTokens(
|
|||
}
|
||||
}
|
||||
|
||||
// https://community.openai.com/t/how-to-calculate-the-tokens-when-using-function-call/266573/10
|
||||
function countToolsTokens(tools: Tool[], modelName: string): number {
|
||||
const count = (value: string) =>
|
||||
encodingForModel(modelName).encode(value).length;
|
||||
|
||||
let numTokens = 12;
|
||||
|
||||
for (const tool of tools) {
|
||||
let functionTokens = count(tool.function.name);
|
||||
if (tool.function.description) {
|
||||
functionTokens += count(tool.function.description);
|
||||
}
|
||||
const props = tool.function.parameters?.properties;
|
||||
if (props) {
|
||||
for (const key in props) {
|
||||
functionTokens += count(key);
|
||||
const fields = props[key];
|
||||
if (fields) {
|
||||
const fieldType = fields["type"];
|
||||
const fieldDesc = fields["description"];
|
||||
const fieldEnum = fields["enum"];
|
||||
if (fieldType && typeof fieldType === "string") {
|
||||
functionTokens += 2;
|
||||
functionTokens += count(fieldType);
|
||||
}
|
||||
if (fieldDesc && typeof fieldDesc === "string") {
|
||||
functionTokens += 2;
|
||||
functionTokens += count(fieldDesc);
|
||||
}
|
||||
if (fieldEnum && Array.isArray(fieldEnum)) {
|
||||
functionTokens -= 3;
|
||||
for (const e of fieldEnum) {
|
||||
functionTokens += 3;
|
||||
functionTokens += typeof e === "string" ? count(e) : 5;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
numTokens += functionTokens;
|
||||
}
|
||||
|
||||
return numTokens + 12;
|
||||
}
|
||||
|
||||
function countChatMessageTokens(
|
||||
modelName: string,
|
||||
chatMessage: ChatMessage,
|
||||
|
|
@ -131,8 +176,38 @@ function countChatMessageTokens(
|
|||
// Doing simpler, safer version of what is here:
|
||||
// https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
|
||||
// every message follows <|im_start|>{role/name}\n{content}<|end|>\n
|
||||
const TOKENS_PER_MESSAGE: number = 4;
|
||||
return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE;
|
||||
const BASE_TOKENS = 4;
|
||||
const TOOL_CALL_EXTRA_TOKENS = 10;
|
||||
const TOOL_OUTPUT_EXTRA_TOKENS = 10;
|
||||
let tokens = BASE_TOKENS;
|
||||
|
||||
if (chatMessage.content) {
|
||||
tokens += countTokens(chatMessage.content, modelName);
|
||||
}
|
||||
|
||||
if ("toolCalls" in chatMessage && chatMessage.toolCalls) {
|
||||
for (const call of chatMessage.toolCalls) {
|
||||
tokens += TOOL_CALL_EXTRA_TOKENS;
|
||||
tokens += countTokens(JSON.stringify(call), modelName); // TODO hone this
|
||||
}
|
||||
}
|
||||
|
||||
if (chatMessage.role === "thinking") {
|
||||
if (chatMessage.redactedThinking) {
|
||||
tokens += countTokens(chatMessage.redactedThinking, modelName);
|
||||
}
|
||||
if (chatMessage.signature) {
|
||||
tokens += countTokens(chatMessage.signature, modelName);
|
||||
}
|
||||
}
|
||||
|
||||
if (chatMessage.role === "tool") {
|
||||
tokens += TOOL_OUTPUT_EXTRA_TOKENS; // safety
|
||||
if (chatMessage.toolCallId) {
|
||||
tokens += countTokens(chatMessage.toolCallId, modelName);
|
||||
}
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
function pruneLinesFromTop(
|
||||
|
|
@ -193,6 +268,20 @@ function pruneStringFromTop(
|
|||
return encoding.decode(tokens.slice(tokens.length - maxTokens));
|
||||
}
|
||||
|
||||
const MAX_TOKEN_SAFETY_BUFFER = 1000;
|
||||
const TOKEN_SAFETY_PROPORTION = 0.02;
|
||||
function getTokenCountingBufferSafety(contextLength: number) {
|
||||
return Math.min(
|
||||
MAX_TOKEN_SAFETY_BUFFER,
|
||||
contextLength * TOKEN_SAFETY_PROPORTION,
|
||||
);
|
||||
}
|
||||
|
||||
const MIN_RESPONSE_TOKENS = 1000;
|
||||
function getMinResponseTokens(maxTokens: number) {
|
||||
return Math.min(MIN_RESPONSE_TOKENS, maxTokens);
|
||||
}
|
||||
|
||||
function pruneRawPromptFromTop(
|
||||
modelName: string,
|
||||
contextLength: number,
|
||||
|
|
@ -200,184 +289,36 @@ function pruneRawPromptFromTop(
|
|||
tokensForCompletion: number,
|
||||
): string {
|
||||
const maxTokens =
|
||||
contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY;
|
||||
contextLength -
|
||||
tokensForCompletion -
|
||||
getTokenCountingBufferSafety(contextLength);
|
||||
return pruneStringFromTop(modelName, maxTokens, prompt);
|
||||
}
|
||||
|
||||
function pruneRawPromptFromBottom(
|
||||
modelName: string,
|
||||
contextLength: number,
|
||||
prompt: string,
|
||||
tokensForCompletion: number,
|
||||
): string {
|
||||
const maxTokens =
|
||||
contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY;
|
||||
return pruneStringFromBottom(modelName, maxTokens, prompt);
|
||||
}
|
||||
|
||||
function summarize(message: ChatMessage): string {
|
||||
return `${renderChatMessage(message).substring(0, 100)}...`;
|
||||
}
|
||||
|
||||
function pruneChatHistory(
|
||||
modelName: string,
|
||||
msgs: ChatMessage[],
|
||||
contextLength: number,
|
||||
tokensForCompletion: number,
|
||||
): ChatMessage[] {
|
||||
// Move system message to 2nd to last to give it priority
|
||||
const systemMessage = msgs.find((msg) => msg.role === "system");
|
||||
const chatHistory: ChatMessage[] = msgs.filter(
|
||||
(msg) => msg.role !== "system",
|
||||
);
|
||||
if (systemMessage) {
|
||||
chatHistory.splice(-1, 0, systemMessage);
|
||||
}
|
||||
|
||||
let totalTokens =
|
||||
tokensForCompletion +
|
||||
chatHistory.reduce((acc, message) => {
|
||||
return acc + countChatMessageTokens(modelName, message);
|
||||
}, 0);
|
||||
|
||||
// 0. Prune any messages that take up more than 1/3 of the context length
|
||||
const zippedMessagesAndTokens: [ChatMessage, number][] = [];
|
||||
|
||||
// Zipped ChatMessage with its token counts
|
||||
chatHistory.forEach((message) => {
|
||||
const zippedItem: [ChatMessage, number] = [
|
||||
message,
|
||||
countTokens(message.content, modelName),
|
||||
];
|
||||
zippedMessagesAndTokens.push(zippedItem);
|
||||
});
|
||||
|
||||
const zippedLongerThanOneThird = zippedMessagesAndTokens.filter(
|
||||
([_message, tokens]: [ChatMessage, number]) => tokens > contextLength / 3,
|
||||
);
|
||||
|
||||
zippedLongerThanOneThird.sort(
|
||||
(
|
||||
[_messageA, tokensA]: [ChatMessage, number],
|
||||
[_messageB, tokensB]: [ChatMessage, number],
|
||||
) => {
|
||||
return tokensB - tokensA;
|
||||
},
|
||||
);
|
||||
|
||||
const longerThanOneThird = zippedLongerThanOneThird.map(
|
||||
([message, _token]: [ChatMessage, number]) => message,
|
||||
);
|
||||
const distanceFromThird = zippedLongerThanOneThird.map(
|
||||
([_message, token]: [ChatMessage, number]) => token - contextLength / 3,
|
||||
);
|
||||
|
||||
for (let i = 0; i < longerThanOneThird.length; i++) {
|
||||
// Prune line-by-line from the top
|
||||
const message = longerThanOneThird[i];
|
||||
const content = renderChatMessage(message);
|
||||
const deltaNeeded = totalTokens - contextLength;
|
||||
const delta = Math.min(deltaNeeded, distanceFromThird[i]);
|
||||
message.content = pruneStringFromTop(
|
||||
modelName,
|
||||
countTokens(message.content, modelName) - delta,
|
||||
content,
|
||||
);
|
||||
totalTokens -= delta;
|
||||
}
|
||||
|
||||
// 1. Replace beyond last 5 messages with summary
|
||||
let i = 0;
|
||||
while (totalTokens > contextLength && i < chatHistory.length - 5) {
|
||||
const message = chatHistory[i];
|
||||
totalTokens -= countTokens(message.content, modelName);
|
||||
totalTokens += countTokens(summarize(message), modelName);
|
||||
message.content = summarize(message);
|
||||
i++;
|
||||
}
|
||||
|
||||
// 2. Remove entire messages until the last 5
|
||||
while (chatHistory.length > 5 && totalTokens > contextLength) {
|
||||
const message = chatHistory.shift()!;
|
||||
totalTokens -= countTokens(message.content, modelName);
|
||||
}
|
||||
|
||||
// 3. Truncate message in the last 5, except last 1
|
||||
i = 0;
|
||||
while (
|
||||
totalTokens > contextLength &&
|
||||
chatHistory.length > 0 &&
|
||||
i < chatHistory.length - 1
|
||||
) {
|
||||
const message = chatHistory[i];
|
||||
totalTokens -= countTokens(message.content, modelName);
|
||||
totalTokens += countTokens(summarize(message), modelName);
|
||||
message.content = summarize(message);
|
||||
i++;
|
||||
}
|
||||
|
||||
// 4. Remove entire messages in the last 5, except last 1
|
||||
while (totalTokens > contextLength && chatHistory.length > 1) {
|
||||
// If tool call/response detected prune both (can't have response with no call)
|
||||
// TODO prune lines from tool response before pruning both messages
|
||||
if (
|
||||
chatHistory.length > 2 &&
|
||||
messageHasToolCalls(chatHistory[0]) &&
|
||||
chatHistory[1].role === "tool"
|
||||
) {
|
||||
const firstMessage = chatHistory.shift()!;
|
||||
const secondMessage = chatHistory.shift()!;
|
||||
totalTokens -= countTokens(firstMessage.content, modelName);
|
||||
totalTokens -= countTokens(secondMessage.content, modelName);
|
||||
} else {
|
||||
const message = chatHistory.shift()!;
|
||||
totalTokens -= countTokens(message.content, modelName);
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Truncate last message
|
||||
if (totalTokens > contextLength && chatHistory.length > 0) {
|
||||
const message = chatHistory[0];
|
||||
message.content = pruneRawPromptFromTop(
|
||||
modelName,
|
||||
contextLength,
|
||||
renderChatMessage(message),
|
||||
tokensForCompletion,
|
||||
);
|
||||
totalTokens = contextLength;
|
||||
}
|
||||
|
||||
// put system message back if applicable
|
||||
if (
|
||||
chatHistory.length > 1 &&
|
||||
chatHistory[chatHistory.length - 2].role === "system"
|
||||
) {
|
||||
const movedSystemMessage = chatHistory.splice(-2, 1)[0];
|
||||
chatHistory.unshift(movedSystemMessage);
|
||||
}
|
||||
|
||||
return chatHistory;
|
||||
}
|
||||
|
||||
/*
|
||||
Goal: reconcile chat messages with available context length
|
||||
Guidelines:
|
||||
- Always keep last user message, system message, and tools
|
||||
- Never allow tool output without the corresponding tool call
|
||||
- Remove older messages first
|
||||
*/
|
||||
function compileChatMessages({
|
||||
modelName,
|
||||
msgs,
|
||||
contextLength,
|
||||
maxTokens,
|
||||
supportsImages,
|
||||
tools,
|
||||
}: {
|
||||
modelName: string;
|
||||
msgs: ChatMessage[];
|
||||
contextLength: number;
|
||||
maxTokens: number;
|
||||
supportsImages: boolean;
|
||||
tools?: Tool[];
|
||||
}): ChatMessage[] {
|
||||
let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m }));
|
||||
|
||||
msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg));
|
||||
|
||||
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
|
||||
|
||||
// If images not supported, convert MessagePart[] to string
|
||||
if (!supportsImages) {
|
||||
for (const msg of msgsCopy) {
|
||||
|
|
@ -388,15 +329,118 @@ function compileChatMessages({
|
|||
}
|
||||
}
|
||||
|
||||
const history = pruneChatHistory(
|
||||
modelName,
|
||||
msgsCopy,
|
||||
contextLength,
|
||||
maxTokens + TOKEN_BUFFER_FOR_SAFETY,
|
||||
);
|
||||
// Extract system message
|
||||
const systemMsg = msgsCopy.find((msg) => msg.role === "system");
|
||||
msgsCopy = msgsCopy.filter((msg) => msg.role !== "system");
|
||||
|
||||
const flattenedHistory = flattenMessages(history);
|
||||
// Remove any empty messages or non-user/tool trailing messages
|
||||
msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg));
|
||||
|
||||
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
|
||||
|
||||
while (msgsCopy.length > 1) {
|
||||
if (isUserOrToolMsg(msgsCopy.at(-1))) {
|
||||
break;
|
||||
}
|
||||
msgsCopy.pop();
|
||||
}
|
||||
|
||||
const lastUserOrToolMsg = msgsCopy.pop();
|
||||
if (!lastUserOrToolMsg || !isUserOrToolMsg(lastUserOrToolMsg)) {
|
||||
throw new Error("Error parsing chat history: no user/tool message found"); // should never happen
|
||||
}
|
||||
|
||||
let lastToolCallsMsg: ChatMessage | undefined = undefined;
|
||||
if (lastUserOrToolMsg.role === "tool") {
|
||||
lastToolCallsMsg = msgsCopy.pop();
|
||||
if (!messageHasToolCallId(lastToolCallsMsg, lastUserOrToolMsg.toolCallId)) {
|
||||
throw new Error(
|
||||
`Error parsing chat history: tool call found to match tool output for id ${lastUserOrToolMsg.toolCallId}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let lastMessagesTokens = countChatMessageTokens(modelName, lastUserOrToolMsg);
|
||||
if (lastToolCallsMsg) {
|
||||
lastMessagesTokens += countChatMessageTokens(modelName, lastToolCallsMsg);
|
||||
}
|
||||
|
||||
// System message
|
||||
let systemMsgTokens = 0;
|
||||
if (systemMsg) {
|
||||
systemMsgTokens = countChatMessageTokens(modelName, systemMsg);
|
||||
}
|
||||
|
||||
// Tools
|
||||
let toolTokens = 0;
|
||||
if (tools) {
|
||||
toolTokens = countToolsTokens(tools, modelName);
|
||||
}
|
||||
|
||||
const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength);
|
||||
const minOutputTokens = getMinResponseTokens(maxTokens);
|
||||
|
||||
let inputTokensAvailable = contextLength;
|
||||
|
||||
// Leave space for output/safety
|
||||
inputTokensAvailable -= countingSafetyBuffer;
|
||||
inputTokensAvailable -= minOutputTokens;
|
||||
|
||||
// Non-negotiable messages
|
||||
inputTokensAvailable -= toolTokens;
|
||||
inputTokensAvailable -= systemMsgTokens;
|
||||
inputTokensAvailable -= lastMessagesTokens;
|
||||
|
||||
// Make sure there's enough context for the non-excludable items
|
||||
if (inputTokensAvailable < 0) {
|
||||
throw new Error(
|
||||
`Not enough context available to include the system message, last user message, and tools.
|
||||
There must be at least ${minOutputTokens} tokens remaining for output.
|
||||
Request had the following token counts:
|
||||
- contextLength: ${contextLength}
|
||||
- counting safety buffer: ${countingSafetyBuffer}
|
||||
- tools: ~${toolTokens}
|
||||
- system message: ~${systemMsgTokens}
|
||||
- last user or tool + tool call message tokens: ~${lastMessagesTokens}
|
||||
- max output tokens: ${maxTokens}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Now remove messages till we're under the limit
|
||||
let currentTotal = 0;
|
||||
const historyWithTokens = msgsCopy.map((message) => {
|
||||
const tokens = countChatMessageTokens(modelName, message);
|
||||
currentTotal += tokens;
|
||||
return {
|
||||
...message,
|
||||
tokens,
|
||||
};
|
||||
});
|
||||
|
||||
while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) {
|
||||
const message = historyWithTokens.shift()!;
|
||||
currentTotal -= message.tokens;
|
||||
|
||||
// At this point make sure no latent tool response without corresponding call
|
||||
while (historyWithTokens[0]?.role === "tool") {
|
||||
const message = historyWithTokens.shift()!;
|
||||
currentTotal -= message.tokens;
|
||||
}
|
||||
}
|
||||
|
||||
// Now reassemble
|
||||
const reassembled: ChatMessage[] = [];
|
||||
if (systemMsg) {
|
||||
reassembled.push(systemMsg);
|
||||
}
|
||||
reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest));
|
||||
if (lastToolCallsMsg) {
|
||||
reassembled.push(lastToolCallsMsg);
|
||||
}
|
||||
reassembled.push(lastUserOrToolMsg);
|
||||
|
||||
// Flatten the messages (combines adjacent similar messages)
|
||||
const flattenedHistory = flattenMessages(reassembled);
|
||||
return flattenedHistory;
|
||||
}
|
||||
|
||||
|
|
@ -404,7 +448,6 @@ export {
|
|||
compileChatMessages,
|
||||
countTokens,
|
||||
countTokensAsync,
|
||||
flattenMessages,
|
||||
pruneLinesFromBottom,
|
||||
pruneLinesFromTop,
|
||||
pruneRawPromptFromTop,
|
||||
|
|
|
|||
|
|
@ -40,7 +40,6 @@ import {
|
|||
modelSupportsImages,
|
||||
} from "./autodetect.js";
|
||||
import {
|
||||
CONTEXT_LENGTH_FOR_MODEL,
|
||||
DEFAULT_ARGS,
|
||||
DEFAULT_CONTEXT_LENGTH,
|
||||
DEFAULT_MAX_BATCH_SIZE,
|
||||
|
|
@ -281,28 +280,6 @@ export abstract class BaseLLM implements ILLM {
|
|||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
private _compileChatMessages(
|
||||
options: CompletionOptions,
|
||||
messages: ChatMessage[],
|
||||
) {
|
||||
let contextLength = this.contextLength;
|
||||
if (
|
||||
options.model !== this.model &&
|
||||
options.model in CONTEXT_LENGTH_FOR_MODEL
|
||||
) {
|
||||
contextLength =
|
||||
CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH;
|
||||
}
|
||||
|
||||
return compileChatMessages({
|
||||
modelName: options.model,
|
||||
msgs: messages,
|
||||
contextLength,
|
||||
maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
supportsImages: this.supportsImages(),
|
||||
});
|
||||
}
|
||||
|
||||
private _templatePromptLikeMessages(prompt: string): string {
|
||||
if (!this.templateMessages) {
|
||||
return prompt;
|
||||
|
|
@ -879,7 +856,14 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
completionOptions = this._modifyCompletionOptions(completionOptions);
|
||||
|
||||
const messages = this._compileChatMessages(completionOptions, _messages);
|
||||
const messages = compileChatMessages({
|
||||
modelName: completionOptions.model,
|
||||
msgs: _messages,
|
||||
contextLength: this.contextLength,
|
||||
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
supportsImages: this.supportsImages(),
|
||||
tools: options.tools,
|
||||
});
|
||||
|
||||
const prompt = this.templateMessages
|
||||
? this.templateMessages(messages)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ChatMessage } from "..";
|
||||
import { flattenMessages } from "./countTokens";
|
||||
import { flattenMessages } from "./messages";
|
||||
|
||||
describe("flattenMessages", () => {
|
||||
it("should return an empty array when given an empty array", () => {
|
||||
|
|
|
|||
|
|
@ -49,6 +49,31 @@ export function addSpaceToAnyEmptyMessages(
|
|||
});
|
||||
}
|
||||
|
||||
export function isUserOrToolMsg(msg: ChatMessage | undefined): boolean {
|
||||
if (!msg) {
|
||||
return false;
|
||||
}
|
||||
return msg.role === "user" || msg.role === "tool";
|
||||
}
|
||||
|
||||
export function isToolMessageForId(
|
||||
msg: ChatMessage | undefined,
|
||||
toolCallId: string,
|
||||
): boolean {
|
||||
return !!msg && msg.role === "tool" && msg.toolCallId === toolCallId;
|
||||
}
|
||||
|
||||
export function messageHasToolCallId(
|
||||
msg: ChatMessage | undefined,
|
||||
toolCallId: string,
|
||||
): boolean {
|
||||
return (
|
||||
!!msg &&
|
||||
msg.role === "assistant" &&
|
||||
!!msg.toolCalls?.find((call) => call.id === toolCallId)
|
||||
);
|
||||
}
|
||||
|
||||
export function chatMessageIsEmpty(message: ChatMessage): boolean {
|
||||
switch (message.role) {
|
||||
case "system":
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ export function toChatMessage(
|
|||
type: toolCall.type!,
|
||||
function: {
|
||||
name: toolCall.function?.name!,
|
||||
arguments: toolCall.function?.arguments!,
|
||||
arguments: toolCall.function?.arguments! || "{}",
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
|
|
|||
201
core/llm/rules/getSystemMessageWithRules.test.ts
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
import { RuleWithSource, UserChatMessage } from "../..";
|
||||
import { getSystemMessageWithRules } from "./getSystemMessageWithRules";
|
||||
|
||||
describe("getSystemMessageWithRules", () => {
|
||||
const baseSystemMessage = "Base system message";
|
||||
const tsRule: RuleWithSource = {
|
||||
name: "TypeScript Rule",
|
||||
rule: "Follow TypeScript best practices",
|
||||
globs: "**/*.ts?(x)",
|
||||
source: "rules-block",
|
||||
};
|
||||
|
||||
// Rule without pattern (always active)
|
||||
const generalRule: RuleWithSource = {
|
||||
name: "General Rule",
|
||||
rule: "Always write clear comments",
|
||||
source: "rules-block",
|
||||
};
|
||||
|
||||
// Rule with a different pattern
|
||||
const pythonRule: RuleWithSource = {
|
||||
name: "Python Rule",
|
||||
rule: "Follow PEP 8 guidelines",
|
||||
globs: "**/*.py",
|
||||
source: "rules-block",
|
||||
};
|
||||
|
||||
it("should not include pattern-matched rules when no file paths are mentioned", () => {
|
||||
const result = getSystemMessageWithRules({
|
||||
baseSystemMessage,
|
||||
userMessage: undefined,
|
||||
rules: [tsRule],
|
||||
});
|
||||
|
||||
expect(result).toBe(baseSystemMessage);
|
||||
});
|
||||
|
||||
it("should include general rules (without matches) regardless of file paths", () => {
|
||||
const result = getSystemMessageWithRules({
|
||||
baseSystemMessage,
|
||||
userMessage: undefined,
|
||||
rules: [generalRule],
|
||||
});
|
||||
|
||||
expect(result).toBe(`${baseSystemMessage}\n\n${generalRule.rule}`);
|
||||
});
|
||||
|
||||
it("should include only matching rules based on file paths", () => {
|
||||
const userMessage: UserChatMessage = {
|
||||
role: "user",
|
||||
content:
|
||||
"```tsx Component.tsx\nexport const Component = () => <div>Hello</div>;\n```",
|
||||
};
|
||||
|
||||
const result = getSystemMessageWithRules({
|
||||
baseSystemMessage,
|
||||
userMessage,
|
||||
rules: [tsRule, pythonRule, generalRule],
|
||||
});
|
||||
|
||||
// Should include TS rule and general rule, but not Python rule
|
||||
const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${generalRule.rule}`;
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
it("should include multiple matching rules", () => {
|
||||
const userMessage: UserChatMessage = {
|
||||
role: "user",
|
||||
content:
|
||||
"```tsx Component.tsx\nexport const Component = () => <div>Hello</div>;\n```\n```python test.py\nprint('hello')\n```",
|
||||
};
|
||||
|
||||
const result = getSystemMessageWithRules({
|
||||
baseSystemMessage,
|
||||
userMessage,
|
||||
rules: [tsRule, pythonRule, generalRule],
|
||||
});
|
||||
|
||||
// Should include all rules
|
||||
const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`;
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
it("should include only general rules when no paths match pattern-specific rules", () => {
|
||||
const userMessage: UserChatMessage = {
|
||||
role: "user",
|
||||
content: "```ruby test.rb\nputs 'hello'\n```",
|
||||
};
|
||||
|
||||
const result = getSystemMessageWithRules({
|
||||
baseSystemMessage,
|
||||
userMessage,
|
||||
rules: [tsRule, pythonRule, generalRule],
|
||||
});
|
||||
|
||||
// Should only include the general rule
|
||||
const expected = `${baseSystemMessage}\n\n${generalRule.rule}`;
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
it("should NOT match with comma-separated glob patterns", () => {
|
||||
const userMessage: UserChatMessage = {
|
||||
role: "user",
|
||||
content:
|
||||
"```ts src/main.ts\nconsole.log('hello');\n```\n```ts tests/example.test.ts\ntest('should work', () => {});\n```",
|
||||
};
|
||||
|
||||
// Rule with comma-separated glob patterns
|
||||
const commaRule: RuleWithSource = {
|
||||
name: "TypeScript Standards",
|
||||
rule: "Use TypeScript best practices for comma-separated globs",
|
||||
globs: "src/**/*.ts, tests/**/*.ts",
|
||||
source: "rules-block",
|
||||
};
|
||||
|
||||
const result = getSystemMessageWithRules({
|
||||
baseSystemMessage,
|
||||
userMessage,
|
||||
rules: [commaRule],
|
||||
});
|
||||
|
||||
// With the current implementation, the comma-separated pattern is treated as a single string,
|
||||
// so it won't match any of the file paths (minimatch doesn't support comma-separated patterns)
|
||||
expect(result).toBe(baseSystemMessage);
|
||||
});
|
||||
|
||||
it("should match with an array of glob patterns", () => {
|
||||
const userMessage: UserChatMessage = {
|
||||
role: "user",
|
||||
content:
|
||||
"```ts src/main.ts\nconsole.log('hello');\n```\n```ts tests/example.test.ts\ntest('should work', () => {});\n```\n```ts config/settings.ts\nconst config = {};\n```",
|
||||
};
|
||||
|
||||
// Rule with an array of glob patterns
|
||||
const arrayGlobRule: RuleWithSource = {
|
||||
name: "TypeScript Standards",
|
||||
rule: "Use TypeScript best practices for array globs",
|
||||
globs: ["src/**/*.ts", "tests/**/*.ts"],
|
||||
source: "rules-block",
|
||||
};
|
||||
|
||||
const result = getSystemMessageWithRules({
|
||||
baseSystemMessage,
|
||||
userMessage,
|
||||
rules: [arrayGlobRule],
|
||||
});
|
||||
|
||||
// With our new implementation, the array of patterns should match both src/main.ts and tests/example.test.ts
|
||||
expect(result).toBe(`${baseSystemMessage}\n\n${arrayGlobRule.rule}`);
|
||||
});
|
||||
|
||||
it("should match only patterns in the array", () => {
|
||||
const userMessage: UserChatMessage = {
|
||||
role: "user",
|
||||
content:
|
||||
"```ts src/main.ts\nconsole.log('hello');\n```\n```ts config/settings.ts\nconst config = {};\n```",
|
||||
};
|
||||
|
||||
// Rule with an array of glob patterns
|
||||
const arrayGlobRule: RuleWithSource = {
|
||||
name: "TypeScript Standards",
|
||||
rule: "Use TypeScript best practices for array globs",
|
||||
globs: ["src/**/*.ts", "tests/**/*.ts"],
|
||||
source: "rules-block",
|
||||
};
|
||||
|
||||
const result = getSystemMessageWithRules({
|
||||
baseSystemMessage,
|
||||
userMessage,
|
||||
rules: [arrayGlobRule],
|
||||
});
|
||||
|
||||
// Should match src/main.ts but not config/settings.ts
|
||||
expect(result).toBe(`${baseSystemMessage}\n\n${arrayGlobRule.rule}`);
|
||||
});
|
||||
|
||||
it("should not match any when no patterns in the array match", () => {
|
||||
const userMessage: UserChatMessage = {
|
||||
role: "user",
|
||||
content:
|
||||
"```ts config/settings.ts\nconst config = {};\n```\n```ruby test.rb\nputs 'hello'\n```",
|
||||
};
|
||||
|
||||
// Rule with an array of glob patterns
|
||||
const arrayGlobRule: RuleWithSource = {
|
||||
name: "TypeScript Standards",
|
||||
rule: "Use TypeScript best practices for array globs",
|
||||
globs: ["src/**/*.ts", "tests/**/*.ts"],
|
||||
source: "rules-block",
|
||||
};
|
||||
|
||||
const result = getSystemMessageWithRules({
|
||||
baseSystemMessage,
|
||||
userMessage,
|
||||
rules: [arrayGlobRule],
|
||||
});
|
||||
|
||||
// Should not match any file paths
|
||||
expect(result).toBe(baseSystemMessage);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,32 +1,52 @@
|
|||
import { RuleWithSource, UserChatMessage } from "../..";
|
||||
import { minimatch } from "minimatch";
|
||||
import { RuleWithSource, ToolResultChatMessage, UserChatMessage } from "../..";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
|
||||
import { isRuleActive } from "./isRuleActive";
|
||||
|
||||
/**
|
||||
* Checks if a path matches any of the provided globs
|
||||
*/
|
||||
const matchesGlobs = (
|
||||
path: string,
|
||||
globs: string | string[] | undefined,
|
||||
): boolean => {
|
||||
if (!globs) return true;
|
||||
|
||||
if (typeof globs === "string") {
|
||||
return minimatch(path, globs);
|
||||
}
|
||||
|
||||
if (Array.isArray(globs)) {
|
||||
return globs.some((glob) => minimatch(path, glob));
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
export const getSystemMessageWithRules = ({
|
||||
baseSystemMessage,
|
||||
userMessage,
|
||||
rules,
|
||||
currentModel,
|
||||
}: {
|
||||
baseSystemMessage?: string;
|
||||
userMessage: UserChatMessage | undefined;
|
||||
userMessage: UserChatMessage | ToolResultChatMessage | undefined;
|
||||
rules: RuleWithSource[];
|
||||
currentModel: string;
|
||||
}) => {
|
||||
const filePathsFromMessage = userMessage
|
||||
? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
|
||||
: [];
|
||||
|
||||
let systemMessage = baseSystemMessage ?? "";
|
||||
|
||||
for (const rule of rules) {
|
||||
if (
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: filePathsFromMessage,
|
||||
currentModel,
|
||||
})
|
||||
) {
|
||||
// A rule is active if it has no globs (applies to all files)
|
||||
// or if at least one file path matches its globs
|
||||
const hasNoGlobs = !rule.globs;
|
||||
const matchesAnyFilePath = filePathsFromMessage.some((path) =>
|
||||
matchesGlobs(path, rule.globs),
|
||||
);
|
||||
|
||||
if (hasNoGlobs || matchesAnyFilePath) {
|
||||
systemMessage += `\n\n${rule.rule}`;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,61 +0,0 @@
|
|||
import { RuleWithSource } from "../..";
|
||||
import { isRuleActive } from "./isRuleActive";
|
||||
|
||||
describe("isRuleActive", () => {
|
||||
const rule: RuleWithSource = {
|
||||
name: "My Rule",
|
||||
rule: "Do no harm",
|
||||
if: '${{ contains(current.model.model, "claude-3-7-sonnet") and glob("*.tsx") }}',
|
||||
source: "rules-block",
|
||||
};
|
||||
|
||||
it("should return false when activePaths is empty", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: [],
|
||||
currentModel: "claude-3-7-sonnet",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false when no matching paths exist", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: ["test.py", "main.js"],
|
||||
currentModel: "claude-3-7-sonnet",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should return true when both conditions are met", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: ["Component.tsx", "main.js"],
|
||||
currentModel: "claude-3-7-sonnet",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false when only glob matches but model doesn't", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: ["Component.tsx"],
|
||||
currentModel: "gpt-4",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false when model matches but glob doesn't", () => {
|
||||
expect(
|
||||
isRuleActive({
|
||||
rule,
|
||||
activePaths: ["Component.ts"],
|
||||
currentModel: "claude-3-7-sonnet",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
import { compileExpression } from "filtrex";
|
||||
import { minimatch } from "minimatch";
|
||||
import { RuleWithSource } from "../..";
|
||||
|
||||
const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/;
|
||||
|
||||
const createGlobFunction = (activePaths: string[]) => {
|
||||
return (pattern: string) => {
|
||||
const result = activePaths.some((path) => minimatch(path, pattern));
|
||||
return result;
|
||||
};
|
||||
};
|
||||
|
||||
const contains = (str: string, searchStr: string): boolean => {
|
||||
return str.includes(searchStr);
|
||||
};
|
||||
|
||||
const evaluateIf = ({
|
||||
condition,
|
||||
activePaths,
|
||||
currentModel,
|
||||
}: {
|
||||
condition: string;
|
||||
activePaths: string[];
|
||||
currentModel: string;
|
||||
}) => {
|
||||
const expression = condition.match(TEMPLATE_VAR_REGEX)?.[1]?.trim();
|
||||
if (!expression) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
const evaluate = compileExpression(expression, {
|
||||
extraFunctions: {
|
||||
glob: createGlobFunction(activePaths),
|
||||
contains,
|
||||
},
|
||||
constants: {
|
||||
"current.model.model": currentModel,
|
||||
},
|
||||
});
|
||||
|
||||
return evaluate({});
|
||||
} catch (error) {
|
||||
console.error("Error evaluating rule condition:", error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const isRuleActive = ({
|
||||
rule,
|
||||
activePaths,
|
||||
currentModel,
|
||||
}: {
|
||||
rule: RuleWithSource;
|
||||
activePaths: string[];
|
||||
currentModel: string;
|
||||
}): boolean => {
|
||||
if (rule.if) {
|
||||
return evaluateIf({ condition: rule.if, activePaths, currentModel });
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
|
@ -31,6 +31,13 @@ export const PROVIDER_TOOL_SUPPORT: Record<
|
|||
return true;
|
||||
}
|
||||
},
|
||||
azure: (model) => {
|
||||
if (
|
||||
model.toLowerCase().startsWith("gpt-4") ||
|
||||
model.toLowerCase().startsWith("o3")
|
||||
) return true;
|
||||
return false;
|
||||
},
|
||||
openai: (model) => {
|
||||
// https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling
|
||||
if (
|
||||
|
|
|
|||
228
core/package-lock.json
generated
|
|
@ -16,7 +16,7 @@
|
|||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.18",
|
||||
"@continuedev/openai-adapters": "^1.0.19",
|
||||
"@modelcontextprotocol/sdk": "^1.5.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
|
|
@ -71,6 +71,7 @@
|
|||
"web-tree-sitter": "^0.21.0",
|
||||
"win-ca": "^3.5.1",
|
||||
"wink-nlp-utils": "^2.1.0",
|
||||
"winston": "^3.17.0",
|
||||
"workerpool": "^9.1.3",
|
||||
"yaml": "^2.4.2",
|
||||
"zod": "^3.24.2"
|
||||
|
|
@ -105,7 +106,7 @@
|
|||
"typescript": "^5.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.11.0"
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
},
|
||||
"../../../../../documents/code/continuedev/continue/packages/config-yaml": {
|
||||
|
|
@ -2902,6 +2903,14 @@
|
|||
"node": ">=14.21.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@colors/colors": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.6.0.tgz",
|
||||
"integrity": "sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==",
|
||||
"engines": {
|
||||
"node": ">=0.1.90"
|
||||
}
|
||||
},
|
||||
"node_modules/@continuedev/config-types": {
|
||||
"version": "1.0.14",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.14.tgz",
|
||||
|
|
@ -2932,31 +2941,42 @@
|
|||
"integrity": "sha512-/htL7p4li3zQSwn9bXkI23WRpZNklWTPzRSSG3Fd5gvYW8cizjhlf7OzeDdKxBfi1S0lpqMm0VwHlx3KjMKLpw=="
|
||||
},
|
||||
"node_modules/@continuedev/openai-adapters": {
|
||||
"version": "1.0.18",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.18.tgz",
|
||||
"integrity": "sha512-VkYNhW+XKVXnn5FTLCGoJkcejkDWSCUvvIS6WnYusmS1+W5MJBFZQ5q6O/WA17U0UF9Xou81RWfCltYs4fXnyQ==",
|
||||
"version": "1.0.19",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.19.tgz",
|
||||
"integrity": "sha512-9bfgTHPThRZAIn5T/zaWvKhMgVDFgpP3zr9DIkBT5THRNIrbbWd6VrguNEp9ASlX85ohNiXnk+jiC/FfFcH++w==",
|
||||
"dependencies": {
|
||||
"@azure/openai": "^1.0.0-beta.12",
|
||||
"@continuedev/config-types": "^1.0.5",
|
||||
"@continuedev/config-yaml": "^1.0.51",
|
||||
"@continuedev/fetch": "^1.0.3",
|
||||
"dotenv": "^16.5.0",
|
||||
"json-schema": "^0.4.0",
|
||||
"node-fetch": "^3.3.2",
|
||||
"openai": "^4.76.0",
|
||||
"uuid": "^11.1.0",
|
||||
"zod": "^3.24.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@continuedev/openai-adapters/node_modules/@continuedev/config-yaml": {
|
||||
"version": "1.0.86",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.86.tgz",
|
||||
"integrity": "sha512-X0H1iPunFcqxgTcoS87EvbqNHjfkfidWt8rQ2CU5A8iBzPSDI/jdkok0Bm0MjgzgZuXbR6GxvwMcZcOTiFw1nA==",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
"yaml": "^2.6.1",
|
||||
"zod": "^3.24.2"
|
||||
},
|
||||
"node_modules/@continuedev/openai-adapters/node_modules/uuid": {
|
||||
"version": "11.1.0",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz",
|
||||
"integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==",
|
||||
"funding": [
|
||||
"https://github.com/sponsors/broofa",
|
||||
"https://github.com/sponsors/ctavan"
|
||||
],
|
||||
"bin": {
|
||||
"config-yaml": "dist/cli.js"
|
||||
"uuid": "dist/esm/bin/uuid"
|
||||
}
|
||||
},
|
||||
"node_modules/@dabh/diagnostics": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.3.tgz",
|
||||
"integrity": "sha512-hrlQOIi7hAfzsMqlGSFyVucrx38O+j6wiGOf//H2ecvIEqYN4ADBSS2iLMh5UFyDunCNniUIPk/q3riFv45xRA==",
|
||||
"dependencies": {
|
||||
"colorspace": "1.1.x",
|
||||
"enabled": "2.0.x",
|
||||
"kuler": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-arm64": {
|
||||
|
|
@ -4983,6 +5003,11 @@
|
|||
"integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@types/triple-beam": {
|
||||
"version": "1.3.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz",
|
||||
"integrity": "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw=="
|
||||
},
|
||||
"node_modules/@types/uuid": {
|
||||
"version": "9.0.8",
|
||||
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.8.tgz",
|
||||
|
|
@ -5629,8 +5654,7 @@
|
|||
"node_modules/async": {
|
||||
"version": "3.2.6",
|
||||
"resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz",
|
||||
"integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",
|
||||
"dev": true
|
||||
"integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA=="
|
||||
},
|
||||
"node_modules/async-mutex": {
|
||||
"version": "0.5.0",
|
||||
|
|
@ -6453,6 +6477,37 @@
|
|||
"color-support": "bin.js"
|
||||
}
|
||||
},
|
||||
"node_modules/colorspace": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/colorspace/-/colorspace-1.1.4.tgz",
|
||||
"integrity": "sha512-BgvKJiuVu1igBUF2kEjRCZXol6wiiGbY5ipL/oVPwm0BL9sIpMIzM8IK7vwuxIIzOXMV3Ey5w+vxhm0rR/TN8w==",
|
||||
"dependencies": {
|
||||
"color": "^3.1.3",
|
||||
"text-hex": "1.0.x"
|
||||
}
|
||||
},
|
||||
"node_modules/colorspace/node_modules/color": {
|
||||
"version": "3.2.1",
|
||||
"resolved": "https://registry.npmjs.org/color/-/color-3.2.1.tgz",
|
||||
"integrity": "sha512-aBl7dZI9ENN6fUGC7mWpMTPNHmWUSNan9tuWN6ahh5ZLNk9baLJOnSMlrQkHcrfFgz2/RigjUVAjdx36VcemKA==",
|
||||
"dependencies": {
|
||||
"color-convert": "^1.9.3",
|
||||
"color-string": "^1.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/colorspace/node_modules/color-convert": {
|
||||
"version": "1.9.3",
|
||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
|
||||
"integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
|
||||
"dependencies": {
|
||||
"color-name": "1.1.3"
|
||||
}
|
||||
},
|
||||
"node_modules/colorspace/node_modules/color-name": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
|
||||
"integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw=="
|
||||
},
|
||||
"node_modules/combined-stream": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
|
||||
|
|
@ -7080,9 +7135,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/dotenv": {
|
||||
"version": "16.4.7",
|
||||
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz",
|
||||
"integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==",
|
||||
"version": "16.5.0",
|
||||
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.5.0.tgz",
|
||||
"integrity": "sha512-m/C+AwOAr9/W1UOIZUo232ejMNnJAJtYQjUbHoNTBNTJSvqzzDh7vnrei3o3r3m9blf6ZoDkvcw0VmozNRFJxg==",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
|
|
@ -7173,6 +7228,11 @@
|
|||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
||||
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="
|
||||
},
|
||||
"node_modules/enabled": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz",
|
||||
"integrity": "sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ=="
|
||||
},
|
||||
"node_modules/encoding": {
|
||||
"version": "0.1.13",
|
||||
"resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz",
|
||||
|
|
@ -8075,6 +8135,11 @@
|
|||
"pend": "~1.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fecha": {
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz",
|
||||
"integrity": "sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw=="
|
||||
},
|
||||
"node_modules/fetch-blob": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz",
|
||||
|
|
@ -8201,6 +8266,11 @@
|
|||
"resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.2.tgz",
|
||||
"integrity": "sha512-AiwGJM8YcNOaobumgtng+6NHuOqC3A7MixFeDafM3X9cIUM+xUXoS5Vfgf+OihAYe20fxqNM9yPBXJzRtZ/4eA=="
|
||||
},
|
||||
"node_modules/fn.name": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/fn.name/-/fn.name-1.1.0.tgz",
|
||||
"integrity": "sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw=="
|
||||
},
|
||||
"node_modules/follow-redirects": {
|
||||
"version": "1.15.9",
|
||||
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
|
||||
|
|
@ -10937,6 +11007,11 @@
|
|||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/kuler": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz",
|
||||
"integrity": "sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A=="
|
||||
},
|
||||
"node_modules/launchdarkly-eventsource": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/launchdarkly-eventsource/-/launchdarkly-eventsource-2.0.3.tgz",
|
||||
|
|
@ -11096,6 +11171,22 @@
|
|||
"resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
|
||||
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg=="
|
||||
},
|
||||
"node_modules/logform": {
|
||||
"version": "2.7.0",
|
||||
"resolved": "https://registry.npmjs.org/logform/-/logform-2.7.0.tgz",
|
||||
"integrity": "sha512-TFYA4jnP7PVbmlBIfhlSe+WKxs9dklXMTEGcBCIvLhE/Tn3H6Gk1norupVW7m5Cnd4bLcr08AytbyV/xj7f/kQ==",
|
||||
"dependencies": {
|
||||
"@colors/colors": "1.6.0",
|
||||
"@types/triple-beam": "^1.3.2",
|
||||
"fecha": "^4.2.0",
|
||||
"ms": "^2.1.1",
|
||||
"safe-stable-stringify": "^2.3.1",
|
||||
"triple-beam": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/long": {
|
||||
"version": "5.2.3",
|
||||
"resolved": "https://registry.npmjs.org/long/-/long-5.2.3.tgz",
|
||||
|
|
@ -12103,6 +12194,14 @@
|
|||
"wrappy": "1"
|
||||
}
|
||||
},
|
||||
"node_modules/one-time": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/one-time/-/one-time-1.0.0.tgz",
|
||||
"integrity": "sha512-5DXOiRKwuSEcQ/l0kGCF6Q3jcADFv5tSmRaJck/OqkVFcOzutB134KRSfF0xDrL39MNnqxbHBbUUcjZIhTgb2g==",
|
||||
"dependencies": {
|
||||
"fn.name": "1.x.x"
|
||||
}
|
||||
},
|
||||
"node_modules/onetime": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",
|
||||
|
|
@ -13746,6 +13845,14 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/safe-stable-stringify": {
|
||||
"version": "2.5.0",
|
||||
"resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",
|
||||
"integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/safer-buffer": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||
|
|
@ -14224,6 +14331,14 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/stack-trace": {
|
||||
"version": "0.0.10",
|
||||
"resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz",
|
||||
"integrity": "sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg==",
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/stack-utils": {
|
||||
"version": "2.0.6",
|
||||
"resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz",
|
||||
|
|
@ -14707,6 +14822,11 @@
|
|||
"b4a": "^1.6.4"
|
||||
}
|
||||
},
|
||||
"node_modules/text-hex": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz",
|
||||
"integrity": "sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg=="
|
||||
},
|
||||
"node_modules/text-table": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz",
|
||||
|
|
@ -14775,6 +14895,14 @@
|
|||
"tree-sitter-wasms": "^0.1.11"
|
||||
}
|
||||
},
|
||||
"node_modules/triple-beam": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz",
|
||||
"integrity": "sha512-aZbgViZrg1QNcG+LULa7nhZpJTZSLm/mXnHXnbAbjmN5aSa0y7V+wvv6+4WaBtpISJzThKy+PIPxc1Nq1EJ9mg==",
|
||||
"engines": {
|
||||
"node": ">= 14.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ts-api-utils": {
|
||||
"version": "1.4.3",
|
||||
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.4.3.tgz",
|
||||
|
|
@ -15582,6 +15710,66 @@
|
|||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
|
||||
"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="
|
||||
},
|
||||
"node_modules/winston": {
|
||||
"version": "3.17.0",
|
||||
"resolved": "https://registry.npmjs.org/winston/-/winston-3.17.0.tgz",
|
||||
"integrity": "sha512-DLiFIXYC5fMPxaRg832S6F5mJYvePtmO5G9v9IgUFPhXm9/GkXarH/TUrBAVzhTCzAj9anE/+GjrgXp/54nOgw==",
|
||||
"dependencies": {
|
||||
"@colors/colors": "^1.6.0",
|
||||
"@dabh/diagnostics": "^2.0.2",
|
||||
"async": "^3.2.3",
|
||||
"is-stream": "^2.0.0",
|
||||
"logform": "^2.7.0",
|
||||
"one-time": "^1.0.0",
|
||||
"readable-stream": "^3.4.0",
|
||||
"safe-stable-stringify": "^2.3.1",
|
||||
"stack-trace": "0.0.x",
|
||||
"triple-beam": "^1.3.0",
|
||||
"winston-transport": "^4.9.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/winston-transport": {
|
||||
"version": "4.9.0",
|
||||
"resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.9.0.tgz",
|
||||
"integrity": "sha512-8drMJ4rkgaPo1Me4zD/3WLfI/zPdA9o2IipKODunnGDcuqbHwjsbB79ylv04LCGGzU0xQ6vTznOMpQGaLhhm6A==",
|
||||
"dependencies": {
|
||||
"logform": "^2.7.0",
|
||||
"readable-stream": "^3.6.2",
|
||||
"triple-beam": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/winston-transport/node_modules/readable-stream": {
|
||||
"version": "3.6.2",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
|
||||
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
|
||||
"dependencies": {
|
||||
"inherits": "^2.0.3",
|
||||
"string_decoder": "^1.1.1",
|
||||
"util-deprecate": "^1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/winston/node_modules/readable-stream": {
|
||||
"version": "3.6.2",
|
||||
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
|
||||
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
|
||||
"dependencies": {
|
||||
"inherits": "^2.0.3",
|
||||
"string_decoder": "^1.1.1",
|
||||
"util-deprecate": "^1.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/word-wrap": {
|
||||
"version": "1.2.5",
|
||||
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@
|
|||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.18",
|
||||
"@continuedev/openai-adapters": "^1.0.19",
|
||||
"@modelcontextprotocol/sdk": "^1.5.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
|
|
@ -105,12 +105,13 @@
|
|||
"web-tree-sitter": "^0.21.0",
|
||||
"win-ca": "^3.5.1",
|
||||
"wink-nlp-utils": "^2.1.0",
|
||||
"winston": "^3.17.0",
|
||||
"workerpool": "^9.1.3",
|
||||
"yaml": "^2.4.2",
|
||||
"zod": "^3.24.2"
|
||||
},
|
||||
"engine-strict": true,
|
||||
"engines": {
|
||||
"node": ">=20.11.0"
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -101,7 +101,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
query: string;
|
||||
fullInput: string;
|
||||
selectedCode: RangeInFile[];
|
||||
selectedModelTitle: string;
|
||||
},
|
||||
ContextItemWithId[],
|
||||
];
|
||||
|
|
@ -156,7 +155,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
];
|
||||
"chatDescriber/describe": [
|
||||
{
|
||||
selectedModelTitle: string;
|
||||
text: string;
|
||||
},
|
||||
string | undefined,
|
||||
|
|
@ -203,15 +201,12 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
|
||||
"auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }];
|
||||
"tools/call": [
|
||||
{ toolCall: ToolCall; selectedModelTitle: string },
|
||||
{ contextItems: ContextItem[] },
|
||||
{ toolCall: ToolCall },
|
||||
{ contextItems: ContextItem[]; errorMessage?: string },
|
||||
];
|
||||
"clipboardCache/add": [{ content: string }, void];
|
||||
"controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void];
|
||||
isItemTooBig: [
|
||||
{ item: ContextItemWithId; selectedModelTitle: string | undefined },
|
||||
boolean,
|
||||
];
|
||||
isItemTooBig: [{ item: ContextItemWithId }, boolean];
|
||||
didChangeControlPlaneSessionInfo: [
|
||||
{ sessionInfo: ControlPlaneSessionInfo | undefined },
|
||||
void,
|
||||
|
|
|
|||
|
|
@ -99,6 +99,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
ControlPlaneSessionInfo | undefined,
|
||||
];
|
||||
logoutOfControlPlane: [undefined, void];
|
||||
closeSidebar: [undefined, void];
|
||||
};
|
||||
|
||||
export type ToWebviewOrCoreFromIdeProtocol = {
|
||||
|
|
|
|||
|
|
@ -17,3 +17,5 @@ export enum BuiltInToolNames {
|
|||
}
|
||||
|
||||
export const BUILT_IN_GROUP_NAME = "Built-In";
|
||||
|
||||
export const CLIENT_TOOLS = [BuiltInToolNames.EditExistingFile];
|
||||
|
|
|
|||
|
|
@ -130,40 +130,72 @@ async function callToolFromUri(
|
|||
}
|
||||
}
|
||||
|
||||
// Handles calls for core/non-client tools
|
||||
// Returns an error context item if the tool call fails
|
||||
// Note: Edit tool is handled on client
|
||||
export async function callTool(
|
||||
tool: Tool,
|
||||
args: any,
|
||||
callArgs: string,
|
||||
extras: ToolExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
): Promise<{
|
||||
contextItems: ContextItem[];
|
||||
errorMessage: string | undefined;
|
||||
}> {
|
||||
const args = JSON.parse(callArgs || "{}");
|
||||
const uri = tool.uri ?? tool.function.name;
|
||||
|
||||
switch (uri) {
|
||||
case BuiltInToolNames.ReadFile:
|
||||
return await readFileImpl(args, extras);
|
||||
// Note: Custom GUI handling for edit
|
||||
case BuiltInToolNames.CreateNewFile:
|
||||
return await createNewFileImpl(args, extras);
|
||||
case BuiltInToolNames.GrepSearch:
|
||||
return await grepSearchImpl(args, extras);
|
||||
case BuiltInToolNames.FileGlobSearch:
|
||||
return await fileGlobSearchImpl(args, extras);
|
||||
case BuiltInToolNames.RunTerminalCommand:
|
||||
return await runTerminalCommandImpl(args, extras);
|
||||
case BuiltInToolNames.SearchWeb:
|
||||
return await searchWebImpl(args, extras);
|
||||
case BuiltInToolNames.ViewDiff:
|
||||
return await viewDiffImpl(args, extras);
|
||||
case BuiltInToolNames.LSTool:
|
||||
return await lsToolImpl(args, extras);
|
||||
case BuiltInToolNames.ReadCurrentlyOpenFile:
|
||||
return await readCurrentlyOpenFileImpl(args, extras);
|
||||
case BuiltInToolNames.CreateRuleBlock:
|
||||
return await createRuleBlockImpl(args, extras);
|
||||
// case BuiltInToolNames.ViewRepoMap:
|
||||
// return await viewRepoMapImpl(args, extras);
|
||||
// case BuiltInToolNames.ViewSubdirectory:
|
||||
// return await viewSubdirectoryImpl(args, extras);
|
||||
default:
|
||||
return await callToolFromUri(uri, args, extras);
|
||||
try {
|
||||
let contextItems: ContextItem[] = [];
|
||||
switch (uri) {
|
||||
case BuiltInToolNames.ReadFile:
|
||||
contextItems = await readFileImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.CreateNewFile:
|
||||
contextItems = await createNewFileImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.GrepSearch:
|
||||
contextItems = await grepSearchImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.FileGlobSearch:
|
||||
contextItems = await fileGlobSearchImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.RunTerminalCommand:
|
||||
contextItems = await runTerminalCommandImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.SearchWeb:
|
||||
contextItems = await searchWebImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.ViewDiff:
|
||||
contextItems = await viewDiffImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.LSTool:
|
||||
contextItems = await lsToolImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.ReadCurrentlyOpenFile:
|
||||
contextItems = await readCurrentlyOpenFileImpl(args, extras);
|
||||
break;
|
||||
case BuiltInToolNames.CreateRuleBlock:
|
||||
contextItems = await createRuleBlockImpl(args, extras);
|
||||
break;
|
||||
default:
|
||||
contextItems = await callToolFromUri(uri, args, extras);
|
||||
}
|
||||
if (tool.faviconUrl) {
|
||||
contextItems.forEach((item) => {
|
||||
item.icon = tool.faviconUrl;
|
||||
});
|
||||
}
|
||||
return {
|
||||
contextItems,
|
||||
errorMessage: undefined,
|
||||
};
|
||||
} catch (e) {
|
||||
let errorMessage = `${e}`;
|
||||
if (e instanceof Error) {
|
||||
errorMessage = e.message;
|
||||
}
|
||||
return {
|
||||
contextItems: [],
|
||||
errorMessage,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
|||
|
||||
export interface EditToolArgs {
|
||||
filepath: string;
|
||||
new_contents: string;
|
||||
changes: string;
|
||||
}
|
||||
|
||||
export const editFileTool: Tool = {
|
||||
|
|
@ -20,16 +20,17 @@ export const editFileTool: Tool = {
|
|||
"Use this tool to edit an existing file. If you don't know the contents of the file, read it first.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["filepath", "new_contents"],
|
||||
required: ["filepath", "changes"],
|
||||
properties: {
|
||||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path of the file to edit, relative to the root of the workspace.",
|
||||
},
|
||||
new_contents: {
|
||||
changes: {
|
||||
type: "string",
|
||||
description: "The new file contents",
|
||||
description:
|
||||
"Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock. Use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... rest of code here ...'",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
|
|||
14
core/util/logger.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import winston from "winston";
|
||||
|
||||
console.log("NODE_ENV", process.env.NODE_ENV);
|
||||
|
||||
export const logger = winston.createLogger({
|
||||
level: "info",
|
||||
format: winston.format.json(),
|
||||
transports: [
|
||||
// Write all logs with importance level of `info` or higher to `info.log`
|
||||
new winston.transports.File({ filename: "e2e.log", level: "info" }),
|
||||
// Normal console.log behavior
|
||||
new winston.transports.Console(),
|
||||
],
|
||||
});
|
||||
|
|
@ -13,8 +13,16 @@ import Types from "../config/types";
|
|||
|
||||
dotenv.config();
|
||||
|
||||
const CONTINUE_GLOBAL_DIR =
|
||||
process.env.CONTINUE_GLOBAL_DIR ?? path.join(os.homedir(), ".continue");
|
||||
const CONTINUE_GLOBAL_DIR = (() => {
|
||||
const configPath = process.env.CONTINUE_GLOBAL_DIR;
|
||||
if (configPath) {
|
||||
// Convert relative path to absolute paths based on current working directory
|
||||
return path.isAbsolute(configPath)
|
||||
? configPath
|
||||
: path.resolve(process.cwd(), configPath);
|
||||
}
|
||||
return path.join(os.homedir(), ".continue");
|
||||
})();
|
||||
|
||||
// export const DEFAULT_CONFIG_TS_CONTENTS = `import { Config } from "./types"\n\nexport function modifyConfig(config: Config): Config {
|
||||
// return config;
|
||||
|
|
@ -376,12 +384,16 @@ export function getPromptLogsPath(): string {
|
|||
return path.join(getLogsDirPath(), "prompt.log");
|
||||
}
|
||||
|
||||
export function getGlobalFolderWithName(name: string): string {
|
||||
return path.join(getContinueGlobalPath(), name);
|
||||
}
|
||||
|
||||
export function getGlobalPromptsPath(): string {
|
||||
return path.join(getContinueGlobalPath(), "prompts");
|
||||
return getGlobalFolderWithName("prompts");
|
||||
}
|
||||
|
||||
export function getGlobalAssistantsPath(): string {
|
||||
return path.join(getContinueGlobalPath(), "assistants");
|
||||
return getGlobalFolderWithName("assistants");
|
||||
}
|
||||
|
||||
export function readAllGlobalPromptFiles(
|
||||
|
|
|
|||
2
core/vendor/package.json
vendored
|
|
@ -13,6 +13,6 @@
|
|||
},
|
||||
"engine-strict": true,
|
||||
"engines": {
|
||||
"node": ">=20.11.0"
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
21
docs/docs/blocks/context-providers.md
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
---
|
||||
title: Context Blocks
|
||||
sidebar_label: Context
|
||||
description: Determine what internal information your AI assistant can access
|
||||
keywords: [context, blocks, repositories, integration, knowledge base]
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
These blocks determine what internal information your AI assistant can access:
|
||||
|
||||
- **Connect to source repositories** and issues, CI/CD systems, wikis, and knowledge bases
|
||||
- **Determine the scope** of what the AI can "see" when providing assistance
|
||||
- **Customize** to match your specific development environment
|
||||
- **Include proprietary code patterns** unique to your organization
|
||||
- **Integrate data sources** to connect to any internal system with valuable context
|
||||
|
||||

|
||||
|
||||
## Learn More
|
||||
|
||||
Learn more about context providers [here](../reference.md#context), and check out [this guide](../customize/tutorials/build-your-own-context-provider.mdx) to creating your own custom context provider.
|
||||
20
docs/docs/blocks/data.md
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
---
|
||||
title: Data Blocks
|
||||
sidebar_label: Data
|
||||
description: Help organizations capture and analyze AI assistant usage data
|
||||
keywords: [data, blocks, analytics, metrics, storage, compliance]
|
||||
sidebar_position: 7
|
||||
---
|
||||
|
||||
These help organizations capture and analyze AI assistant usage data:
|
||||
|
||||
- **Analytics Integration**: Export metrics to observability platforms like Splunk or New Relic
|
||||
- **Cloud Storage**: Store development data in S3/Azure Blob for model fine-tuning and auditing
|
||||
- **Impact Measurement**: Track acceptance rates and productivity outcomes for ROI calculation
|
||||
- **Compliance Reporting**: Generate audit trails for security and governance requirements
|
||||
|
||||

|
||||
|
||||
## Learn More
|
||||
|
||||
You can read more about development data [here](../customize/deep-dives/development-data.md). Data destinations are configured in the [`data`](../reference.md#data) section of `config.yaml`.
|
||||
19
docs/docs/blocks/docs.md
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
---
|
||||
title: Docs Blocks
|
||||
sidebar_label: Docs
|
||||
description: Bring your documentation directly into the IDE
|
||||
keywords: [docs, blocks, documentation, guidance, flow]
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
This is how Continue brings your documentation directly into the IDE:
|
||||
|
||||
- **Provide just-in-time guidance** without context switching
|
||||
- **Reduce support burden** by making information discoverable
|
||||
- **Keep developers in flow** by eliminating searches through multiple systems
|
||||
|
||||

|
||||
|
||||
## Learn More
|
||||
|
||||
Learn more in the [@Docs deep dive](../customize/deep-dives/docs.mdx), and view [`docs`](../reference.md#docs) in the YAML Reference for more details.
|
||||
44
docs/docs/blocks/mcp.md
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
---
|
||||
title: MCP Blocks
|
||||
---
|
||||
|
||||
title: MCP Blocks
|
||||
sidebar_label: MCP
|
||||
description: Model Context Protocol servers provide specialized functionality
|
||||
keywords: [mcp, blocks, model context protocol, integrations, tools]
|
||||
sidebar_position: 4
|
||||
|
||||
---
|
||||
|
||||
Model Context Protocol servers provide specialized functionality:
|
||||
|
||||
- **Enable integration** with external tools and systems
|
||||
- **Create extensible interfaces** for custom capabilities
|
||||
- **Support complex interactions** with your development environment
|
||||
- **Allow partners** to contribute specialized functionality
|
||||
- **Connect to databases** to understand schema and data models during development
|
||||
|
||||

|
||||
|
||||
## Learn More
|
||||
|
||||
Learn more in the [MCP deep dive](../customize/deep-dives/mcp.mdx), and view [`mcpServers`](../reference.md#mcpservers) in the YAML Reference for more details.
|
||||
description: Model Context Protocol servers provide specialized functionality
|
||||
keywords: [mcp, blocks, model context protocol, integrations, tools]
|
||||
sidebar_position: 4
|
||||
|
||||
---
|
||||
|
||||
Model Context Protocol servers provide specialized functionality:
|
||||
|
||||
- Enable integration with external tools and systems
|
||||
- Create extensible interfaces for custom capabilities
|
||||
- Support more complex interactions with your development environment
|
||||
- Allow partners to contribute specialized functionality
|
||||
- Database Connectors: Understand schema and data models during development
|
||||
|
||||

|
||||
|
||||
## Learn More
|
||||
|
||||
Learn more in the [MCP deep dive](../customize/deep-dives/mcp.mdx), and view [`mcpServers`](../reference.md#mcpservers) in the YAML Reference for more details.
|
||||
24
docs/docs/blocks/models.md
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
---
|
||||
title: Model Blocks
|
||||
sidebar_label: Model
|
||||
description: Foundation of the entire assistant experience offering specialized capabilities
|
||||
keywords: [model, blocks, chat, edit, apply, autocomplete, embedding, reranker]
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
These blocks form the foundation of the entire assistant experience, offering different specialized capabilities:
|
||||
|
||||
- **[Chat](../customize/model-roles/chat.mdx)**: Power conversational interactions about code and provide detailed guidance
|
||||
- **[Edit](../customize/model-roles/edit.mdx)**: Handle complex code transformations and refactoring tasks
|
||||
- **[Apply](../customize/model-roles/apply.mdx)**: Execute targeted code modifications with high accuracy
|
||||
- **[Autocomplete](../customize/model-roles/autocomplete.md)**: Provide real-time suggestions as developers type
|
||||
- **[Embedding](../customize/model-roles/embeddings.mdx)**: Transform code into vector representations for semantic search
|
||||
- **[Reranker](../customize/model-roles/reranking.mdx)**: Improve search relevance by ordering results based on semantic meaning
|
||||
|
||||

|
||||
|
||||
## Learn More
|
||||
|
||||
Continue supports [many model providers](../customize/model-providers), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`.
|
||||
|
||||
Read more about roles [here](../customize/model-roles/intro.mdx) and view [`models`](../reference.md#models) in the YAML Reference.
|
||||
21
docs/docs/blocks/prompts.md
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
---
|
||||
title: Prompt Blocks
|
||||
sidebar_label: Prompt
|
||||
description: Specialized instructions that shape how models respond
|
||||
keywords: [prompts, blocks, instructions, guidance, code review]
|
||||
sidebar_position: 6
|
||||
---
|
||||
|
||||
These are the specialized instructions that shape how models respond:
|
||||
|
||||
- **Define interaction patterns** for specific tasks or frameworks
|
||||
- **Encode domain expertise** for particular technologies
|
||||
- **Ensure consistent guidance** aligned with organizational practices
|
||||
- **Can be shared and reused** across multiple assistants
|
||||
- **Act as automated code reviewers** that ensure consistency across teams
|
||||
|
||||

|
||||
|
||||
## Learn More
|
||||
|
||||
Prompt blocks have the same syntax as [prompt files](../customize/deep-dives/prompts.md). The `config.yaml` spec for `prompts` can be found [here](../reference.md#prompts).
|
||||
19
docs/docs/blocks/rules.md
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
---
|
||||
title: Rules Blocks
|
||||
sidebar_label: Rules
|
||||
description: Guardrails for your AI coding assistants
|
||||
keywords: [rules, blocks, standards, practices, guardrails]
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
Think of these as the guardrails for your AI coding assistants:
|
||||
|
||||
- **Enforce company-specific coding standards** and security practices
|
||||
- **Implement quality checks** that match your engineering culture
|
||||
- **Create paved paths** for developers to follow organizational best practices
|
||||
|
||||

|
||||
|
||||
## Learn More
|
||||
|
||||
Learn more in the [rules deep dive](../customize/deep-dives/rules.md), and view [`rules`](../reference.md#rules) in the YAML Reference for more details.
|
||||
|
|
@ -17,12 +17,14 @@ Hub Assistants can be managed in [the Hub](https://hub.continue.dev). See [Editi
|
|||
|
||||
Local user-level configuration is stored and can be edited in your home directory in `config.yaml`:
|
||||
|
||||
To open `config.yaml`, you can click the "gear" icon in the header of the Continue Chat sidebar to open the settings page, and then click `Open Assistant configuration` to open the file. When editing this file, you can see the available options suggested as you type, or check the reference below.
|
||||
|
||||
- `~/.continue/config.yaml` (MacOS / Linux)
|
||||
- `%USERPROFILE%\.continue\config.yaml` (Windows)
|
||||
|
||||
When you save a config file from the IDE, Continue will automatically refresh to take into account your changes. A config file is automatically created the first time you use Continue, and always automatically generated with default values if it doesn't exist.
|
||||
To open this `config.yaml`, you need to open the assistants dropdown in the top-right portion of the chat input. On that dropdown beside the "Local Assistant" option, select the cog icon. It will open the local `config.yaml`.
|
||||
|
||||

|
||||
|
||||
When editing this file, you can see the available options suggested as you type, or check the reference below. When you save a config file from the IDE, Continue will automatically refresh to take into account your changes. A config file is automatically created the first time you use Continue, and always automatically generated with default values if it doesn't exist.
|
||||
|
||||
See the full reference for `config.yaml` [here](../../reference.md).
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ keywords: [rules, .continuerules, system, prompt, message]
|
|||
|
||||
Rules are used to provide instructions to the model for [Chat](../../chat/how-to-use-it.md), [Edit](../../edit/how-to-use-it.md), and [Agent](../../agent/how-to-use-it.md) requests.
|
||||
|
||||
Rules are **_NOT_** included in most other requests, such as [autocomplete](./autocomplete.mdx) or [apply](../model-roles/apply.mdx).
|
||||
Rules are not included in most other requests, such as [autocomplete](./autocomplete.mdx) or [apply](../model-roles/apply.mdx).
|
||||
|
||||
You can view the current rules by clicking the pen icon above the main toolbar:
|
||||
|
||||
|
|
@ -25,22 +25,31 @@ When in Agent mode, you can simply prompt the agent to create a rule for you.
|
|||
For example, you can say "Create a rule for this", and a rule will be created for you in `~/.continue/rules` based on your conversation.
|
||||
:::
|
||||
|
||||
### Syntax
|
||||
|
||||
Rules blocks can be simple text, or have the following properties:
|
||||
|
||||
- `name` (**required**): A display name/title for the rule
|
||||
- `rule` (**required**): The text content of the rule
|
||||
|
||||
Examples:
|
||||
- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`).
|
||||
|
||||
```yaml title="config.yaml"
|
||||
rules:
|
||||
- Always annotate Python functions with their parameter and return types
|
||||
|
||||
- name: TypeScript best practices
|
||||
rule: Always use TypeScript interfaces to define shape of objects. Use type aliases sparingly.
|
||||
globs: "**/*.{ts,tsx}"
|
||||
|
||||
- name: TypeScript test patterns
|
||||
rule: In TypeScript tests, use Jest's describe/it pattern and follow best practices for mocking.
|
||||
globs:
|
||||
- "src/**/*.test.ts"
|
||||
- "tests/**/*.ts"
|
||||
|
||||
- uses: myprofile/my-mood-setter
|
||||
with:
|
||||
TONE: consise
|
||||
- Always annotate Python functions with their parameter and return types
|
||||
- Always write Google style docstrings for functions and classes
|
||||
- name: Server-side components
|
||||
rule: When writing Next.js React components, use server-side components where possible instead of client components.
|
||||
TONE: concise
|
||||
```
|
||||
|
||||
## Chat System Message
|
||||
|
|
|
|||
|
|
@ -12,3 +12,30 @@ In Continue, autocomplete models are used to display inline [Autocomplete](../..
|
|||
## Recommended Autocomplete models
|
||||
|
||||
Visit the [Autocomplete Deep Dive](../deep-dives/autocomplete.mdx) for recommended models and more details.
|
||||
|
||||
## Prompt templating
|
||||
|
||||
You can customize the prompt template used when autocomplete happens by setting the `promptTemplates.autocomplete` property in your model configuration. Continue uses [Handlebars syntax](https://handlebarsjs.com/guide/) for templating.
|
||||
|
||||
Available variables for the apply template:
|
||||
|
||||
- `{{{prefix}}}` - the code before your cursor
|
||||
- `{{{suffix}}}` - the code after your cursor
|
||||
- `{{{filename}}}` - the name of the file your cursor currently is
|
||||
- `{{{reponame}}}` - the name of the folder where the codebase is
|
||||
- `{{{language}}}` - the name of the programming language in full (ex. Typescript)
|
||||
|
||||
Example:
|
||||
|
||||
```yaml
|
||||
models:
|
||||
- name: My Custom Autocomplete Template
|
||||
provider: ollama
|
||||
model: qwen2.5-coder:1.5b
|
||||
promptTemplates:
|
||||
autocomplete: |
|
||||
`
|
||||
globalThis.importantFunc = importantFunc
|
||||
<|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>
|
||||
`
|
||||
```
|
||||
|
|
@ -18,7 +18,7 @@ In Continue, these models are used for normal [Chat](../../chat/how-to-use-it.md
|
|||
|
||||
For the best overall Chat experience, you will want to use a 400B+ parameter model or one of the frontier models.
|
||||
|
||||
### Claude Sonnet 3.5 from Anthropic
|
||||
### Claude Sonnet 3.7 from Anthropic
|
||||
|
||||
Our current top recommendation is Claude 3.7 Sonnet from [Anthropic](../model-providers/top-level/anthropic.mdx).
|
||||
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ Assistants can either explicitly define blocks - see [Properties](#properties) b
|
|||
|
||||
### Using Blocks
|
||||
|
||||
Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization.
|
||||
Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from [https://hub.continue.dev](https://hub.continue.dev).
|
||||
|
||||
Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type.
|
||||
|
||||
|
|
@ -167,7 +167,7 @@ The `models` section defines the language models used in your configuration. Mod
|
|||
- `apiBase`: Can be used to override the default API base that is specified per model
|
||||
- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used.
|
||||
- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`.
|
||||
- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are [`edit`](./customize/model-roles/edit.mdx#prompt-templating) and [`apply`](./customize/model-roles/apply.mdx#prompt-templating).
|
||||
- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [`apply`](./customize/model-roles/apply.mdx#prompt-templating) and [autocomplete](./customize/model-roles/autocomplete.md#prompt-templating)
|
||||
- `chatOptions`: If the model includes role `chat`, these settings apply for Chat and Agent mode:
|
||||
- `baseSystemMessage`: Can be used to override the default system prompt.
|
||||
- `embedOptions`: If the model includes role `embed`, these settings apply for embeddings:
|
||||
|
|
@ -270,19 +270,25 @@ Explicit rules can either be simple text or an object with the following propert
|
|||
|
||||
- `name` (**required**): A display name/title for the rule
|
||||
- `rule` (**required**): The text content of the rule
|
||||
<!-- `if` -->
|
||||
|
||||
Example
|
||||
- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`).
|
||||
|
||||
```yaml title="config.yaml"
|
||||
rules:
|
||||
- Always annotate Python functions with their parameter and return types
|
||||
|
||||
- name: TypeScript best practices
|
||||
rule: Always use TypeScript interfaces to define shape of objects. Use type aliases sparingly.
|
||||
globs: "**/*.{ts,tsx}"
|
||||
|
||||
- name: TypeScript test patterns
|
||||
rule: In TypeScript tests, use Jest's describe/it pattern and follow best practices for mocking.
|
||||
globs:
|
||||
- "src/**/*.test.ts"
|
||||
- "tests/**/*.ts"
|
||||
|
||||
- uses: myprofile/my-mood-setter
|
||||
with:
|
||||
TONE: concise
|
||||
- Always annotate Python functions with their parameter and return types
|
||||
- Always write Google style docstrings for functions and classes
|
||||
- name: Server-side components
|
||||
rule: When writing Next.js React components, use server-side components where possible instead of client components.
|
||||
```
|
||||
|
||||
---
|
||||
|
|
|
|||
48
docs/package-lock.json
generated
|
|
@ -23,7 +23,7 @@
|
|||
"nodemon": "^3.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.11.0"
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@algolia/autocomplete-core": {
|
||||
|
|
@ -566,23 +566,25 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@babel/helpers": {
|
||||
"version": "7.26.0",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.26.0.tgz",
|
||||
"integrity": "sha512-tbhNuIxNcVb21pInl3ZSjksLCvgdZy9KwJ8brv993QtIVKJBBkYXz4q4ZbAv31GdnC+R90np23L5FbEBlthAEw==",
|
||||
"version": "7.27.0",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.27.0.tgz",
|
||||
"integrity": "sha512-U5eyP/CTFPuNE3qk+WZMxFkp/4zUzdceQlfzf7DdGdhp+Fezd7HD+i8Y24ZuTMKX3wQBld449jijbGq6OdGNQg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/template": "^7.25.9",
|
||||
"@babel/types": "^7.26.0"
|
||||
"@babel/template": "^7.27.0",
|
||||
"@babel/types": "^7.27.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/parser": {
|
||||
"version": "7.26.3",
|
||||
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.3.tgz",
|
||||
"integrity": "sha512-WJ/CvmY8Mea8iDXo6a7RK2wbmJITT5fN3BEkRuFlxVyNx8jOKIIhmC4fSkTcPcf8JyavbBwIe6OpiCOBXt/IcA==",
|
||||
"version": "7.27.0",
|
||||
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.27.0.tgz",
|
||||
"integrity": "sha512-iaepho73/2Pz7w2eMS0Q5f83+0RKI7i4xmiYeBmDzfRVbQtTOG7Ts0S4HzJVsTMGI9keU8rNfuZr8DKfSt7Yyg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/types": "^7.26.3"
|
||||
"@babel/types": "^7.27.0"
|
||||
},
|
||||
"bin": {
|
||||
"parser": "bin/babel-parser.js"
|
||||
|
|
@ -1781,13 +1783,14 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@babel/template": {
|
||||
"version": "7.25.9",
|
||||
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.25.9.tgz",
|
||||
"integrity": "sha512-9DGttpmPvIxBb/2uwpVo3dqJ+O6RooAFOS+lB+xDqoE2PVCE8nfoHMdZLpfCQRLwvohzXISPZcgxt80xLfsuwg==",
|
||||
"version": "7.27.0",
|
||||
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.0.tgz",
|
||||
"integrity": "sha512-2ncevenBqXI6qRMukPlXwHKHchC7RyMuu4xv5JBXRfOGVcTy1mXCD12qrp7Jsoxll1EV3+9sE4GugBVRjT2jFA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.25.9",
|
||||
"@babel/parser": "^7.25.9",
|
||||
"@babel/types": "^7.25.9"
|
||||
"@babel/code-frame": "^7.26.2",
|
||||
"@babel/parser": "^7.27.0",
|
||||
"@babel/types": "^7.27.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
|
|
@ -1811,9 +1814,10 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@babel/types": {
|
||||
"version": "7.26.3",
|
||||
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.3.tgz",
|
||||
"integrity": "sha512-vN5p+1kl59GVKMvTHt55NzzmYVxprfJD+ql7U9NFIfKCBkYE55LYtS+WtPlaYOyzydrKI8Nezd+aZextrd+FMA==",
|
||||
"version": "7.27.0",
|
||||
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.27.0.tgz",
|
||||
"integrity": "sha512-H45s8fVLYjbhFH62dIJ3WtmJ6RSPt/3DRO0ZcT2SUiYiQyz3BLVb9ADEnLl91m74aQPS3AzzeajZHYOalWe3bg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/helper-string-parser": "^7.25.9",
|
||||
"@babel/helper-validator-identifier": "^7.25.9"
|
||||
|
|
@ -9521,9 +9525,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/http-proxy-middleware": {
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.7.tgz",
|
||||
"integrity": "sha512-fgVY8AV7qU7z/MmXJ/rxwbrtQH4jBQ9m7kp3llF0liB7glmFeVZFBepQb32T3y8n8k2+AEYuMPCpinYW+/CuRA==",
|
||||
"version": "2.0.9",
|
||||
"resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.9.tgz",
|
||||
"integrity": "sha512-c1IyJYLYppU574+YI7R4QyX2ystMtVXZwIdzazUIPIJsHuWNd+mho2j+bKoHftndicGj9yh+xjd+l0yj7VeT1Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/http-proxy": "^1.17.8",
|
||||
|
|
|
|||
|
|
@ -44,6 +44,6 @@
|
|||
},
|
||||
"engine-strict": true,
|
||||
"engines": {
|
||||
"node": ">=20.11.0"
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -55,6 +55,16 @@ const sidebars = {
|
|||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "category",
|
||||
label: "Blocks",
|
||||
items: [
|
||||
{
|
||||
type: "autogenerated",
|
||||
dirName: "blocks",
|
||||
},
|
||||
],
|
||||
},
|
||||
"telemetry",
|
||||
"troubleshooting",
|
||||
{
|
||||
|
|
@ -68,7 +78,6 @@ const sidebars = {
|
|||
{
|
||||
type: "category",
|
||||
label: "Model providers",
|
||||
collapsed: false,
|
||||
link: {
|
||||
slug: "/customize/model-providers",
|
||||
type: "generated-index",
|
||||
|
|
|
|||
BIN
docs/static/img/context-blocks-overview.png
vendored
Normal file
|
After Width: | Height: | Size: 1.3 MiB |
BIN
docs/static/img/data-blocks-overview.png
vendored
Normal file
|
After Width: | Height: | Size: 1.4 MiB |
BIN
docs/static/img/docs-blocks-overview.png
vendored
Normal file
|
After Width: | Height: | Size: 1.5 MiB |
BIN
docs/static/img/local-config-open-steps.png
vendored
Normal file
|
After Width: | Height: | Size: 64 KiB |
BIN
docs/static/img/mcp-blocks-overview.png
vendored
Normal file
|
After Width: | Height: | Size: 1.6 MiB |
BIN
docs/static/img/model-blocks-overview.png
vendored
Normal file
|
After Width: | Height: | Size: 1.7 MiB |
BIN
docs/static/img/prompts-blocks-overview.png
vendored
Normal file
|
After Width: | Height: | Size: 1.5 MiB |
BIN
docs/static/img/rules-blocks-overview.png
vendored
Normal file
|
After Width: | Height: | Size: 1.3 MiB |
|
|
@ -1,6 +1,6 @@
|
|||
<component name="ProjectRunConfigurationManager">
|
||||
<configuration default="false" name="IDE Logs" type="ShConfigurationType">
|
||||
<option name="SCRIPT_TEXT" value="mkdir -p ./extensions/.continue-debug/logs && touch ./extensions/.continue-debug/logs/prompt.log && tail -f ./extensions/intellij/build/idea-sandbox/system/log/idea.log" />
|
||||
<option name="SCRIPT_TEXT" value="mkdir -p ./extensions/intellij/build/idea-sandbox/system/log && touch ./extensions/intellij/build/idea-sandbox/system/log/idea.log && tail -f ./extensions/intellij/build/idea-sandbox/system/log/idea.log" />
|
||||
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
|
||||
<option name="SCRIPT_PATH" value="mkdir -p ./extensions/.continue-debug/logs && touch ./extensions/.continue-debug/logs/prompt.log && tail -f ./extensions/.continue-debug/logs/prompt.log" />
|
||||
<option name="SCRIPT_OPTIONS" value="" />
|
||||
|
|
|
|||
|
|
@ -4,6 +4,16 @@
|
|||
<env name="CONTINUE_DEVELOPMENT" value="true" />
|
||||
<env name="CONTINUE_GLOBAL_DIR" value="$PROJECT_DIR$/extensions/.continue-debug" />
|
||||
</envs>
|
||||
<method v="2" />
|
||||
<method v="2">
|
||||
<option name="NpmBeforeRunTask" enabled="true">
|
||||
<package-json value="$PROJECT_DIR$/binary/package.json" />
|
||||
<command value="run" />
|
||||
<scripts>
|
||||
<script value="rebuild" />
|
||||
</scripts>
|
||||
<node-interpreter value="project" />
|
||||
<envs />
|
||||
</option>
|
||||
</method>
|
||||
</configuration>
|
||||
</component>
|
||||
|
|
@ -52,7 +52,7 @@ notes below).
|
|||
|
||||
### Node.js Requirements
|
||||
|
||||
This project requires Node.js version 20.11.0 (LTS) or higher. You have two options for installation:
|
||||
This project requires Node.js version 20.19.0 (LTS) or higher. You have two options for installation:
|
||||
|
||||
1. Download and install directly from [nodejs.org](https://nodejs.org/en/download).
|
||||
2. If you're using NVM (Node Version Manager), set the correct Node.js version for this project by running `nvm use` in
|
||||
|
|
|
|||
|
|
@ -3,12 +3,13 @@ pluginGroup=com.github.continuedev.continueintellijextension
|
|||
pluginName=continue-intellij-extension
|
||||
pluginRepositoryUrl=https://github.com/continuedev/continue
|
||||
# SemVer format -> https://semver.org
|
||||
pluginVersion=1.0.13
|
||||
pluginVersion=1.0.14
|
||||
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
|
||||
pluginSinceBuild=223
|
||||
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
|
||||
platformType=IC
|
||||
platformVersion=2022.3.3
|
||||
#org.gradle.java.home=/opt/homebrew/opt/openjdk@17
|
||||
#platformVersion = LATEST-EAP-SNAPSHOT
|
||||
# Plugin Dependencies -> https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html
|
||||
# Example: platformPlugins = com.intellij.java, com.jetbrains.php:203.4449.22
|
||||
|
|
|
|||
|
|
@ -5,3 +5,4 @@ networkTimeout=10000
|
|||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
#org.gradle.java.home=/opt/homebrew/opt/openjdk@17
|
||||
|
|
@ -126,3 +126,16 @@ class OpenConfigAction : AnAction() {
|
|||
continuePluginService.sendToWebview("navigateTo", params)
|
||||
}
|
||||
}
|
||||
|
||||
class OpenLogsAction : AnAction() {
|
||||
override fun actionPerformed(e: AnActionEvent) {
|
||||
val project = e.project ?: return
|
||||
val logFile = java.io.File(System.getProperty("user.home") + "/.continue/logs/core.log")
|
||||
if (logFile.exists()) {
|
||||
val virtualFile = com.intellij.openapi.vfs.LocalFileSystem.getInstance().findFileByIoFile(logFile)
|
||||
if (virtualFile != null) {
|
||||
com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project).openFile(virtualFile, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
package com.github.continuedev.continueintellijextension.activities
|
||||
|
||||
import IntelliJIDE
|
||||
import com.intellij.openapi.fileEditor.FileEditorManagerListener
|
||||
import com.github.continuedev.continueintellijextension.auth.AuthListener
|
||||
|
|
@ -153,11 +154,13 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
|
|||
val connection = ApplicationManager.getApplication().messageBus.connect()
|
||||
connection.subscribe(SettingsListener.TOPIC, object : SettingsListener {
|
||||
override fun settingsUpdated(settings: ContinueExtensionSettings.ContinueState) {
|
||||
continuePluginService.coreMessenger?.request("config/ideSettingsUpdate", mapOf(
|
||||
"remoteConfigServerUrl" to settings.remoteConfigServerUrl,
|
||||
"remoteConfigSyncPeriod" to settings.remoteConfigSyncPeriod,
|
||||
"userToken" to settings.userToken,
|
||||
), null) { _ -> }
|
||||
continuePluginService.coreMessenger?.request(
|
||||
"config/ideSettingsUpdate", mapOf(
|
||||
"remoteConfigServerUrl" to settings.remoteConfigServerUrl,
|
||||
"remoteConfigSyncPeriod" to settings.remoteConfigSyncPeriod,
|
||||
"userToken" to settings.userToken,
|
||||
), null
|
||||
) { _ -> }
|
||||
}
|
||||
})
|
||||
|
||||
|
|
@ -205,6 +208,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
|
|||
continuePluginService.coreMessenger?.request("files/closed", data, null) { _ -> }
|
||||
}
|
||||
}
|
||||
|
||||
override fun fileOpened(source: FileEditorManager, file: VirtualFile) {
|
||||
file.toUriOrNull()?.let { uri ->
|
||||
val data = mapOf("uris" to listOf(uri))
|
||||
|
|
@ -214,7 +218,6 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
|
|||
})
|
||||
|
||||
|
||||
|
||||
// Listen for theme changes
|
||||
connection.subscribe(LafManagerListener.TOPIC, LafManagerListener {
|
||||
val colors = GetTheme().getTheme();
|
||||
|
|
|
|||
|
|
@ -3,12 +3,17 @@ package com.github.continuedev.continueintellijextension.auth
|
|||
import com.intellij.openapi.ui.DialogWrapper
|
||||
import com.intellij.ui.components.JBLabel
|
||||
import com.intellij.ui.components.JBTextField
|
||||
import com.intellij.ui.HyperlinkLabel
|
||||
import javax.swing.JComponent
|
||||
import javax.swing.JPanel
|
||||
import java.awt.BorderLayout
|
||||
import javax.swing.BoxLayout
|
||||
|
||||
class ContinueAuthDialog(private val useOnboarding: Boolean, private val onTokenEntered: (String) -> Unit) :
|
||||
DialogWrapper(true) {
|
||||
class ContinueAuthDialog(
|
||||
private val useOnboarding: Boolean,
|
||||
private val authUrl: String? = null,
|
||||
private val onTokenEntered: (String) -> Unit,
|
||||
) : DialogWrapper(true) {
|
||||
private val tokenField = JBTextField()
|
||||
|
||||
init {
|
||||
|
|
@ -18,9 +23,22 @@ class ContinueAuthDialog(private val useOnboarding: Boolean, private val onToken
|
|||
|
||||
override fun createCenterPanel(): JComponent {
|
||||
val panel = JPanel(BorderLayout())
|
||||
val topPanel = JPanel()
|
||||
topPanel.layout = BoxLayout(topPanel, BoxLayout.Y_AXIS)
|
||||
|
||||
val message =
|
||||
if (useOnboarding) "After onboarding you will be shown an authentication token. Please enter it here:" else "Please enter your Continue authentication token:"
|
||||
panel.add(JBLabel(message), BorderLayout.NORTH)
|
||||
topPanel.add(JBLabel(message))
|
||||
topPanel.add(javax.swing.Box.createVerticalStrut(10))
|
||||
|
||||
if (authUrl != null) {
|
||||
val linkLabel = HyperlinkLabel("Open authentication page")
|
||||
linkLabel.setHyperlinkTarget(authUrl)
|
||||
topPanel.add(linkLabel)
|
||||
topPanel.add(javax.swing.Box.createVerticalStrut(10))
|
||||
}
|
||||
|
||||
panel.add(topPanel, BorderLayout.NORTH)
|
||||
panel.add(tokenField, BorderLayout.CENTER)
|
||||
return panel
|
||||
}
|
||||
|
|
|
|||
|
|
@ -53,11 +53,11 @@ class ContinueAuthService {
|
|||
|
||||
fun startAuthFlow(project: Project, useOnboarding: Boolean) {
|
||||
// Open login page
|
||||
openSignInPage(project, useOnboarding)
|
||||
val url = openSignInPage(project, useOnboarding)
|
||||
|
||||
// Open a dialog where the user should paste their sign-in token
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
val dialog = ContinueAuthDialog(useOnboarding) { token ->
|
||||
val dialog = ContinueAuthDialog(useOnboarding, url) { token ->
|
||||
// Store the token
|
||||
updateRefreshToken(token)
|
||||
}
|
||||
|
|
@ -144,18 +144,31 @@ class ContinueAuthService {
|
|||
}
|
||||
|
||||
|
||||
private fun openSignInPage(project: Project, useOnboarding: Boolean) {
|
||||
private fun openSignInPage(project: Project, useOnboarding: Boolean): String? {
|
||||
var authUrl: String? = null
|
||||
val coreMessenger = project.service<ContinuePluginService>().coreMessenger
|
||||
|
||||
// Use a blocking approach to get the URL
|
||||
val latch = java.util.concurrent.CountDownLatch(1)
|
||||
|
||||
coreMessenger?.request(
|
||||
"auth/getAuthUrl", mapOf(
|
||||
"useOnboarding" to useOnboarding
|
||||
), null
|
||||
) { response ->
|
||||
val authUrl = ((response as? Map<*, *>)?.get("content") as? Map<*, *>)?.get("url") as? String
|
||||
if (authUrl != null) {
|
||||
Desktop.browse(java.net.URI(authUrl))
|
||||
}
|
||||
authUrl = ((response as? Map<*, *>)?.get("content") as? Map<*, *>)?.get("url") as? String
|
||||
latch.countDown()
|
||||
}
|
||||
|
||||
// Wait for the response with a reasonable timeout
|
||||
latch.await(5, java.util.concurrent.TimeUnit.SECONDS)
|
||||
|
||||
// Still open the URL in the browser (keeping existing behavior)
|
||||
if (authUrl != null) {
|
||||
Desktop.browse(java.net.URI(authUrl))
|
||||
}
|
||||
|
||||
return authUrl
|
||||
}
|
||||
|
||||
private fun retrieveSecret(key: String): String? {
|
||||
|
|
|
|||
|
|
@ -56,27 +56,34 @@ class CoreMessengerManager(
|
|||
}
|
||||
|
||||
private fun setupCoreMessenger(continueCorePath: String) {
|
||||
coreMessenger = CoreMessenger(project, continueCorePath, ideProtocolClient, coroutineScope)
|
||||
try {
|
||||
coreMessenger = CoreMessenger(project, continueCorePath, ideProtocolClient, coroutineScope)
|
||||
|
||||
coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
|
||||
val responseObject = response as Map<*, *>
|
||||
val responseContent = responseObject["content"] as Map<*, *>
|
||||
val result = responseContent["result"] as Map<*, *>
|
||||
val config = result["config"] as Map<String, Any>
|
||||
coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
|
||||
val responseObject = response as Map<*, *>
|
||||
val responseContent = responseObject["content"] as Map<*, *>
|
||||
val result = responseContent["result"] as Map<*, *>
|
||||
val config = result["config"] as Map<String, Any>
|
||||
|
||||
val allowAnonymousTelemetry = config?.get("allowAnonymousTelemetry") as? Boolean
|
||||
val telemetryService = service<TelemetryService>()
|
||||
if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) {
|
||||
telemetryService.setup(getMachineUniqueID())
|
||||
val allowAnonymousTelemetry = config?.get("allowAnonymousTelemetry") as? Boolean
|
||||
val telemetryService = service<TelemetryService>()
|
||||
if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) {
|
||||
telemetryService.setup(getMachineUniqueID())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// On exit, use exponential backoff to create another CoreMessenger
|
||||
coreMessenger?.onDidExit {
|
||||
lastBackoffInterval *= 2
|
||||
println("CoreMessenger exited, retrying in $lastBackoffInterval seconds")
|
||||
Thread.sleep((lastBackoffInterval * 1000).toLong())
|
||||
setupCoreMessenger(continueCorePath)
|
||||
// On exit, use exponential backoff to create another CoreMessenger
|
||||
coreMessenger?.onDidExit {
|
||||
lastBackoffInterval *= 2
|
||||
println("CoreMessenger exited, retrying in $lastBackoffInterval seconds")
|
||||
Thread.sleep((lastBackoffInterval * 1000).toLong())
|
||||
setupCoreMessenger(continueCorePath)
|
||||
}
|
||||
} catch (err: Throwable) {
|
||||
val telemetryService = service<TelemetryService>()
|
||||
telemetryService.capture("jetbrains_core_start_error", mapOf("error" to err))
|
||||
|
||||
err.printStackTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ import com.intellij.openapi.project.DumbAware
|
|||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.util.TextRange
|
||||
import com.intellij.openapi.vfs.VirtualFileManager
|
||||
import com.intellij.openapi.wm.ToolWindowManager
|
||||
import kotlinx.coroutines.*
|
||||
import java.awt.Toolkit
|
||||
import java.awt.datatransfer.StringSelection
|
||||
|
|
@ -334,6 +335,14 @@ class IdeProtocolClient(
|
|||
respond(result)
|
||||
}
|
||||
|
||||
"closeSidebar" -> {
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
val toolWindowManager = ToolWindowManager.getInstance(project)
|
||||
val toolWindow = toolWindowManager.getToolWindow("Continue")
|
||||
toolWindow?.hide()
|
||||
}
|
||||
}
|
||||
|
||||
"getSearchResults" -> {
|
||||
val params = Gson().fromJson(
|
||||
dataElement.toString(),
|
||||
|
|
@ -423,6 +432,25 @@ class IdeProtocolClient(
|
|||
}
|
||||
}
|
||||
|
||||
"acceptDiff" -> {
|
||||
val params = Gson().fromJson(
|
||||
dataElement.toString(),
|
||||
AcceptDiffParams::class.java
|
||||
)
|
||||
val filepath = params.filepath;
|
||||
|
||||
acceptOrRejectDiff(filepath, true)
|
||||
}
|
||||
|
||||
"rejectDiff" -> {
|
||||
val params = Gson().fromJson(
|
||||
dataElement.toString(),
|
||||
RejectDiffParams::class.java
|
||||
)
|
||||
val filepath = params.filepath;
|
||||
acceptOrRejectDiff(filepath, false)
|
||||
}
|
||||
|
||||
"applyToFile" -> {
|
||||
val params = Gson().fromJson(
|
||||
dataElement.toString(),
|
||||
|
|
@ -430,24 +458,28 @@ class IdeProtocolClient(
|
|||
)
|
||||
val filepath = params.filepath
|
||||
|
||||
continuePluginService.sendToWebview("updateApplyState", mapOf(
|
||||
"streamId" to params.streamId,
|
||||
"status" to "streaming",
|
||||
"fileContent" to params.text,
|
||||
"toolCallId" to params.toolCallId,
|
||||
"filepath" to filepath
|
||||
))
|
||||
|
||||
|
||||
fun closeStream () {
|
||||
continuePluginService.sendToWebview("updateApplyState", mapOf(
|
||||
"numDiffs" to 0,
|
||||
continuePluginService.sendToWebview(
|
||||
"updateApplyState", mapOf(
|
||||
"streamId" to params.streamId,
|
||||
"status" to "closed",
|
||||
"status" to "streaming",
|
||||
"fileContent" to params.text,
|
||||
"toolCallId" to params.toolCallId,
|
||||
"filepath" to filepath
|
||||
))
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
fun closeStream() {
|
||||
continuePluginService.sendToWebview(
|
||||
"updateApplyState", mapOf(
|
||||
"numDiffs" to 0,
|
||||
"streamId" to params.streamId,
|
||||
"status" to "closed",
|
||||
"fileContent" to params.text,
|
||||
"toolCallId" to params.toolCallId,
|
||||
"filepath" to filepath
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
var editor: Editor? = null;
|
||||
|
|
@ -493,7 +525,7 @@ class IdeProtocolClient(
|
|||
|
||||
val selectedModels = config["selectedModelByRole"] as? Map<*, *>
|
||||
var applyCodeBlockModel = selectedModels?.get("apply") as? Map<*, *>
|
||||
|
||||
|
||||
// If "apply" role model is not found, try "chat" role
|
||||
if (applyCodeBlockModel == null) {
|
||||
applyCodeBlockModel = selectedModels?.get("chat") as? Map<*, *>
|
||||
|
|
@ -555,8 +587,8 @@ class IdeProtocolClient(
|
|||
editor,
|
||||
rif?.range?.start?.line ?: 0,
|
||||
rif?.range?.end?.line ?: (editor.document.lineCount - 1),
|
||||
{},
|
||||
{},
|
||||
{},
|
||||
{},
|
||||
params.streamId,
|
||||
params.toolCallId
|
||||
)
|
||||
|
|
@ -635,6 +667,29 @@ class IdeProtocolClient(
|
|||
continuePluginService.sendToWebview("acceptRejectDiff", AcceptRejectDiff(accepted, stepIndex), uuid())
|
||||
}
|
||||
|
||||
fun acceptOrRejectDiff(filepath: String, accepted: Boolean) {
|
||||
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath)
|
||||
|
||||
if (virtualFile != null) {
|
||||
ApplicationManager.getApplication().invokeAndWait {
|
||||
val openedEditor =
|
||||
FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first()
|
||||
if (openedEditor != null) {
|
||||
val editor: Editor? = FileEditorManager.getInstance(project).selectedTextEditor
|
||||
|
||||
if (editor != null) {
|
||||
val diffStreamService = project.service<DiffStreamService>()
|
||||
if (accepted) {
|
||||
diffStreamService.accept(editor)
|
||||
} else {
|
||||
diffStreamService.reject(editor)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteAtIndex(index: Int) {
|
||||
continuePluginService.sendToWebview("deleteAtIndex", DeleteAtIndex(index), uuid())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ class IntelliJIDE(
|
|||
private val project: Project,
|
||||
private val continuePluginService: ContinuePluginService,
|
||||
|
||||
) : IDE {
|
||||
) : IDE {
|
||||
|
||||
private val gitService = GitService(project, continuePluginService)
|
||||
|
||||
|
|
@ -57,6 +57,19 @@ class IntelliJIDE(
|
|||
val os = getOS()
|
||||
ripgrep =
|
||||
Paths.get(pluginPath.toString(), "ripgrep", "bin", "rg" + if (os == OS.WINDOWS) ".exe" else "").toString()
|
||||
|
||||
// Make ripgrep executable if on Unix-like systems
|
||||
try {
|
||||
if (os == OS.LINUX || os == OS.MAC) {
|
||||
val file = File(ripgrep)
|
||||
if (!file.canExecute()) {
|
||||
file.setExecutable(true)
|
||||
}
|
||||
}
|
||||
} catch (e: Throwable) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -179,6 +192,7 @@ class IntelliJIDE(
|
|||
|
||||
override suspend fun writeFile(path: String, contents: String) {
|
||||
val file = File(URI(path))
|
||||
file.parentFile?.mkdirs()
|
||||
file.writeText(contents)
|
||||
}
|
||||
|
||||
|
|
@ -194,7 +208,13 @@ class IntelliJIDE(
|
|||
}
|
||||
|
||||
override suspend fun openFile(path: String) {
|
||||
val file = LocalFileSystem.getInstance().findFileByPath(URI(path).path)
|
||||
// Convert URI path to absolute file path
|
||||
val filePath = File(URI(path)).absolutePath
|
||||
// Find the file using the absolute path
|
||||
val file = withContext(Dispatchers.IO) {
|
||||
LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath)
|
||||
}
|
||||
|
||||
file?.let {
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
FileEditorManager.getInstance(project).openFile(it, true)
|
||||
|
|
@ -311,7 +331,7 @@ class IntelliJIDE(
|
|||
val ideInfo = this.getIdeInfo()
|
||||
if (ideInfo.remoteName == "local") {
|
||||
val command = GeneralCommandLine(
|
||||
ripgrep,
|
||||
ripgrep,
|
||||
"--files",
|
||||
"--iglob",
|
||||
pattern,
|
||||
|
|
@ -320,37 +340,37 @@ class IntelliJIDE(
|
|||
"--ignore-file",
|
||||
".gitignore",
|
||||
)
|
||||
|
||||
|
||||
command.setWorkDirectory(project.basePath)
|
||||
val results = ExecUtil.execAndGetOutput(command).stdout
|
||||
return results.split("\n")
|
||||
} else {
|
||||
throw NotImplementedError("Ripgrep not supported, this workspace is remote")
|
||||
throw NotImplementedError("Ripgrep not supported, this workspace is remote")
|
||||
|
||||
// Leaving in here for ideas
|
||||
// val projectBasePath = project.basePath ?: return emptyList()
|
||||
// val scope = GlobalSearchScope.projectScope(project)
|
||||
//
|
||||
// // Get all ignore patterns from .continueignore files
|
||||
// val ignorePatterns = mutableSetOf<String>()
|
||||
// VirtualFileManager.getInstance().findFileByUrl("file://$projectBasePath")?.let { root ->
|
||||
// VfsUtil.collectChildrenRecursively(root).forEach { file ->
|
||||
// if (file.name == ".continueignore") {
|
||||
// file.inputStream.bufferedReader().useLines { lines ->
|
||||
// ignorePatterns.addAll(lines.filter { it.isNotBlank() && !it.startsWith("#") })
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// return FilenameIndex.getAllFilesByExt(project, "*", scope)
|
||||
// .filter { file ->
|
||||
// val relativePath = file.path.removePrefix("$projectBasePath/")
|
||||
// // Check if file matches pattern and isn't ignored
|
||||
// PatternUtil.(relativePath, pattern) &&
|
||||
// !ignorePatterns.any { PatternUtil.matchesGlob(relativePath, it) }
|
||||
// }
|
||||
// .map { it.path.removePrefix("$projectBasePath/") }
|
||||
// Leaving in here for ideas
|
||||
// val projectBasePath = project.basePath ?: return emptyList()
|
||||
// val scope = GlobalSearchScope.projectScope(project)
|
||||
//
|
||||
// // Get all ignore patterns from .continueignore files
|
||||
// val ignorePatterns = mutableSetOf<String>()
|
||||
// VirtualFileManager.getInstance().findFileByUrl("file://$projectBasePath")?.let { root ->
|
||||
// VfsUtil.collectChildrenRecursively(root).forEach { file ->
|
||||
// if (file.name == ".continueignore") {
|
||||
// file.inputStream.bufferedReader().useLines { lines ->
|
||||
// ignorePatterns.addAll(lines.filter { it.isNotBlank() && !it.startsWith("#") })
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// return FilenameIndex.getAllFilesByExt(project, "*", scope)
|
||||
// .filter { file ->
|
||||
// val relativePath = file.path.removePrefix("$projectBasePath/")
|
||||
// // Check if file matches pattern and isn't ignored
|
||||
// PatternUtil.(relativePath, pattern) &&
|
||||
// !ignorePatterns.any { PatternUtil.matchesGlob(relativePath, it) }
|
||||
// }
|
||||
// .map { it.path.removePrefix("$projectBasePath/") }
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -358,20 +378,20 @@ class IntelliJIDE(
|
|||
val ideInfo = this.getIdeInfo()
|
||||
if (ideInfo.remoteName == "local") {
|
||||
val command = GeneralCommandLine(
|
||||
ripgrep,
|
||||
"-i",
|
||||
ripgrep,
|
||||
"-i",
|
||||
"--ignore-file",
|
||||
".continueignore",
|
||||
"--ignore-file",
|
||||
".gitignore",
|
||||
"-C",
|
||||
"2",
|
||||
"--heading",
|
||||
"-e",
|
||||
query,
|
||||
".gitignore",
|
||||
"-C",
|
||||
"2",
|
||||
"--heading",
|
||||
"-e",
|
||||
query,
|
||||
"."
|
||||
)
|
||||
|
||||
|
||||
command.setWorkDirectory(project.basePath)
|
||||
return ExecUtil.execAndGetOutput(command).stdout
|
||||
} else {
|
||||
|
|
@ -415,7 +435,7 @@ class IntelliJIDE(
|
|||
// return searchResults.toString()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
override suspend fun subprocess(command: String, cwd: String?): List<Any> {
|
||||
val commandList = command.split(" ")
|
||||
|
|
|
|||
|
|
@ -133,8 +133,9 @@ fun openInlineEdit(project: Project?, editor: Editor) {
|
|||
val content = (response as Map<String, Any>)["content"] as Map<String, Any>
|
||||
val result = content["result"] as Map<String, Any>
|
||||
val config = result["config"] as Map<String, Any>
|
||||
val models = config["models"] as List<Map<String, Any>>
|
||||
modelTitles.addAll(models.map { it["title"] as String })
|
||||
val models = config["modelsByRole"] as Map<String, Any>
|
||||
val editModels = models["edit"] as List<Map<String, Any>>
|
||||
modelTitles.addAll(editModels.map { it["title"] as String })
|
||||
}
|
||||
|
||||
// This is a hacky way to not complicate getting model titles with coroutines
|
||||
|
|
|
|||
|
|
@ -15,6 +15,16 @@ data class ApplyToFileParams(
|
|||
val toolCallId: String?
|
||||
)
|
||||
|
||||
data class AcceptDiffParams(
|
||||
val filepath: String,
|
||||
val streamId: String
|
||||
)
|
||||
|
||||
data class RejectDiffParams(
|
||||
val filepath: String,
|
||||
val streamId: String
|
||||
)
|
||||
|
||||
data class InsertAtCursorParams(
|
||||
val text: String
|
||||
)
|
||||
|
|
|
|||
|
|
@ -13,12 +13,16 @@ import com.intellij.openapi.project.DumbAware
|
|||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlin.properties.Delegates
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class ContinuePluginService : Disposable, DumbAware {
|
||||
private val coroutineScope = CoroutineScope(Dispatchers.Main)
|
||||
var continuePluginWindow: ContinuePluginToolWindowFactory.ContinuePluginWindow? = null
|
||||
var ideProtocolClient: IdeProtocolClient? = null
|
||||
var listener: (() -> Unit)? = null
|
||||
var ideProtocolClient: IdeProtocolClient? by Delegates.observable(null) { _, _, _ ->
|
||||
synchronized(this) { listener?.also { listener = null }?.invoke() }
|
||||
}
|
||||
var coreMessengerManager: CoreMessengerManager? = null
|
||||
val coreMessenger: CoreMessenger?
|
||||
get() = coreMessengerManager?.coreMessenger
|
||||
|
|
@ -42,6 +46,25 @@ class ContinuePluginService : Disposable, DumbAware {
|
|||
continuePluginWindow?.browser?.sendToWebview(messageType, data, messageId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a listener for protocolClient initialization.
|
||||
* Currently, only one needs to be processed. If there are more than one,
|
||||
* we can use an array to add listeners to ensure that the message is processed.
|
||||
*/
|
||||
fun onProtocolClientInitialized(listener: () -> Unit) {
|
||||
if (ideProtocolClient == null) {
|
||||
synchronized(this) {
|
||||
if (ideProtocolClient == null) {
|
||||
this.listener = listener
|
||||
} else {
|
||||
listener()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
listener()
|
||||
}
|
||||
}
|
||||
|
||||
fun updateLastFileSaveTimestamp() {
|
||||
ideProtocolClient?.updateLastFileSaveTimestamp()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
package com.github.continuedev.continueintellijextension.toolWindow
|
||||
|
||||
import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable
|
||||
import com.github.continuedev.continueintellijextension.constants.MessageTypes
|
||||
import com.github.continuedev.continueintellijextension.constants.MessageTypes.Companion.PASS_THROUGH_TO_CORE
|
||||
import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
|
|
@ -10,11 +9,11 @@ import com.github.continuedev.continueintellijextension.utils.uuid
|
|||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.JsonParser
|
||||
import com.intellij.openapi.components.ServiceManager
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.util.Disposer
|
||||
import com.intellij.ui.jcef.*
|
||||
import com.intellij.ui.jcef.JBCefClient.Properties
|
||||
import com.intellij.util.application
|
||||
import org.cef.CefApp
|
||||
import org.cef.browser.CefBrowser
|
||||
import org.cef.handler.CefLoadHandlerAdapter
|
||||
|
|
@ -30,8 +29,10 @@ class ContinueBrowser(val project: Project, url: String) {
|
|||
|
||||
val browser: JBCefBrowser
|
||||
|
||||
val continuePluginService: ContinuePluginService = project.getService(ContinuePluginService::class.java)
|
||||
|
||||
init {
|
||||
val isOSREnabled = ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR
|
||||
val isOSREnabled = application.getService(ContinueExtensionSettings::class.java).continueState.enableOSR
|
||||
|
||||
this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(isOSREnabled).build().apply {
|
||||
// To avoid using System.setProperty to affect other plugins,
|
||||
|
|
@ -42,7 +43,6 @@ class ContinueBrowser(val project: Project, url: String) {
|
|||
}
|
||||
|
||||
registerAppSchemeHandler()
|
||||
browser.loadURL(url)
|
||||
Disposer.register(ContinuePluginDisposable.getInstance(project), browser)
|
||||
|
||||
// Listen for events sent from browser
|
||||
|
|
@ -55,11 +55,6 @@ class ContinueBrowser(val project: Project, url: String) {
|
|||
val data = json.get("data")
|
||||
val messageId = json.get("messageId")?.asString
|
||||
|
||||
val continuePluginService = ServiceManager.getService(
|
||||
project,
|
||||
ContinuePluginService::class.java
|
||||
)
|
||||
|
||||
val respond = fun(data: Any?) {
|
||||
sendToWebview(messageType, data, messageId ?: uuid())
|
||||
}
|
||||
|
|
@ -101,6 +96,13 @@ class ContinueBrowser(val project: Project, url: String) {
|
|||
}
|
||||
}, browser.cefBrowser)
|
||||
|
||||
// Load the url only after the protocolClient is initialized,
|
||||
// otherwise some messages will be lost, which are some configurations when the page is loaded.
|
||||
// Moreover, we should add LoadHandler before loading the url.
|
||||
continuePluginService.onProtocolClientInitialized {
|
||||
browser.loadURL(url)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fun executeJavaScript(browser: CefBrowser?, myJSQueryOpenInBrowser: JBCefJSQuery) {
|
||||
|
|
|
|||
|
|
@ -140,6 +140,14 @@
|
|||
<override-text place="GoToAction" text="Continue Config"/>
|
||||
</action>
|
||||
|
||||
<action id="continue.openLogs"
|
||||
class="com.github.continuedev.continueintellijextension.actions.OpenLogsAction"
|
||||
icon="AllIcons.General.ShowInfos"
|
||||
text="Open Logs"
|
||||
description="Open Continue Logs">
|
||||
<override-text place="GoToAction" text="Open Continue Logs"/>
|
||||
</action>
|
||||
|
||||
<group id="ContinueSidebarActionsGroup">
|
||||
<reference ref="continue.newContinueSession"/>
|
||||
<reference ref="continue.viewHistory"/>
|
||||
|
|
|
|||
5
extensions/vscode/.gitignore
vendored
|
|
@ -3,7 +3,6 @@ node_modules/
|
|||
out/
|
||||
.vscode-test/
|
||||
data/
|
||||
src/.buildTimestamp.ts
|
||||
src/client
|
||||
.continue
|
||||
|
||||
|
|
@ -26,5 +25,5 @@ e2e/test-continue/*
|
|||
!e2e/test-continue/config.json
|
||||
e2e/test-continue-yaml/*
|
||||
!e2e/test-continue-yaml/config.yaml
|
||||
|
||||
config-yaml-schema.json
|
||||
config-yaml-schema.json
|
||||
src/.buildTimestamp.ts
|
||||
16
extensions/vscode/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"version": "1.1.24",
|
||||
"version": "1.1.26",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "continue",
|
||||
"version": "1.1.24",
|
||||
"version": "1.1.26",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/fetch": "^1.0.3",
|
||||
|
|
@ -93,7 +93,7 @@
|
|||
"vscode-extension-tester": "^8.10.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.11.0",
|
||||
"node": ">=20.19.0",
|
||||
"vscode": "^1.70.0"
|
||||
}
|
||||
},
|
||||
|
|
@ -164,6 +164,7 @@
|
|||
"web-tree-sitter": "^0.21.0",
|
||||
"win-ca": "^3.5.1",
|
||||
"wink-nlp-utils": "^2.1.0",
|
||||
"winston": "^3.17.0",
|
||||
"workerpool": "^9.1.3",
|
||||
"yaml": "^2.4.2",
|
||||
"zod": "^3.24.2"
|
||||
|
|
@ -198,7 +199,7 @@
|
|||
"typescript": "^5.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.11.0"
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@75lb/deep-merge": {
|
||||
|
|
@ -494,9 +495,10 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@babel/runtime": {
|
||||
"version": "7.26.0",
|
||||
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.0.tgz",
|
||||
"integrity": "sha512-FDSOghenHTiToteC/QRlv2q3DhPZ/oOXTBoirfWNx1Cx3TMVcGWQtMMmQcSvb/JjpNeGzx8Pq/b4fKEJuWm1sw==",
|
||||
"version": "7.27.0",
|
||||
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.27.0.tgz",
|
||||
"integrity": "sha512-VtPOkrdPHZsKc/clNqyi9WUA8TINkZ4cGk63UUE3u4pmB2k+ZMQRDuIOagv8UVd6j7k0T3+RRIb7beKTebNbcw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"regenerator-runtime": "^0.14.0"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"author": "Continue Dev, Inc",
|
||||
"version": "1.1.24",
|
||||
"version": "1.1.26",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/continuedev/continue"
|
||||
|
|
@ -24,7 +24,7 @@
|
|||
"publisher": "Continue",
|
||||
"engines": {
|
||||
"vscode": "^1.70.0",
|
||||
"node": ">=20.11.0"
|
||||
"node": ">=20.19.0"
|
||||
},
|
||||
"engine-strict": true,
|
||||
"galleryBanner": {
|
||||
|
|
|
|||
|
|
@ -576,7 +576,7 @@ const getCommandsMap: (
|
|||
const range =
|
||||
args?.range ?? new vscode.Range(startFromCharZero, endAtCharLast);
|
||||
|
||||
editDecorationManager.setDecoration(editor, range);
|
||||
editDecorationManager.addDecorations(editor, [range]);
|
||||
|
||||
const rangeInFileWithContents = getRangeInFileWithContents(true, range);
|
||||
|
||||
|
|
@ -908,7 +908,7 @@ const getCommandsMap: (
|
|||
|
||||
quickPick.items = [
|
||||
{
|
||||
label: "$(question) Open help center",
|
||||
label: "$(gear) Open settings",
|
||||
},
|
||||
{
|
||||
label: "$(comment) Open chat",
|
||||
|
|
@ -963,7 +963,10 @@ const getCommandsMap: (
|
|||
vscode.commands.executeCommand("continue.focusContinueInput");
|
||||
} else if (selectedOption === "$(screen-full) Open full screen chat") {
|
||||
vscode.commands.executeCommand("continue.toggleFullScreen");
|
||||
} else if (selectedOption === "$(gear) Open settings") {
|
||||
vscode.commands.executeCommand("continue.navigateTo", "/config");
|
||||
}
|
||||
|
||||
quickPick.dispose();
|
||||
});
|
||||
quickPick.show();
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import vscode from "vscode";
|
|||
class EditDecorationManager {
|
||||
private _lastEditor: vscode.TextEditor | undefined;
|
||||
private decorationType: vscode.TextEditorDecorationType;
|
||||
private activeRangesMap: Map<string, vscode.Range> = new Map(); // Store unique active ranges
|
||||
|
||||
constructor(context: vscode.ExtensionContext) {
|
||||
this.decorationType = vscode.window.createTextEditorDecorationType({
|
||||
|
|
@ -23,18 +24,55 @@ class EditDecorationManager {
|
|||
);
|
||||
}
|
||||
|
||||
setDecoration(editor: vscode.TextEditor, range: vscode.Range) {
|
||||
if (this._lastEditor) {
|
||||
this._lastEditor.setDecorations(this.decorationType, []);
|
||||
// Converts each range to a unique string for storing in the map
|
||||
private rangeToString(range: vscode.Range): string {
|
||||
return `(${range.start.line},${range.start.character})-(${range.end.line},${range.end.character})`;
|
||||
}
|
||||
|
||||
// Checks if two ranges are adjacent or overlapping
|
||||
private rangesCoincide(range1: vscode.Range, range2: vscode.Range): boolean {
|
||||
return range1.start.isEqual(range2.start)
|
||||
|| range1.end.isEqual(range2.start)
|
||||
|| range2.end.isEqual(range1.start)
|
||||
|| !!range1.intersection(range2);
|
||||
}
|
||||
|
||||
// Merges new range with existing ranges in the map
|
||||
private mergeNewRange(newRange: vscode.Range): void {
|
||||
let mergedRange = newRange;
|
||||
const rangesToPrune: string[] = [];
|
||||
|
||||
for (const [key, existingRange] of this.activeRangesMap.entries()) {
|
||||
if (!this.rangesCoincide(mergedRange, existingRange)) continue;
|
||||
mergedRange = mergedRange.union(existingRange);
|
||||
rangesToPrune.push(key);
|
||||
}
|
||||
|
||||
for (const key of rangesToPrune) this.activeRangesMap.delete(key);
|
||||
this.activeRangesMap.set(this.rangeToString(mergedRange), mergedRange);
|
||||
}
|
||||
|
||||
// Adds a new decoration to the editor and merges it with existing ranges
|
||||
addDecorations(editor: vscode.TextEditor, ranges: vscode.Range[]): void {
|
||||
if (this._lastEditor?.document !== editor.document) {
|
||||
this.clear(); // Clear previous decorations if editor has changed
|
||||
}
|
||||
editor.setDecorations(this.decorationType, [range]);
|
||||
this._lastEditor = editor;
|
||||
|
||||
for (const range of ranges) this.mergeNewRange(range);
|
||||
|
||||
const activeRanges = Array.from(this.activeRangesMap.values());
|
||||
if (activeRanges.length === 0) return; // No ranges to highlight
|
||||
|
||||
// Update active ranges and apply decorations
|
||||
editor.setDecorations(this.decorationType, activeRanges);
|
||||
this.updateInEditMode(true);
|
||||
}
|
||||
|
||||
clear() {
|
||||
if (this._lastEditor) {
|
||||
this._lastEditor.setDecorations(this.decorationType, []);
|
||||
this.activeRangesMap.clear();
|
||||
this._lastEditor = undefined;
|
||||
this.updateInEditMode(false);
|
||||
}
|
||||
|
|
|
|||
14
gui/package-lock.json
generated
|
|
@ -97,7 +97,7 @@
|
|||
"vitest": "^2.1.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.11.0"
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
},
|
||||
"../core": {
|
||||
|
|
@ -167,6 +167,7 @@
|
|||
"web-tree-sitter": "^0.21.0",
|
||||
"win-ca": "^3.5.1",
|
||||
"wink-nlp-utils": "^2.1.0",
|
||||
"winston": "^3.17.0",
|
||||
"workerpool": "^9.1.3",
|
||||
"yaml": "^2.4.2",
|
||||
"zod": "^3.24.2"
|
||||
|
|
@ -201,7 +202,7 @@
|
|||
"typescript": "^5.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.11.0"
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
},
|
||||
"../packages/config-yaml": {
|
||||
|
|
@ -4363,9 +4364,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/caniuse-lite": {
|
||||
"version": "1.0.30001662",
|
||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001662.tgz",
|
||||
"integrity": "sha512-sgMUVwLmGseH8ZIrm1d51UbrhqMCH3jvS7gF/M6byuHOnKyLOBL7W8yz5V02OHwgLGA36o/AFhWzzh4uc5aqTA==",
|
||||
"version": "1.0.30001715",
|
||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001715.tgz",
|
||||
"integrity": "sha512-7ptkFGMm2OAOgvZpwgA4yjQ5SQbrNVGdRjzH0pBdy1Fasvcr+KAeECmbCAECzTuDuoX0FCY8KzUxjf9+9kfZEw==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "opencollective",
|
||||
|
|
@ -4379,7 +4380,8 @@
|
|||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ai"
|
||||
}
|
||||
]
|
||||
],
|
||||
"license": "CC-BY-4.0"
|
||||
},
|
||||
"node_modules/ccount": {
|
||||
"version": "2.0.1",
|
||||
|
|
|
|||
|
|
@ -106,6 +106,6 @@
|
|||
},
|
||||
"engine-strict": true,
|
||||
"engines": {
|
||||
"node": ">=20.11.0"
|
||||
"node": ">=20.19.0"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ const router = createMemoryRouter([
|
|||
Prevents entire app from rerendering continuously with useSetup in App
|
||||
TODO - look into a more redux-esque way to do this
|
||||
*/
|
||||
function SetupListeners() {
|
||||
export function SetupListeners() {
|
||||
useSetup();
|
||||
return <></>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,6 +39,17 @@ export default function AddFileCombobox({
|
|||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
// update selectedFiles showing only the files that are in codeToEdit
|
||||
setSelectedFiles(
|
||||
(prevSelectedFiles) =>
|
||||
prevSelectedFiles.filter(
|
||||
(file) =>
|
||||
codeToEdit.findIndex((code) => code.filepath === file.id) !== -1,
|
||||
),
|
||||
);
|
||||
}, [codeToEdit]);
|
||||
|
||||
const filteredFiles =
|
||||
query === ""
|
||||
? remainingFiles
|
||||
|
|
@ -55,12 +66,14 @@ export default function AddFileCombobox({
|
|||
setSelectedFiles(files);
|
||||
void onSelect(files.map((file) => file.id));
|
||||
buttonRef.current?.click();
|
||||
setQuery("");
|
||||
}}
|
||||
>
|
||||
{({ open }) => (
|
||||
<div className="relative">
|
||||
<ComboboxButton className="hidden" ref={buttonRef} />
|
||||
<ComboboxInput
|
||||
value={query}
|
||||
ref={inputRef}
|
||||
onClick={() => {
|
||||
if (!open) {
|
||||
|
|
|
|||
|
|
@ -48,9 +48,17 @@ export function ApplyActions(props: ApplyActionsProps) {
|
|||
);
|
||||
|
||||
switch (props.applyState ? props.applyState.status : null) {
|
||||
case "not-started":
|
||||
return (
|
||||
<div className="flex select-none items-center rounded bg-zinc-700 pl-2 pr-1">
|
||||
<span className="text-lightgray inline-flex w-min items-center gap-2 text-center text-xs">
|
||||
Pending
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
case "streaming":
|
||||
return (
|
||||
<div className="flex items-center rounded bg-zinc-700 pl-2 pr-1">
|
||||
<div className="flex select-none items-center rounded bg-zinc-700 pl-2 pr-1">
|
||||
<span className="text-lightgray inline-flex w-min items-center gap-2 text-center text-xs">
|
||||
Applying
|
||||
<Spinner />
|
||||
|
|
@ -59,7 +67,7 @@ export function ApplyActions(props: ApplyActionsProps) {
|
|||
);
|
||||
case "done":
|
||||
return (
|
||||
<div className="flex items-center rounded bg-zinc-700 px-1.5 sm:gap-1">
|
||||
<div className="flex select-none items-center rounded bg-zinc-700 px-1.5 sm:gap-1">
|
||||
<span className="max-xs:hidden text-lightgray text-center text-xs">
|
||||
{`${props.applyState?.numDiffs === 1 ? "1 diff" : `${props.applyState?.numDiffs} diffs`}`}
|
||||
</span>
|
||||
|
|
@ -84,18 +92,15 @@ export function ApplyActions(props: ApplyActionsProps) {
|
|||
</div>
|
||||
);
|
||||
case "closed":
|
||||
if (!hasRejected && props.applyState?.numDiffs === 0) {
|
||||
if (showApplied) {
|
||||
if (isSuccessful) {
|
||||
if (showApplied || props.disableManualApply) {
|
||||
return (
|
||||
<span className="flex items-center rounded bg-zinc-700 text-slate-400 max-sm:px-0.5 sm:pl-2">
|
||||
<span className="flex select-none items-center rounded bg-zinc-700 text-slate-400 max-sm:px-0.5 sm:pl-2">
|
||||
<span className="max-sm:hidden">Applied</span>
|
||||
<CheckIcon className="h-3.5 w-3.5 hover:brightness-125 sm:px-1" />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (props.disableManualApply) {
|
||||
return null;
|
||||
}
|
||||
return applyButton("Reapply");
|
||||
}
|
||||
default:
|
||||
|
|
|
|||
|
|
@ -15,7 +15,9 @@ export function CreateFileButton({ onClick }: CreateFileButtonProps) {
|
|||
>
|
||||
<div className="flex items-center gap-1">
|
||||
<DocumentPlusIcon className="h-3.5 w-3.5 shrink-0" />
|
||||
<span className="line-clamp-1 break-all">Create file</span>
|
||||
<span className="line-clamp-1 select-none break-all">
|
||||
Create file
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
</>
|
||||
|
|
|
|||