Merge branch 'main' into feat/watsonx_reranker_integration
This commit is contained in:
commit
e26d18924a
171 changed files with 4394 additions and 2274 deletions
|
|
@ -5,4 +5,5 @@ docs/docs/languages
|
|||
.vscode/
|
||||
.archive/
|
||||
**/*.scm
|
||||
**/*.diff
|
||||
**/*.diff
|
||||
.continue/
|
||||
1
.github/CODEOWNERS
vendored
Normal file
1
.github/CODEOWNERS
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
* @continuedev/continue-code-reviewers
|
||||
7
.github/workflows/pr_checks.yaml
vendored
7
.github/workflows/pr_checks.yaml
vendored
|
|
@ -275,7 +275,7 @@ jobs:
|
|||
cd core
|
||||
npm test
|
||||
env:
|
||||
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true && github.actor == 'dependabot[bot]' }}
|
||||
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
|
||||
|
|
@ -420,8 +420,7 @@ jobs:
|
|||
id: test-extensions-cache
|
||||
with:
|
||||
path: extensions/vscode/e2e/.test-extensions
|
||||
# package.json used as the key because that's where the download script is defined
|
||||
key: vscode-test-extensions-${{ hashFiles('extensions/vscode/package.json') }}
|
||||
key: CONSTANT
|
||||
|
||||
- name: Download build artifact
|
||||
uses: actions/download-artifact@v4
|
||||
|
|
@ -460,7 +459,7 @@ jobs:
|
|||
- name: Run e2e tests
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }}
|
||||
IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }}
|
||||
env:
|
||||
DISPLAY: :99
|
||||
|
||||
|
|
|
|||
3
.gitignore
vendored
3
.gitignore
vendored
|
|
@ -168,4 +168,5 @@ extensions/.continue-debug/
|
|||
|
||||
*.vsix
|
||||
|
||||
.continuerules
|
||||
.continuerules
|
||||
**/.continue/assistants/
|
||||
|
|
@ -14,4 +14,5 @@ gui/dist
|
|||
**/.continueignore
|
||||
CHANGELOG.md
|
||||
**/continue_tutorial.py
|
||||
**/node_modules
|
||||
**/node_modules
|
||||
**/CODEOWNERS
|
||||
|
|
@ -8,7 +8,7 @@
|
|||
|
||||
<div align="center">
|
||||
|
||||
**[Continue](https://docs.continue.dev) enables to developers to create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
|
||||
**[Continue](https://docs.continue.dev) enables developers to create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
|
||||
|
||||
</div>
|
||||
|
||||
|
|
|
|||
6
binary/package-lock.json
generated
6
binary/package-lock.json
generated
|
|
@ -44,9 +44,9 @@
|
|||
"version": "1.0.13",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
|
||||
"@aws-sdk/credential-providers": "^3.620.1",
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.758.0",
|
||||
"@aws-sdk/credential-providers": "^3.758.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "^1.0.52",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
|
|
|
|||
|
|
@ -262,7 +262,7 @@ export class CompletionProvider {
|
|||
|
||||
// When using the JetBrains extension, Mark as displayed
|
||||
const ideType = (await this.ide.getIdeInfo()).ideType;
|
||||
if (ideType === "jetbrains") {
|
||||
if (ideType.toLowerCase() === "jetbrains") {
|
||||
this.markDisplayed(input.completionId, outcome);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,3 @@
|
|||
import * as fs from "node:fs";
|
||||
|
||||
import { ConfigResult, FullSlug } from "@continuedev/config-yaml";
|
||||
|
||||
import {
|
||||
|
|
@ -17,9 +15,8 @@ import {
|
|||
} from "../index.js";
|
||||
import Ollama from "../llm/llms/Ollama.js";
|
||||
import { GlobalContext } from "../util/GlobalContext.js";
|
||||
import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js";
|
||||
import { localPathToUri } from "../util/pathToUri.js";
|
||||
|
||||
import { getAllAssistantFiles } from "./loadLocalAssistants.js";
|
||||
import {
|
||||
LOCAL_ONBOARDING_CHAT_MODEL,
|
||||
LOCAL_ONBOARDING_PROVIDER_TITLE,
|
||||
|
|
@ -53,6 +50,7 @@ export class ConfigHandler {
|
|||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private readonly writeLog: (text: string) => Promise<void>,
|
||||
sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
|
||||
private readonly didSelectOrganization?: (orgId: string | null) => void,
|
||||
) {
|
||||
this.ide = ide;
|
||||
this.ideSettingsPromise = ideSettingsPromise;
|
||||
|
|
@ -86,6 +84,25 @@ export class ConfigHandler {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Users can define as many local assistants as they want in a `.continue/assistants` folder
|
||||
*/
|
||||
private async getLocalAssistantProfiles() {
|
||||
const assistantFiles = await getAllAssistantFiles(this.ide);
|
||||
const profiles = assistantFiles.map((assistant) => {
|
||||
return new LocalProfileLoader(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
assistant,
|
||||
);
|
||||
});
|
||||
return profiles.map(
|
||||
(profile) => new ProfileLifecycleManager(profile, this.ide),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the titles of additional context providers that are of type "submenu".
|
||||
*
|
||||
|
|
@ -103,8 +120,9 @@ export class ConfigHandler {
|
|||
} catch (e) {
|
||||
// If this fails, make sure at least local profile is loaded
|
||||
console.error("Failed to fetch control plane profiles in init: ", e);
|
||||
await this.updateAvailableProfiles([this.localProfileManager]);
|
||||
await this.loadLocalProfilesOnly();
|
||||
}
|
||||
|
||||
try {
|
||||
const configResult = await this.loadConfig();
|
||||
this.notifyConfigListeners(configResult);
|
||||
|
|
@ -135,14 +153,12 @@ export class ConfigHandler {
|
|||
|
||||
async openConfigProfile(profileId?: string) {
|
||||
let openProfileId = profileId || this.selectedProfileId;
|
||||
if (openProfileId === "local") {
|
||||
const profile = this.profiles?.find(
|
||||
(p) => p.profileDescription.id === openProfileId,
|
||||
);
|
||||
if (profile?.profileDescription.profileType === "local") {
|
||||
const ideInfo = await this.ide.getIdeInfo();
|
||||
const configYamlPath = getConfigYamlPath(ideInfo.ideType);
|
||||
if (fs.existsSync(configYamlPath)) {
|
||||
await this.ide.openFile(localPathToUri(configYamlPath));
|
||||
} else {
|
||||
await this.ide.openFile(localPathToUri(getConfigJsonPath()));
|
||||
}
|
||||
await this.ide.openFile(profile.profileDescription.uri);
|
||||
} else {
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
|
||||
|
|
@ -161,35 +177,39 @@ export class ConfigHandler {
|
|||
let profiles: ProfileLifecycleManager[] | null = null;
|
||||
if (!userId) {
|
||||
// Not logged in
|
||||
profiles = [this.localProfileManager];
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
profiles = [...allLocalProfiles];
|
||||
} else {
|
||||
// Logged in
|
||||
const assistants =
|
||||
await this.controlPlaneClient.listAssistants(selectedOrgId);
|
||||
|
||||
const hubProfiles = assistants.map((assistant) => {
|
||||
const profileLoader = new PlatformProfileLoader(
|
||||
{
|
||||
...assistant.configResult,
|
||||
config: assistant.configResult.config,
|
||||
},
|
||||
assistant.ownerSlug,
|
||||
assistant.packageSlug,
|
||||
assistant.iconUrl,
|
||||
assistant.configResult.config?.version ?? "latest",
|
||||
this.controlPlaneClient,
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.writeLog,
|
||||
this.reloadConfig.bind(this),
|
||||
);
|
||||
const hubProfiles = await Promise.all(
|
||||
assistants.map(async (assistant) => {
|
||||
const profileLoader = await PlatformProfileLoader.create(
|
||||
{
|
||||
...assistant.configResult,
|
||||
config: assistant.configResult.config,
|
||||
},
|
||||
assistant.ownerSlug,
|
||||
assistant.packageSlug,
|
||||
assistant.iconUrl,
|
||||
assistant.configResult.config?.version ?? "latest",
|
||||
this.controlPlaneClient,
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.writeLog,
|
||||
this.reloadConfig.bind(this),
|
||||
);
|
||||
|
||||
return new ProfileLifecycleManager(profileLoader, this.ide);
|
||||
});
|
||||
return new ProfileLifecycleManager(profileLoader, this.ide);
|
||||
}),
|
||||
);
|
||||
|
||||
if (selectedOrgId === null) {
|
||||
// Personal
|
||||
profiles = [...hubProfiles, this.localProfileManager];
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
profiles = [...hubProfiles, ...allLocalProfiles];
|
||||
} else {
|
||||
// Organization
|
||||
profiles = hubProfiles;
|
||||
|
|
@ -199,6 +219,16 @@ export class ConfigHandler {
|
|||
await this.updateAvailableProfiles(profiles);
|
||||
}
|
||||
|
||||
private async getAllLocalProfiles() {
|
||||
const localAssistantProfiles = await this.getLocalAssistantProfiles();
|
||||
return [this.localProfileManager, ...localAssistantProfiles];
|
||||
}
|
||||
|
||||
private async loadLocalProfilesOnly() {
|
||||
const allLocalProfiles = await this.getAllLocalProfiles();
|
||||
await this.updateAvailableProfiles(allLocalProfiles);
|
||||
}
|
||||
|
||||
private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) {
|
||||
this.profiles = profiles;
|
||||
|
||||
|
|
@ -278,7 +308,7 @@ export class ConfigHandler {
|
|||
} else {
|
||||
try {
|
||||
const workspaces = await this.controlPlaneClient.listWorkspaces();
|
||||
const profiles = [this.localProfileManager];
|
||||
const profiles = await this.getAllLocalProfiles();
|
||||
workspaces.forEach((workspace) => {
|
||||
const profileLoader = new ControlPlaneProfileLoader(
|
||||
workspace.id,
|
||||
|
|
@ -296,7 +326,7 @@ export class ConfigHandler {
|
|||
await this.updateAvailableProfiles(profiles);
|
||||
} catch (e: any) {
|
||||
console.error("Failed to load profiles: ", e);
|
||||
await this.updateAvailableProfiles([this.localProfileManager]);
|
||||
await this.loadLocalProfilesOnly();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -311,7 +341,8 @@ export class ConfigHandler {
|
|||
async getSelectedOrgId(): Promise<string | null> {
|
||||
const selectedOrgs =
|
||||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
return selectedOrgs[await this.getWorkspaceId()] ?? null;
|
||||
const workspaceId = await this.getWorkspaceId();
|
||||
return selectedOrgs[workspaceId] ?? null;
|
||||
}
|
||||
|
||||
async setSelectedOrgId(orgId: string | null) {
|
||||
|
|
@ -319,9 +350,13 @@ export class ConfigHandler {
|
|||
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
|
||||
selectedOrgs[await this.getWorkspaceId()] = orgId;
|
||||
this.globalContext.update("lastSelectedOrgIdForWorkspace", selectedOrgs);
|
||||
this.didSelectOrganization?.(orgId);
|
||||
}
|
||||
|
||||
async setSelectedProfile(profileId: string | null) {
|
||||
console.log(
|
||||
`Changing selected profile from ${this.selectedProfileId} to ${profileId}`,
|
||||
);
|
||||
this.selectedProfileId = profileId;
|
||||
const result = await this.loadConfig();
|
||||
this.notifyConfigListeners(result);
|
||||
|
|
@ -353,9 +388,20 @@ export class ConfigHandler {
|
|||
Promise.resolve(sessionInfo),
|
||||
this.ideSettingsPromise,
|
||||
);
|
||||
|
||||
// After login, default to the first org as the selected org
|
||||
try {
|
||||
const orgs = await this.controlPlaneClient.listOrganizations();
|
||||
if (orgs.length) {
|
||||
await this.setSelectedOrgId(orgs[0].id);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to fetch control plane profiles: ", e);
|
||||
}
|
||||
|
||||
this.fetchControlPlaneProfiles().catch(async (e) => {
|
||||
console.error("Failed to fetch control plane profiles: ", e);
|
||||
await this.updateAvailableProfiles([this.localProfileManager]);
|
||||
await this.loadLocalProfilesOnly();
|
||||
await this.reloadConfig();
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ export interface ProfileDescription {
|
|||
id: string;
|
||||
iconUrl: string;
|
||||
errors: ConfigValidationError[] | undefined;
|
||||
uri: string;
|
||||
}
|
||||
|
||||
export interface OrganizationDescription {
|
||||
|
|
@ -77,14 +78,18 @@ export class ProfileLifecycleManager {
|
|||
// Set pending config promise
|
||||
this.pendingConfigPromise = new Promise(async (resolve, reject) => {
|
||||
let result: ConfigResult<ContinueConfig>;
|
||||
// This try catch is expected to catch high-level errors that aren't block-specific
|
||||
// Like invalid json, invalid yaml, file read errors, etc.
|
||||
// NOT block-specific loading errors
|
||||
try {
|
||||
result = await this.profileLoader.doLoadConfig();
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : "Error loading config";
|
||||
result = {
|
||||
errors: [
|
||||
{
|
||||
fatal: true,
|
||||
message: e.message,
|
||||
message,
|
||||
},
|
||||
],
|
||||
config: undefined,
|
||||
|
|
@ -99,7 +104,6 @@ export class ProfileLifecycleManager {
|
|||
).concat(additionalContextProviders);
|
||||
}
|
||||
|
||||
this.savedConfigResult = result;
|
||||
resolve(result);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -543,18 +543,21 @@ async function intermediateToFinalConfig(
|
|||
// Apply MCP if specified
|
||||
const mcpManager = MCPManagerSingleton.getInstance();
|
||||
if (config.experimental?.modelContextProtocolServers) {
|
||||
await Promise.all(
|
||||
const abortController = new AbortController();
|
||||
const mcpConnectionTimeout = setTimeout(
|
||||
() => abortController.abort(),
|
||||
4000,
|
||||
);
|
||||
|
||||
await Promise.allSettled(
|
||||
config.experimental.modelContextProtocolServers?.map(
|
||||
async (server, index) => {
|
||||
const mcpId = index.toString();
|
||||
const mcpConnection = mcpManager.createConnection(mcpId, server);
|
||||
if (!mcpConnection) {
|
||||
return;
|
||||
}
|
||||
|
||||
const abortController = new AbortController();
|
||||
|
||||
try {
|
||||
const mcpId = index.toString();
|
||||
const mcpConnection = mcpManager.createConnection(mcpId, server);
|
||||
if (!mcpConnection) {
|
||||
return;
|
||||
}
|
||||
const mcpError = await mcpConnection.modifyConfig(
|
||||
continueConfig,
|
||||
mcpId,
|
||||
|
|
@ -565,14 +568,21 @@ async function intermediateToFinalConfig(
|
|||
if (mcpError) {
|
||||
errors.push(mcpError);
|
||||
}
|
||||
} catch (e: any) {
|
||||
} catch (e) {
|
||||
let errorMessage = "Failed to load MCP server";
|
||||
if (e instanceof Error) {
|
||||
if (e.name === "AbortError") {
|
||||
errorMessage += ": connection timed out";
|
||||
} else {
|
||||
errorMessage += ": " + e.message;
|
||||
}
|
||||
}
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Failed to load MCP server: ${e.message}`,
|
||||
message: errorMessage,
|
||||
});
|
||||
if (e.name !== "AbortError") {
|
||||
throw e;
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(mcpConnectionTimeout);
|
||||
}
|
||||
},
|
||||
) || [],
|
||||
|
|
|
|||
79
core/config/loadLocalAssistants.ts
Normal file
79
core/config/loadLocalAssistants.ts
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
import ignore from "ignore";
|
||||
import { IDE } from "..";
|
||||
import {
|
||||
DEFAULT_IGNORE_DIRS,
|
||||
DEFAULT_IGNORE_FILETYPES,
|
||||
} from "../indexing/ignore";
|
||||
import { walkDir } from "../indexing/walkDir";
|
||||
import { getGlobalAssistantsPath } from "../util/paths";
|
||||
import { localPathToUri } from "../util/pathToUri";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
|
||||
export const ASSISTANTS_FOLDER = ".continue/assistants";
|
||||
|
||||
export function isLocalAssistantFile(uri: string): boolean {
|
||||
if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const normalizedUri = uri.replace(/\\/g, "/");
|
||||
return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
|
||||
}
|
||||
|
||||
export async function getAssistantFilesFromDir(
|
||||
ide: IDE,
|
||||
dir: string,
|
||||
): Promise<{ path: string; content: string }[]> {
|
||||
try {
|
||||
const exists = await ide.fileExists(dir);
|
||||
|
||||
if (!exists) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const overrideDefaultIgnores = ignore()
|
||||
.add(DEFAULT_IGNORE_FILETYPES.filter((t) => t !== "config.yaml"))
|
||||
.add(DEFAULT_IGNORE_DIRS);
|
||||
|
||||
const uris = await walkDir(dir, ide, {
|
||||
overrideDefaultIgnores,
|
||||
source: "get assistant files",
|
||||
});
|
||||
const assistantFilePaths = uris.filter(
|
||||
(p) => p.endsWith(".yaml") || p.endsWith(".yml"),
|
||||
);
|
||||
const results = assistantFilePaths.map(async (uri) => {
|
||||
const content = await ide.readFile(uri); // make a try catch
|
||||
return { path: uri, content };
|
||||
});
|
||||
return Promise.all(results);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAllAssistantFiles(
|
||||
ide: IDE,
|
||||
): Promise<{ path: string; content: string }[]> {
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
let assistantFiles: { path: string; content: string }[] = [];
|
||||
|
||||
let dirsToCheck = [ASSISTANTS_FOLDER];
|
||||
const fullDirs = workspaceDirs
|
||||
.map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d)))
|
||||
.flat();
|
||||
|
||||
fullDirs.push(localPathToUri(getGlobalAssistantsPath()));
|
||||
|
||||
assistantFiles = (
|
||||
await Promise.all(fullDirs.map((dir) => getAssistantFilesFromDir(ide, dir)))
|
||||
).flat();
|
||||
|
||||
return await Promise.all(
|
||||
assistantFiles.map(async (file) => {
|
||||
const content = await ide.readFile(file.path);
|
||||
return { path: file.path, content };
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
|
@ -10,6 +10,7 @@ import {
|
|||
} from "../../index.js";
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
|
||||
import { PRODUCTION_ENV } from "../../control-plane/env.js";
|
||||
import doLoadConfig from "./doLoadConfig.js";
|
||||
import { IProfileLoader } from "./IProfileLoader.js";
|
||||
|
||||
|
|
@ -40,6 +41,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
|
|||
},
|
||||
title: workspaceTitle,
|
||||
errors: undefined,
|
||||
uri: `${PRODUCTION_ENV.APP_URL}workspaces/${workspaceId}`,
|
||||
};
|
||||
|
||||
setInterval(async () => {
|
||||
|
|
@ -59,7 +61,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
|
|||
)) as any);
|
||||
const serializedConfig: SerializedContinueConfig = settings;
|
||||
|
||||
const results = await doLoadConfig(
|
||||
return await doLoadConfig(
|
||||
this.ide,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
|
|
@ -68,12 +70,8 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
|
|||
undefined,
|
||||
undefined,
|
||||
this.workspaceId,
|
||||
undefined,
|
||||
);
|
||||
|
||||
return {
|
||||
...results,
|
||||
errors: [], // Don't do config validation here, it happens in admin panel
|
||||
};
|
||||
}
|
||||
|
||||
setIsActive(isActive: boolean): void {}
|
||||
|
|
|
|||
|
|
@ -1,33 +1,57 @@
|
|||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml";
|
||||
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
|
||||
import { getPrimaryConfigFilePath } from "../../util/paths.js";
|
||||
import { localPathToUri } from "../../util/pathToUri.js";
|
||||
import { getUriPathBasename } from "../../util/uri.js";
|
||||
import doLoadConfig from "./doLoadConfig.js";
|
||||
import { IProfileLoader } from "./IProfileLoader.js";
|
||||
|
||||
export default class LocalProfileLoader implements IProfileLoader {
|
||||
static ID = "local";
|
||||
description: ProfileDescription = {
|
||||
id: LocalProfileLoader.ID,
|
||||
profileType: "local",
|
||||
fullSlug: {
|
||||
ownerSlug: "",
|
||||
packageSlug: "",
|
||||
versionSlug: "",
|
||||
},
|
||||
iconUrl: "",
|
||||
title: "Local Config",
|
||||
errors: undefined,
|
||||
};
|
||||
|
||||
constructor(
|
||||
private ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private controlPlaneClient: ControlPlaneClient,
|
||||
private writeLog: (message: string) => Promise<void>,
|
||||
) {}
|
||||
private overrideAssistantFile?:
|
||||
| { path: string; content: string }
|
||||
| undefined,
|
||||
) {
|
||||
const description: ProfileDescription = {
|
||||
id: overrideAssistantFile?.path ?? LocalProfileLoader.ID,
|
||||
profileType: "local",
|
||||
fullSlug: {
|
||||
ownerSlug: "",
|
||||
packageSlug: "",
|
||||
versionSlug: "",
|
||||
},
|
||||
iconUrl: "",
|
||||
title: overrideAssistantFile?.path
|
||||
? getUriPathBasename(overrideAssistantFile.path)
|
||||
: "Local Assistant",
|
||||
errors: undefined,
|
||||
uri:
|
||||
overrideAssistantFile?.path ??
|
||||
localPathToUri(getPrimaryConfigFilePath()),
|
||||
};
|
||||
this.description = description;
|
||||
if (overrideAssistantFile?.content) {
|
||||
try {
|
||||
const parsedAssistant = parseConfigYaml(
|
||||
overrideAssistantFile?.content ?? "",
|
||||
);
|
||||
this.description.title = parsedAssistant.name;
|
||||
} catch (e) {
|
||||
console.error("Failed to parse assistant file: ", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
description: ProfileDescription;
|
||||
|
||||
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
|
||||
const result = await doLoadConfig(
|
||||
|
|
@ -39,6 +63,7 @@ export default class LocalProfileLoader implements IProfileLoader {
|
|||
undefined,
|
||||
undefined,
|
||||
this.description.id,
|
||||
this.overrideAssistantFile?.path,
|
||||
);
|
||||
|
||||
this.description.errors = result.errors;
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
|
|||
|
||||
import { ProfileDescription } from "../ProfileLifecycleManager.js";
|
||||
|
||||
import { getControlPlaneEnv } from "../../control-plane/env.js";
|
||||
import doLoadConfig from "./doLoadConfig.js";
|
||||
import { IProfileLoader } from "./IProfileLoader.js";
|
||||
|
||||
|
|
@ -21,21 +22,35 @@ export interface PlatformConfigMetadata {
|
|||
export default class PlatformProfileLoader implements IProfileLoader {
|
||||
static RELOAD_INTERVAL = 1000 * 5; // 5 seconds
|
||||
|
||||
description: ProfileDescription;
|
||||
|
||||
constructor(
|
||||
private constructor(
|
||||
private configResult: ConfigResult<AssistantUnrolled>,
|
||||
private readonly ownerSlug: string,
|
||||
private readonly packageSlug: string,
|
||||
private readonly iconUrl: string,
|
||||
versionSlug: string,
|
||||
private readonly versionSlug: string,
|
||||
private readonly controlPlaneClient: ControlPlaneClient,
|
||||
private readonly ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private writeLog: (message: string) => Promise<void>,
|
||||
private readonly onReload: () => void,
|
||||
) {
|
||||
this.description = {
|
||||
readonly description: ProfileDescription,
|
||||
) {}
|
||||
|
||||
static async create(
|
||||
configResult: ConfigResult<AssistantUnrolled>,
|
||||
ownerSlug: string,
|
||||
packageSlug: string,
|
||||
iconUrl: string,
|
||||
versionSlug: string,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
ide: IDE,
|
||||
ideSettingsPromise: Promise<IdeSettings>,
|
||||
writeLog: (message: string) => Promise<void>,
|
||||
onReload: () => void,
|
||||
): Promise<PlatformProfileLoader> {
|
||||
const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise);
|
||||
|
||||
const description: ProfileDescription = {
|
||||
id: `${ownerSlug}/${packageSlug}`,
|
||||
profileType: "platform",
|
||||
fullSlug: {
|
||||
|
|
@ -45,12 +60,27 @@ export default class PlatformProfileLoader implements IProfileLoader {
|
|||
},
|
||||
title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`,
|
||||
errors: configResult.errors,
|
||||
iconUrl: this.iconUrl,
|
||||
iconUrl: iconUrl,
|
||||
uri: `${controlPlaneEnv}${ownerSlug}/${packageSlug}`,
|
||||
};
|
||||
|
||||
return new PlatformProfileLoader(
|
||||
configResult,
|
||||
ownerSlug,
|
||||
packageSlug,
|
||||
iconUrl,
|
||||
versionSlug,
|
||||
controlPlaneClient,
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
writeLog,
|
||||
onReload,
|
||||
description,
|
||||
);
|
||||
}
|
||||
|
||||
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
|
||||
if (this.configResult.errors?.length) {
|
||||
if (this.configResult.errors?.find((e) => e.fatal)) {
|
||||
return {
|
||||
config: undefined,
|
||||
errors: this.configResult.errors,
|
||||
|
|
@ -70,11 +100,13 @@ export default class PlatformProfileLoader implements IProfileLoader {
|
|||
packageSlug: this.packageSlug,
|
||||
},
|
||||
this.description.id,
|
||||
undefined,
|
||||
);
|
||||
|
||||
return {
|
||||
...results,
|
||||
errors: [], // Don't do config validation here, it happens in admin panel
|
||||
config: results.config,
|
||||
errors: [...(this.configResult.errors ?? []), ...(results.errors ?? [])],
|
||||
configLoadInterrupted: results.configLoadInterrupted,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -19,13 +19,14 @@ import { getControlPlaneEnv } from "../../control-plane/env.js";
|
|||
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
|
||||
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
|
||||
import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
|
||||
import { localPathOrUriToPath } from "../../util/pathToUri";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
import { TTS } from "../../util/tts";
|
||||
import { loadContinueConfigFromJson } from "../load";
|
||||
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
|
||||
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
|
||||
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
|
||||
import { PlatformConfigMetadata } from "./PlatformProfileLoader";
|
||||
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
|
||||
|
||||
export default async function doLoadConfig(
|
||||
ide: IDE,
|
||||
|
|
@ -36,6 +37,7 @@ export default async function doLoadConfig(
|
|||
overrideConfigYaml: AssistantUnrolled | undefined,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
profileId: string,
|
||||
overrideConfigYamlByPath: string | undefined,
|
||||
): Promise<ConfigResult<ContinueConfig>> {
|
||||
const workspaceConfigs = await getWorkspaceConfigs(ide);
|
||||
const ideInfo = await ide.getIdeInfo();
|
||||
|
|
@ -50,7 +52,9 @@ export default async function doLoadConfig(
|
|||
migrateJsonSharedConfig(configJsonPath, ide);
|
||||
}
|
||||
|
||||
const configYamlPath = getConfigYamlPath(ideInfo.ideType);
|
||||
const configYamlPath = localPathOrUriToPath(
|
||||
overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType),
|
||||
);
|
||||
|
||||
let newConfig: ContinueConfig | undefined;
|
||||
let errors: ConfigValidationError[] | undefined;
|
||||
|
|
@ -68,6 +72,7 @@ export default async function doLoadConfig(
|
|||
overrideConfigYaml,
|
||||
platformConfigMetadata,
|
||||
controlPlaneClient,
|
||||
configYamlPath,
|
||||
);
|
||||
newConfig = result.config;
|
||||
errors = result.errors;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { ModelConfig, AssistantUnrolled } from "@continuedev/config-yaml";
|
||||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
|
||||
import { SerializedContinueConfig } from "../..";
|
||||
|
||||
|
|
@ -6,7 +6,7 @@ export function convertConfigJsonToConfigYaml(
|
|||
configJson: SerializedContinueConfig,
|
||||
): AssistantUnrolled {
|
||||
return {
|
||||
name: "Local Config",
|
||||
name: "Local Assistant",
|
||||
version: "1.0.0",
|
||||
models: [
|
||||
...configJson.models.map(
|
||||
|
|
|
|||
|
|
@ -4,13 +4,13 @@ import { AssistantUnrolled } from "@continuedev/config-yaml";
|
|||
export const defaultConfigYaml: AssistantUnrolled = {
|
||||
models: [],
|
||||
context: [],
|
||||
name: "Local Config",
|
||||
name: "Local Assistant",
|
||||
version: "1.0.0",
|
||||
};
|
||||
|
||||
export const defaultConfigYamlJetBrains: AssistantUnrolled = {
|
||||
models: [],
|
||||
context: [],
|
||||
name: "Local Config",
|
||||
name: "Local Assistant",
|
||||
version: "1.0.0",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -4,8 +4,12 @@ import {
|
|||
AssistantUnrolled,
|
||||
ConfigResult,
|
||||
ConfigValidationError,
|
||||
FQSN,
|
||||
ModelRole,
|
||||
parseAssistantUnrolled,
|
||||
PlatformClient,
|
||||
RegistryClient,
|
||||
SecretResult,
|
||||
unrollAssistantFromContent,
|
||||
validateConfigYaml,
|
||||
} from "@continuedev/config-yaml";
|
||||
import { fetchwithRequestOptions } from "@continuedev/fetch";
|
||||
|
|
@ -16,7 +20,6 @@ import {
|
|||
IDE,
|
||||
IdeInfo,
|
||||
IdeSettings,
|
||||
SlashCommand,
|
||||
} from "../..";
|
||||
import { slashFromCustomCommand } from "../../commands";
|
||||
import { AllRerankers } from "../../context/allRerankers";
|
||||
|
|
@ -41,6 +44,14 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
|||
|
||||
import { llmsFromModelConfig } from "./models";
|
||||
|
||||
export class LocalPlatformClient implements PlatformClient {
|
||||
async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> {
|
||||
return fqsns.map((fqsn) => {
|
||||
return undefined;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function loadConfigYaml(
|
||||
workspaceConfigs: string[],
|
||||
rawYaml: string,
|
||||
|
|
@ -48,14 +59,25 @@ async function loadConfigYaml(
|
|||
ide: IDE,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
): Promise<ConfigResult<AssistantUnrolled>> {
|
||||
// const ideSettings = await ide.getIdeSettings();
|
||||
let config =
|
||||
overrideConfigYaml ??
|
||||
// (ideSettings.continueTestEnvironment === "production"
|
||||
// ? await clientRenderHelper(rawYaml, ide, controlPlaneClient)
|
||||
// :
|
||||
parseAssistantUnrolled(rawYaml);
|
||||
// );
|
||||
// This is how we allow use of blocks locally
|
||||
(await unrollAssistantFromContent(
|
||||
{
|
||||
ownerSlug: "",
|
||||
packageSlug: "",
|
||||
versionSlug: "",
|
||||
},
|
||||
rawYaml,
|
||||
new RegistryClient(),
|
||||
{
|
||||
currentUserSlug: "",
|
||||
onPremProxyUrl: null,
|
||||
orgScopeId: null,
|
||||
platformClient: new LocalPlatformClient(),
|
||||
renderSecrets: true,
|
||||
},
|
||||
));
|
||||
const errors = validateConfigYaml(config);
|
||||
|
||||
if (errors?.some((error) => error.fatal)) {
|
||||
|
|
@ -69,31 +91,11 @@ async function loadConfigYaml(
|
|||
// Set defaults if undefined (this lets us keep config.json uncluttered for new users)
|
||||
return {
|
||||
config,
|
||||
errors: errors.map((error) => ({
|
||||
message: error.message,
|
||||
fatal: error.fatal,
|
||||
})),
|
||||
errors,
|
||||
configLoadInterrupted: false,
|
||||
};
|
||||
}
|
||||
|
||||
async function slashCommandsFromV1PromptFiles(
|
||||
ide: IDE,
|
||||
): Promise<SlashCommand[]> {
|
||||
const slashCommands: SlashCommand[] = [];
|
||||
|
||||
const promptFiles = await getAllPromptFiles(ide, undefined, true);
|
||||
|
||||
for (const file of promptFiles) {
|
||||
const slashCommand = slashCommandFromPromptFileV1(file.path, file.content);
|
||||
if (slashCommand) {
|
||||
slashCommands.push(slashCommand);
|
||||
}
|
||||
}
|
||||
|
||||
return slashCommands;
|
||||
}
|
||||
|
||||
async function configYamlToContinueConfig(
|
||||
config: AssistantUnrolled,
|
||||
ide: IDE,
|
||||
|
|
@ -105,12 +107,9 @@ async function configYamlToContinueConfig(
|
|||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
allowFreeTrial: boolean = true,
|
||||
): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
|
||||
const errors: ConfigValidationError[] = [];
|
||||
const localErrors: ConfigValidationError[] = [];
|
||||
const continueConfig: ContinueConfig = {
|
||||
slashCommands: [
|
||||
...(await slashCommandsFromV1PromptFiles(ide)),
|
||||
...(config.prompts?.map(slashFromCustomCommand) ?? []),
|
||||
],
|
||||
slashCommands: [],
|
||||
models: [],
|
||||
tools: allTools,
|
||||
systemMessage: config.rules?.join("\n"),
|
||||
|
|
@ -152,89 +151,137 @@ async function configYamlToContinueConfig(
|
|||
data: config.data,
|
||||
};
|
||||
|
||||
// Prompt files -
|
||||
try {
|
||||
const promptFiles = await getAllPromptFiles(ide, undefined, true);
|
||||
|
||||
for (const file of promptFiles) {
|
||||
try {
|
||||
const slashCommand = slashCommandFromPromptFileV1(
|
||||
file.path,
|
||||
file.content,
|
||||
);
|
||||
if (slashCommand) {
|
||||
continueConfig.slashCommands?.push(slashCommand);
|
||||
}
|
||||
} catch (e) {
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `Failed to convert prompt file ${file.path} to slash command: ${e instanceof Error ? e.message : e}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `Error loading local prompt files: ${e instanceof Error ? e.message : e}`,
|
||||
});
|
||||
}
|
||||
|
||||
config.prompts?.forEach((prompt) => {
|
||||
try {
|
||||
const slashCommand = slashFromCustomCommand(prompt);
|
||||
continueConfig.slashCommands?.push(slashCommand);
|
||||
} catch (e) {
|
||||
localErrors.push({
|
||||
message: `Error loading prompt ${prompt.name}: ${e instanceof Error ? e.message : e}`,
|
||||
fatal: false,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Models
|
||||
const modelsArrayRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
|
||||
for (const model of config.models ?? []) {
|
||||
model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified
|
||||
const llms = await llmsFromModelConfig(
|
||||
model,
|
||||
ide,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
continueConfig.systemMessage,
|
||||
);
|
||||
try {
|
||||
const llms = await llmsFromModelConfig(
|
||||
model,
|
||||
ide,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
writeLog,
|
||||
platformConfigMetadata,
|
||||
continueConfig.systemMessage,
|
||||
);
|
||||
|
||||
//
|
||||
if (modelsArrayRoles.some((role) => model.roles?.includes(role))) {
|
||||
continueConfig.models.push(...llms);
|
||||
}
|
||||
//
|
||||
if (modelsArrayRoles.some((role) => model.roles?.includes(role))) {
|
||||
continueConfig.models.push(...llms);
|
||||
}
|
||||
|
||||
if (model.roles?.includes("chat")) {
|
||||
continueConfig.modelsByRole.chat.push(...llms);
|
||||
}
|
||||
if (model.roles?.includes("chat")) {
|
||||
continueConfig.modelsByRole.chat.push(...llms);
|
||||
}
|
||||
|
||||
if (model.roles?.includes("summarize")) {
|
||||
continueConfig.modelsByRole.summarize.push(...llms);
|
||||
}
|
||||
if (model.roles?.includes("summarize")) {
|
||||
continueConfig.modelsByRole.summarize.push(...llms);
|
||||
}
|
||||
|
||||
if (model.roles?.includes("apply")) {
|
||||
continueConfig.modelsByRole.apply.push(...llms);
|
||||
}
|
||||
if (model.roles?.includes("apply")) {
|
||||
continueConfig.modelsByRole.apply.push(...llms);
|
||||
}
|
||||
|
||||
if (model.roles?.includes("edit")) {
|
||||
continueConfig.modelsByRole.edit.push(...llms);
|
||||
}
|
||||
if (model.roles?.includes("edit")) {
|
||||
continueConfig.modelsByRole.edit.push(...llms);
|
||||
}
|
||||
|
||||
if (model.roles?.includes("autocomplete")) {
|
||||
continueConfig.modelsByRole.autocomplete.push(...llms);
|
||||
}
|
||||
if (model.roles?.includes("autocomplete")) {
|
||||
continueConfig.modelsByRole.autocomplete.push(...llms);
|
||||
}
|
||||
|
||||
if (model.roles?.includes("embed")) {
|
||||
const { provider, ...options } = model;
|
||||
const embeddingsProviderClass = allEmbeddingsProviders[provider];
|
||||
if (embeddingsProviderClass) {
|
||||
if (
|
||||
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
|
||||
) {
|
||||
continueConfig.modelsByRole.embed.push(new embeddingsProviderClass());
|
||||
if (model.roles?.includes("embed")) {
|
||||
const { provider, ...options } = model;
|
||||
const embeddingsProviderClass = allEmbeddingsProviders[provider];
|
||||
if (embeddingsProviderClass) {
|
||||
if (
|
||||
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
|
||||
) {
|
||||
continueConfig.modelsByRole.embed.push(
|
||||
new embeddingsProviderClass(),
|
||||
);
|
||||
} else {
|
||||
continueConfig.modelsByRole.embed.push(
|
||||
new embeddingsProviderClass(
|
||||
options,
|
||||
(url: string | URL, init: any) =>
|
||||
fetchwithRequestOptions(url, init, {
|
||||
...options.requestOptions,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
continueConfig.modelsByRole.embed.push(
|
||||
new embeddingsProviderClass(
|
||||
options,
|
||||
(url: string | URL, init: any) =>
|
||||
fetchwithRequestOptions(url, init, {
|
||||
...options.requestOptions,
|
||||
}),
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `Unsupported embeddings model provider found: ${provider}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (model.roles?.includes("rerank")) {
|
||||
const { provider, ...options } = model;
|
||||
const rerankerClass = AllRerankers[provider];
|
||||
if (rerankerClass) {
|
||||
continueConfig.modelsByRole.rerank.push(
|
||||
new rerankerClass(options, (url: string | URL, init: any) =>
|
||||
fetchwithRequestOptions(url, init, {
|
||||
...options.requestOptions,
|
||||
}),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `Unsupported reranking model provider found: ${provider}`,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Unsupported embeddings model provider found: ${provider}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (model.roles?.includes("rerank")) {
|
||||
const { provider, ...options } = model;
|
||||
const rerankerClass = AllRerankers[provider];
|
||||
if (rerankerClass) {
|
||||
continueConfig.modelsByRole.rerank.push(
|
||||
new rerankerClass(options, (url: string | URL, init: any) =>
|
||||
fetchwithRequestOptions(url, init, {
|
||||
...options.requestOptions,
|
||||
}),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Unsupported reranking model provider found: ${provider}`,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `Failed to load model:\nName: ${model.name}\nModel: ${model.model}\nProvider: ${model.provider}\n${e instanceof Error ? e.message : e}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -256,9 +303,20 @@ async function configYamlToContinueConfig(
|
|||
(model) => model.providerName === "free-trial",
|
||||
);
|
||||
if (freeTrialModels.length > 0) {
|
||||
const ghAuthToken = await ide.getGitHubAuthToken({});
|
||||
for (const model of freeTrialModels) {
|
||||
(model as FreeTrial).setupGhAuthToken(ghAuthToken);
|
||||
try {
|
||||
const ghAuthToken = await ide.getGitHubAuthToken({});
|
||||
for (const model of freeTrialModels) {
|
||||
(model as FreeTrial).setupGhAuthToken(ghAuthToken);
|
||||
}
|
||||
} catch (e) {
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `Failed to obtain GitHub auth token for free trial:\n${e instanceof Error ? e.message : e}`,
|
||||
});
|
||||
// Remove free trial models
|
||||
continueConfig.models = continueConfig.models.filter(
|
||||
(model) => model.providerName !== "free-trial",
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
|
@ -287,7 +345,10 @@ async function configYamlToContinueConfig(
|
|||
const cls = contextProviderClassFromName(context.provider) as any;
|
||||
if (!cls) {
|
||||
if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.provider)) {
|
||||
console.warn(`Unknown context provider ${context.provider}`);
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `Unknown context provider ${context.provider}`,
|
||||
});
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
|
@ -308,27 +369,27 @@ async function configYamlToContinueConfig(
|
|||
|
||||
// Apply MCP if specified
|
||||
const mcpManager = MCPManagerSingleton.getInstance();
|
||||
await Promise.all(
|
||||
await Promise.allSettled(
|
||||
config.mcpServers?.map(async (server) => {
|
||||
const mcpId = server.name;
|
||||
const mcpConnection = mcpManager.createConnection(mcpId, {
|
||||
transport: {
|
||||
type: "stdio",
|
||||
args: [],
|
||||
...server,
|
||||
},
|
||||
});
|
||||
if (!mcpConnection) {
|
||||
return;
|
||||
}
|
||||
|
||||
const abortController = new AbortController();
|
||||
const mcpConnectionTimeout = setTimeout(
|
||||
() => abortController.abort(),
|
||||
5000,
|
||||
4000,
|
||||
);
|
||||
|
||||
try {
|
||||
const mcpId = server.name;
|
||||
const mcpConnection = mcpManager.createConnection(mcpId, {
|
||||
transport: {
|
||||
type: "stdio",
|
||||
args: [],
|
||||
...server,
|
||||
},
|
||||
});
|
||||
if (!mcpConnection) {
|
||||
return;
|
||||
}
|
||||
|
||||
const mcpError = await mcpConnection.modifyConfig(
|
||||
continueConfig,
|
||||
mcpId,
|
||||
|
|
@ -337,22 +398,28 @@ async function configYamlToContinueConfig(
|
|||
server.faviconUrl,
|
||||
);
|
||||
if (mcpError) {
|
||||
errors.push(mcpError);
|
||||
localErrors.push(mcpError);
|
||||
}
|
||||
} catch (e: any) {
|
||||
errors.push({
|
||||
} catch (e) {
|
||||
let errorMessage = `Failed to load MCP server ${server.name}`;
|
||||
if (e instanceof Error) {
|
||||
if (e.name === "AbortError") {
|
||||
errorMessage += ": connection timed out";
|
||||
} else {
|
||||
errorMessage += ": " + e.message;
|
||||
}
|
||||
}
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `Failed to load MCP server: ${e.message}`,
|
||||
message: errorMessage,
|
||||
});
|
||||
if (e.name !== "AbortError") {
|
||||
throw e;
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(mcpConnectionTimeout);
|
||||
}
|
||||
clearTimeout(mcpConnectionTimeout);
|
||||
}) ?? [],
|
||||
);
|
||||
|
||||
return { config: continueConfig, errors };
|
||||
return { config: continueConfig, errors: localErrors };
|
||||
}
|
||||
|
||||
export async function loadContinueConfigFromYaml(
|
||||
|
|
@ -366,10 +433,14 @@ export async function loadContinueConfigFromYaml(
|
|||
overrideConfigYaml: AssistantUnrolled | undefined,
|
||||
platformConfigMetadata: PlatformConfigMetadata | undefined,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
configYamlPath: string | undefined,
|
||||
): Promise<ConfigResult<ContinueConfig>> {
|
||||
const rawYaml =
|
||||
overrideConfigYaml === undefined
|
||||
? fs.readFileSync(getConfigYamlPath(ideInfo.ideType), "utf-8")
|
||||
? fs.readFileSync(
|
||||
configYamlPath ?? getConfigYamlPath(ideInfo.ideType),
|
||||
"utf-8",
|
||||
)
|
||||
: "";
|
||||
|
||||
const configYamlResult = await loadConfigYaml(
|
||||
|
|
@ -388,28 +459,37 @@ export async function loadContinueConfigFromYaml(
|
|||
};
|
||||
}
|
||||
|
||||
const { config: continueConfig, errors } = await configYamlToContinueConfig(
|
||||
configYamlResult.config,
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
writeLog,
|
||||
workOsAccessToken,
|
||||
platformConfigMetadata,
|
||||
);
|
||||
const { config: continueConfig, errors: localErrors } =
|
||||
await configYamlToContinueConfig(
|
||||
configYamlResult.config,
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
writeLog,
|
||||
workOsAccessToken,
|
||||
platformConfigMetadata,
|
||||
);
|
||||
|
||||
const systemPromptDotFile = await getSystemPromptDotFile(ide);
|
||||
if (systemPromptDotFile) {
|
||||
if (continueConfig.systemMessage) {
|
||||
continueConfig.systemMessage += "\n\n" + systemPromptDotFile;
|
||||
} else {
|
||||
continueConfig.systemMessage = systemPromptDotFile;
|
||||
try {
|
||||
const systemPromptDotFile = await getSystemPromptDotFile(ide);
|
||||
if (systemPromptDotFile) {
|
||||
if (continueConfig.systemMessage) {
|
||||
continueConfig.systemMessage += "\n\n" + systemPromptDotFile;
|
||||
} else {
|
||||
continueConfig.systemMessage = systemPromptDotFile;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `Failed to load system prompt dot file: ${e instanceof Error ? e.message : e}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Apply shared config
|
||||
// TODO: override several of these values with user/org shared config
|
||||
// Don't try catch this - has security implications and failure should be fatal
|
||||
const sharedConfig = new GlobalContext().getSharedConfig();
|
||||
const withShared = modifyAnyConfigWithSharedConfig(
|
||||
continueConfig,
|
||||
|
|
@ -421,7 +501,7 @@ export async function loadContinueConfigFromYaml(
|
|||
|
||||
return {
|
||||
config: withShared,
|
||||
errors: [...(configYamlResult.errors ?? []), ...errors],
|
||||
errors: [...(configYamlResult.errors ?? []), ...localErrors],
|
||||
configLoadInterrupted: false,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,8 +35,11 @@ async function modelConfigToBaseLLM(
|
|||
return undefined;
|
||||
}
|
||||
|
||||
const { capabilities, ...rest } = model;
|
||||
|
||||
let options: LLMOptions = {
|
||||
...model,
|
||||
...rest,
|
||||
// contextLength: model.defaultCompletionOptions?.contextLength ?? undefined,
|
||||
completionOptions: {
|
||||
...(model.defaultCompletionOptions ?? {}),
|
||||
model: model.model,
|
||||
|
|
@ -49,8 +52,28 @@ async function modelConfigToBaseLLM(
|
|||
title: model.name,
|
||||
systemMessage,
|
||||
promptTemplates: model.promptTemplates,
|
||||
capabilities: {
|
||||
tools: model.capabilities?.includes("tool_use"),
|
||||
uploadImage: model.capabilities?.includes("image_input"),
|
||||
},
|
||||
};
|
||||
|
||||
// Model capabilities - need to be undefined if not found
|
||||
// To fallback to our autodetection
|
||||
if (capabilities?.find((c) => c === "tool_use")) {
|
||||
options.capabilities = {
|
||||
...options.capabilities,
|
||||
tools: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (capabilities?.find((c) => c === "image_input")) {
|
||||
options.capabilities = {
|
||||
...options.capabilities,
|
||||
uploadImage: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (model.embedOptions?.maxBatchSize) {
|
||||
options.maxEmbeddingBatchSize = model.embedOptions.maxBatchSize;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
ContextSubmenuItem,
|
||||
IDE,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../..";
|
||||
import DocsService from "../../indexing/docs/DocsService";
|
||||
|
|
@ -36,6 +37,7 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
chunks: Chunk[],
|
||||
reranker: NonNullable<ContextProviderExtras["reranker"]>,
|
||||
fullInput: ContextProviderExtras["fullInput"],
|
||||
ide: IDE,
|
||||
) {
|
||||
let chunksCopy = [...chunks];
|
||||
|
||||
|
|
@ -51,7 +53,7 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
this.options?.nFinal ?? DocsContextProvider.nFinal,
|
||||
);
|
||||
} catch (e) {
|
||||
console.warn(`Failed to rerank docs results: ${e}`);
|
||||
void ide.showToast("warning", `Failed to rerank retrieval results\n${e}`);
|
||||
|
||||
chunksCopy = chunksCopy.splice(
|
||||
0,
|
||||
|
|
@ -116,6 +118,7 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
chunks,
|
||||
extras.reranker,
|
||||
extras.fullInput,
|
||||
extras.ide,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,9 +8,9 @@ import {
|
|||
} from "../../";
|
||||
import { walkDirs } from "../../indexing/walkDir";
|
||||
import {
|
||||
getUriPathBasename,
|
||||
getShortestUniqueRelativeUriPaths,
|
||||
getUriDescription,
|
||||
getUriPathBasename,
|
||||
} from "../../util/uri";
|
||||
|
||||
const MAX_SUBMENU_ITEMS = 10_000;
|
||||
|
|
@ -53,7 +53,13 @@ class FileContextProvider extends BaseContextProvider {
|
|||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const workspaceDirs = await args.ide.getWorkspaceDirs();
|
||||
const results = await walkDirs(args.ide, undefined, workspaceDirs);
|
||||
const results = await walkDirs(
|
||||
args.ide,
|
||||
{
|
||||
source: "load submenu items - file",
|
||||
},
|
||||
workspaceDirs,
|
||||
);
|
||||
const files = results.flat().slice(-MAX_SUBMENU_ITEMS);
|
||||
const withUniquePaths = getShortestUniqueRelativeUriPaths(
|
||||
files,
|
||||
|
|
|
|||
|
|
@ -50,7 +50,9 @@ class FileTreeContextProvider extends BaseContextProvider {
|
|||
directories: [],
|
||||
};
|
||||
|
||||
const uris = await walkDir(workspaceDir, extras.ide);
|
||||
const uris = await walkDir(workspaceDir, extras.ide, {
|
||||
source: "get context items - file tree",
|
||||
});
|
||||
const relativePaths = uris.map(
|
||||
(uri) => findUriInDirs(uri, [workspaceDir]).relativePathOrBasename,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -36,6 +36,7 @@ class FolderContextProvider extends BaseContextProvider {
|
|||
args.ide,
|
||||
{
|
||||
onlyDirs: true,
|
||||
source: "load submenu items - folder",
|
||||
},
|
||||
workspaceDirs,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -36,6 +36,7 @@ class HttpContextProvider extends BaseContextProvider {
|
|||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...(this.options.headers || {}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query: query || "",
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ interface JiraClientOptions {
|
|||
password: string;
|
||||
issueQuery?: string;
|
||||
apiVersion?: string;
|
||||
maxResults?: string;
|
||||
requestOptions?: RequestOptions;
|
||||
}
|
||||
|
||||
|
|
@ -73,6 +74,7 @@ export class JiraClient {
|
|||
"assignee = currentUser() AND resolution = Unresolved order by updated DESC",
|
||||
apiVersion: "3",
|
||||
requestOptions: {},
|
||||
maxResults: "50",
|
||||
...options,
|
||||
};
|
||||
this.baseUrl = `https://${this.options.domain}/rest/api/${this.options.apiVersion}`;
|
||||
|
|
@ -146,7 +148,7 @@ export class JiraClient {
|
|||
`/search?fields=summary&jql=${
|
||||
this.options.issueQuery ??
|
||||
"assignee = currentUser() AND resolution = Unresolved order by updated DESC"
|
||||
}`,
|
||||
}&maxResults=${this.options.maxResults ?? "50"}`,
|
||||
),
|
||||
{
|
||||
method: "GET",
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ class JiraIssuesContextProvider extends BaseContextProvider {
|
|||
issueQuery: this.options.issueQuery,
|
||||
apiVersion: this.options.apiVersion,
|
||||
requestOptions: this.options.requestOptions,
|
||||
maxResults: this.options.maxResults
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -32,8 +33,6 @@ class JiraIssuesContextProvider extends BaseContextProvider {
|
|||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const issueId = query;
|
||||
|
||||
const api = this.getApi();
|
||||
const issue = await api.issue(query, extras.fetch);
|
||||
|
||||
|
|
|
|||
|
|
@ -55,6 +55,7 @@ class RepoMapContextProvider extends BaseContextProvider {
|
|||
args.ide,
|
||||
{
|
||||
onlyDirs: true,
|
||||
source: "load submenu items - repo map",
|
||||
},
|
||||
workspaceDirs,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -80,24 +80,19 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
|||
args: RetrievalPipelineRunArguments,
|
||||
n: number,
|
||||
): Promise<Chunk[]> {
|
||||
try {
|
||||
if (args.query.trim() === "") {
|
||||
return [];
|
||||
}
|
||||
|
||||
const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR ");
|
||||
const tokens = this.escapeFtsQueryString(tokensRaw);
|
||||
|
||||
return await this.ftsIndex.retrieve({
|
||||
n,
|
||||
text: tokens,
|
||||
tags: args.tags,
|
||||
directory: args.filterDirectory,
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn("Error retrieving from FTS:", e);
|
||||
if (args.query.trim() === "") {
|
||||
return [];
|
||||
}
|
||||
|
||||
const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR ");
|
||||
const tokens = this.escapeFtsQueryString(tokensRaw);
|
||||
|
||||
return await this.ftsIndex.retrieve({
|
||||
n,
|
||||
text: tokens,
|
||||
tags: args.tags,
|
||||
directory: args.filterDirectory,
|
||||
});
|
||||
}
|
||||
|
||||
protected async retrieveAndChunkRecentlyEditedFiles(
|
||||
|
|
|
|||
|
|
@ -19,22 +19,42 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
|
||||
let retrievalResults: Chunk[] = [];
|
||||
|
||||
const ftsChunks = await this.retrieveFts(args, ftsNFinal);
|
||||
let ftsChunks: Chunk[] = [];
|
||||
try {
|
||||
ftsChunks = await this.retrieveFts(args, ftsNFinal);
|
||||
} catch (error) {
|
||||
console.error("Error retrieving FTS chunks:", error);
|
||||
}
|
||||
|
||||
const embeddingsChunks = !!config.selectedModelByRole.embed
|
||||
? await this.retrieveEmbeddings(input, embeddingsNFinal)
|
||||
: [];
|
||||
let embeddingsChunks: Chunk[] = [];
|
||||
try {
|
||||
embeddingsChunks = !!config.selectedModelByRole.embed
|
||||
? await this.retrieveEmbeddings(input, embeddingsNFinal)
|
||||
: [];
|
||||
} catch (error) {
|
||||
console.error("Error retrieving embeddings:", error);
|
||||
}
|
||||
|
||||
const recentlyEditedFilesChunks =
|
||||
await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal);
|
||||
let recentlyEditedFilesChunks: Chunk[] = [];
|
||||
try {
|
||||
recentlyEditedFilesChunks =
|
||||
await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal);
|
||||
} catch (error) {
|
||||
console.error("Error retrieving recently edited files:", error);
|
||||
}
|
||||
|
||||
const repoMapChunks = await requestFilesFromRepoMap(
|
||||
this.options.llm,
|
||||
this.options.config,
|
||||
this.options.ide,
|
||||
input,
|
||||
filterDirectory,
|
||||
);
|
||||
let repoMapChunks: Chunk[] = [];
|
||||
try {
|
||||
repoMapChunks = await requestFilesFromRepoMap(
|
||||
this.options.llm,
|
||||
this.options.config,
|
||||
this.options.ide,
|
||||
input,
|
||||
filterDirectory,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error retrieving repo map chunks:", error);
|
||||
}
|
||||
|
||||
retrievalResults.push(
|
||||
...recentlyEditedFilesChunks,
|
||||
|
|
|
|||
|
|
@ -16,20 +16,42 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
|
||||
let retrievalResults: Chunk[] = [];
|
||||
|
||||
const ftsChunks = await this.retrieveFts(args, nRetrieve);
|
||||
const embeddingsChunks = !!config.selectedModelByRole.embed
|
||||
? await this.retrieveEmbeddings(input, nRetrieve)
|
||||
: [];
|
||||
const recentlyEditedFilesChunks =
|
||||
await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve);
|
||||
let ftsChunks: Chunk[] = [];
|
||||
try {
|
||||
ftsChunks = await this.retrieveFts(args, nRetrieve);
|
||||
} catch (error) {
|
||||
console.error("Error retrieving FTS chunks:", error);
|
||||
}
|
||||
|
||||
const repoMapChunks = await requestFilesFromRepoMap(
|
||||
this.options.llm,
|
||||
this.options.config,
|
||||
this.options.ide,
|
||||
input,
|
||||
filterDirectory,
|
||||
);
|
||||
let embeddingsChunks: Chunk[] = [];
|
||||
try {
|
||||
embeddingsChunks = !!config.selectedModelByRole.embed
|
||||
? await this.retrieveEmbeddings(input, nRetrieve)
|
||||
: [];
|
||||
} catch (error) {
|
||||
console.error("Error retrieving embeddings chunks:", error);
|
||||
}
|
||||
|
||||
let recentlyEditedFilesChunks: Chunk[] = [];
|
||||
try {
|
||||
recentlyEditedFilesChunks =
|
||||
await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve);
|
||||
} catch (error) {
|
||||
console.error("Error retrieving recently edited files chunks:", error);
|
||||
}
|
||||
|
||||
let repoMapChunks: Chunk[] = [];
|
||||
try {
|
||||
repoMapChunks = await requestFilesFromRepoMap(
|
||||
this.options.llm,
|
||||
this.options.config,
|
||||
this.options.ide,
|
||||
input,
|
||||
filterDirectory,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error retrieving repo map chunks:", error);
|
||||
}
|
||||
|
||||
retrievalResults.push(
|
||||
...recentlyEditedFilesChunks,
|
||||
|
|
@ -41,7 +63,8 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
if (filterDirectory) {
|
||||
// Backup if the individual retrieval methods don't listen
|
||||
retrievalResults = retrievalResults.filter(
|
||||
(chunk) => !!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir,
|
||||
(chunk) =>
|
||||
!!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -59,29 +82,37 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
// remove empty chunks -- some APIs fail on that
|
||||
chunks = chunks.filter((chunk) => chunk.content);
|
||||
|
||||
let scores: number[] =
|
||||
await this.options.config.selectedModelByRole.rerank.rerank(
|
||||
input,
|
||||
chunks,
|
||||
try {
|
||||
let scores: number[] =
|
||||
await this.options.config.selectedModelByRole.rerank.rerank(
|
||||
input,
|
||||
chunks,
|
||||
);
|
||||
|
||||
// Filter out low-scoring results
|
||||
let results = chunks;
|
||||
// let results = chunks.filter(
|
||||
// (_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold,
|
||||
// );
|
||||
// scores = scores.filter(
|
||||
// (score) => score >= RETRIEVAL_PARAMS.rerankThreshold,
|
||||
// );
|
||||
|
||||
const chunkIndexMap = new Map<Chunk, number>();
|
||||
chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx));
|
||||
|
||||
results.sort(
|
||||
(a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!],
|
||||
);
|
||||
|
||||
// Filter out low-scoring results
|
||||
let results = chunks;
|
||||
// let results = chunks.filter(
|
||||
// (_, i) => scores[i] >= RETRIEVAL_PARAMS.rerankThreshold,
|
||||
// );
|
||||
// scores = scores.filter(
|
||||
// (score) => score >= RETRIEVAL_PARAMS.rerankThreshold,
|
||||
// );
|
||||
|
||||
const chunkIndexMap = new Map<Chunk, number>();
|
||||
chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx));
|
||||
|
||||
results.sort(
|
||||
(a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!],
|
||||
);
|
||||
results = results.slice(-this.options.nFinal);
|
||||
return results;
|
||||
results = results.slice(-this.options.nFinal);
|
||||
return results;
|
||||
} catch (e) {
|
||||
void this.options.ide.showToast(
|
||||
"warning",
|
||||
`Failed to rerank retrieval results\n${e}`,
|
||||
);
|
||||
return chunks.slice(-this.options.nFinal);
|
||||
}
|
||||
}
|
||||
|
||||
private async _expandWithEmbeddings(chunks: Chunk[]): Promise<Chunk[]> {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { Chunk, ContinueConfig, IDE, ILLM } from "../..";
|
||||
import { getModelByRole } from "../../config/util";
|
||||
import generateRepoMap from "../../util/generateRepoMap";
|
||||
import { resolveRelativePathInDir } from "../../util/ideUtils";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
|
||||
const SUPPORTED_MODEL_TITLE_FAMILIES = [
|
||||
|
|
@ -48,14 +49,14 @@ export async function requestFilesFromRepoMap(
|
|||
const repoMap = await generateRepoMap(llm, ide, {
|
||||
dirUris: filterDirUri ? [filterDirUri] : undefined,
|
||||
includeSignatures: false,
|
||||
outputRelativeUriPaths: false,
|
||||
outputRelativeUriPaths: true,
|
||||
});
|
||||
|
||||
const prompt = `${repoMap}
|
||||
|
||||
Given the above repo map, your task is to decide which files are most likely to be relevant in answering a question. Before giving your answer, you should write your reasoning about which files/folders are most important. This thinking should start with a <reasoning> tag, followed by a paragraph explaining your reasoning, and then a closing </reasoning> tag on the last line.
|
||||
|
||||
After this, your response should begin with a <results> tag, followed by a list of each file, one per line, and then a closing </results> tag on the last line. You should select between 5 and 10 files. The names that you list should be the full path from the root of the repo, not just the basename of the file.
|
||||
After this, your response should begin with a <results> tag, followed by a list of each file, one per line, and then a closing </results> tag on the last line. You should select between 5 and 10 files. The names that you list should be the exact relative path that you saw in the repo map, not just the basename of the file.
|
||||
|
||||
This is the question that you should select relevant files for: "${input}"`;
|
||||
|
||||
|
|
@ -72,16 +73,20 @@ This is the question that you should select relevant files for: "${input}"`;
|
|||
return [];
|
||||
}
|
||||
|
||||
const fileUris = content
|
||||
const filepaths = content
|
||||
.split("<results>")[1]
|
||||
?.split("</results>")[0]
|
||||
?.split("\n")
|
||||
.filter(Boolean)
|
||||
.map((uri) => uri.trim());
|
||||
.map((filepath) => filepath.trim());
|
||||
|
||||
const chunks = await Promise.all(
|
||||
fileUris.map(async (uri) => {
|
||||
const content = await ide.readFile(uri);
|
||||
filepaths.map(async (filepath) => {
|
||||
const uri = await resolveRelativePathInDir(filepath, ide);
|
||||
if (!uri) {
|
||||
return undefined;
|
||||
}
|
||||
const content = await ide.readFile(filepath);
|
||||
const lineCount = content.split("\n").length;
|
||||
const chunk: Chunk = {
|
||||
digest: uri,
|
||||
|
|
@ -95,7 +100,7 @@ This is the question that you should select relevant files for: "${input}"`;
|
|||
}),
|
||||
);
|
||||
|
||||
return chunks;
|
||||
return chunks.filter((c) => c !== undefined) as Chunk[];
|
||||
} catch (e) {
|
||||
console.debug("Error requesting files from repo map", e);
|
||||
return [];
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
import * as fs from "node:fs";
|
||||
import { IdeSettings } from "..";
|
||||
import { getStagingEnvironmentDotFilePath } from "../util/paths";
|
||||
import {
|
||||
getLocalEnvironmentDotFilePath,
|
||||
getStagingEnvironmentDotFilePath,
|
||||
} from "../util/paths";
|
||||
|
||||
export interface ControlPlaneEnv {
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL: string;
|
||||
|
|
@ -18,7 +21,7 @@ const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ";
|
|||
const WORKOS_ENV_ID_PRODUCTION = "continue";
|
||||
const WORKOS_ENV_ID_STAGING = "continue-staging";
|
||||
|
||||
const PRODUCTION_ENV: ControlPlaneEnv = {
|
||||
export const PRODUCTION_ENV: ControlPlaneEnv = {
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL:
|
||||
"https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/",
|
||||
CONTROL_PLANE_URL:
|
||||
|
|
@ -78,6 +81,11 @@ export function getControlPlaneEnvSync(
|
|||
ideTestEnvironment: IdeSettings["continueTestEnvironment"],
|
||||
enableControlServerBeta: IdeSettings["enableControlServerBeta"],
|
||||
): ControlPlaneEnv {
|
||||
// Note .local overrides .staging
|
||||
if (fs.existsSync(getLocalEnvironmentDotFilePath())) {
|
||||
return LOCAL_ENV;
|
||||
}
|
||||
|
||||
if (fs.existsSync(getStagingEnvironmentDotFilePath())) {
|
||||
return STAGING_ENV;
|
||||
}
|
||||
|
|
|
|||
50
core/core.ts
50
core/core.ts
|
|
@ -30,12 +30,7 @@ import { ChatDescriber } from "./util/chatDescriber";
|
|||
import { clipboardCache } from "./util/clipboardCache";
|
||||
import { GlobalContext } from "./util/GlobalContext";
|
||||
import historyManager from "./util/history";
|
||||
import {
|
||||
editConfigJson,
|
||||
getConfigJsonPath,
|
||||
migrateV1DevDataFiles,
|
||||
} from "./util/paths";
|
||||
import { localPathToUri } from "./util/pathToUri";
|
||||
import { editConfigJson, migrateV1DevDataFiles } from "./util/paths";
|
||||
import { Telemetry } from "./util/posthog";
|
||||
import { getSymbolsForManyFiles } from "./util/treeSitter";
|
||||
import { TTS } from "./util/tts";
|
||||
|
|
@ -49,7 +44,9 @@ import {
|
|||
type IndexingProgressUpdate,
|
||||
} from ".";
|
||||
|
||||
import { isLocalAssistantFile } from "./config/loadLocalAssistants";
|
||||
import { shouldIgnore } from "./indexing/shouldIgnore";
|
||||
import { walkDirCache } from "./indexing/walkDir";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
import type { IMessenger, Message } from "./protocol/messenger";
|
||||
|
||||
|
|
@ -111,6 +108,11 @@ export class Core {
|
|||
ideSettingsPromise,
|
||||
this.onWrite,
|
||||
sessionInfoPromise,
|
||||
(orgId: string | null) => {
|
||||
void messenger.request("didSelectOrganization", {
|
||||
orgId,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
this.docsService = DocsService.createSingleton(
|
||||
|
|
@ -299,8 +301,11 @@ export class Core {
|
|||
this.configHandler.updateIdeSettings(msg.data);
|
||||
});
|
||||
|
||||
on("config/listProfiles", (msg) => {
|
||||
return this.configHandler.listProfiles();
|
||||
on("config/listProfiles", async (msg) => {
|
||||
const profiles = this.configHandler.listProfiles();
|
||||
const selectedProfileId =
|
||||
this.configHandler.currentProfile?.profileDescription.id ?? null;
|
||||
return { profiles, selectedProfileId };
|
||||
});
|
||||
|
||||
on("config/refreshProfiles", async (msg) => {
|
||||
|
|
@ -830,6 +835,7 @@ export class Core {
|
|||
if (!config || config.disableIndexing) {
|
||||
return; // TODO silent in case of commands?
|
||||
}
|
||||
walkDirCache.invalidate();
|
||||
if (data?.shouldClearIndexes) {
|
||||
const codebaseIndexer = await this.codebaseIndexerPromise;
|
||||
await codebaseIndexer.clearIndexes();
|
||||
|
|
@ -857,10 +863,12 @@ export class Core {
|
|||
// TODO - remove remaining logic for these from IDEs where possible
|
||||
on("files/changed", async ({ data }) => {
|
||||
if (data?.uris?.length) {
|
||||
walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes
|
||||
for (const uri of data.uris) {
|
||||
// Listen for file changes in the workspace
|
||||
// URI TODO is this equality statement valid?
|
||||
if (URI.equal(uri, localPathToUri(getConfigJsonPath()))) {
|
||||
const currentProfileUri =
|
||||
this.configHandler.currentProfile?.profileDescription.uri ?? "";
|
||||
|
||||
if (URI.equal(uri, currentProfileUri)) {
|
||||
// Trigger a toast notification to provide UI feedback that config has been updated
|
||||
const showToast =
|
||||
this.globalContext.get("showConfigUpdateToast") ?? true;
|
||||
|
|
@ -874,6 +882,8 @@ export class Core {
|
|||
this.globalContext.update("showConfigUpdateToast", false);
|
||||
}
|
||||
}
|
||||
await this.configHandler.reloadConfig();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
|
|
@ -925,15 +935,33 @@ export class Core {
|
|||
|
||||
on("files/created", async ({ data }) => {
|
||||
if (data?.uris?.length) {
|
||||
walkDirCache.invalidate();
|
||||
void refreshIfNotIgnored(data.uris);
|
||||
|
||||
// If it's a local assistant being created, we want to reload all assistants so it shows up in the list
|
||||
for (const uri of data.uris) {
|
||||
if (isLocalAssistantFile(uri)) {
|
||||
await this.configHandler.loadAssistantsForSelectedOrg();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
on("files/deleted", async ({ data }) => {
|
||||
if (data?.uris?.length) {
|
||||
walkDirCache.invalidate();
|
||||
void refreshIfNotIgnored(data.uris);
|
||||
}
|
||||
});
|
||||
|
||||
on("files/closed", async ({ data }) => {
|
||||
if (data.uris) {
|
||||
this.messenger.send("didCloseFiles", {
|
||||
uris: data.uris,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
on("files/opened", async ({ data }) => {
|
||||
if (data?.uris?.length) {
|
||||
// Do something on files opened
|
||||
|
|
|
|||
|
|
@ -46,7 +46,7 @@ export class DataLogger {
|
|||
if ("eventName" in zodSchema.shape) {
|
||||
newBody.eventName = eventName;
|
||||
}
|
||||
if ("timestamp" in zodSchema.shape) {
|
||||
if (!newBody.timestamp && "timestamp" in zodSchema.shape) {
|
||||
newBody.timestamp = new Date().toISOString();
|
||||
}
|
||||
if ("schema" in zodSchema.shape) {
|
||||
|
|
|
|||
|
|
@ -29,4 +29,16 @@ describe("Test myers diff function", () => {
|
|||
{ type: "same", line: "E" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("should ignore newline differences at end", () => {
|
||||
const linesA = "A\nB\nC\n";
|
||||
const linesB = "A\nB\nC";
|
||||
|
||||
const diffLines = myersDiff(linesA, linesB);
|
||||
expect(diffLines).toEqual([
|
||||
{ type: "same", line: "A" },
|
||||
{ type: "same", line: "B" },
|
||||
{ type: "same", line: "C" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ export function convertMyersChangeToDiffLines(change: Change): DiffLine[] {
|
|||
: "same";
|
||||
const lines = change.value.split("\n");
|
||||
|
||||
// `diff` package is always adding an extra new line at the end of the array
|
||||
// Ignore the \n at the end of the final line, if there is one
|
||||
if (lines[lines.length - 1] === "") {
|
||||
lines.pop();
|
||||
}
|
||||
|
|
@ -18,9 +18,27 @@ export function convertMyersChangeToDiffLines(change: Change): DiffLine[] {
|
|||
return lines.map((line) => ({ type, line }));
|
||||
}
|
||||
|
||||
// The interpretation of lines in oldContent and newContent is the same as jsdiff
|
||||
// Lines are separated by \n, with the exception that a trailing \n does *not*
|
||||
// represent an empty line.
|
||||
//
|
||||
// The default for jsdiff is that "foo" and "foo\n" are *different* single-line
|
||||
// contents, but we can't represent that: to avoid a diff
|
||||
// [ { type: "old", line: "foo" }, { type: "new", line: "foo" } ], we
|
||||
// pass ignoreNewlineAtEof: true.
|
||||
export function myersDiff(oldContent: string, newContent: string): DiffLine[] {
|
||||
const theirFormat = diffLines(oldContent, newContent);
|
||||
const theirFormat = diffLines(oldContent, newContent, {
|
||||
ignoreNewlineAtEof: true,
|
||||
});
|
||||
const ourFormat = theirFormat.flatMap(convertMyersChangeToDiffLines);
|
||||
|
||||
while (
|
||||
ourFormat.length > 0 &&
|
||||
ourFormat[ourFormat.length - 1].type === "old" &&
|
||||
ourFormat[ourFormat.length - 1].line === ""
|
||||
) {
|
||||
ourFormat.pop();
|
||||
}
|
||||
|
||||
return ourFormat;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { getUriFileExtension } from "../../util/uri";
|
|||
|
||||
import { deterministicApplyLazyEdit } from "./deterministic";
|
||||
import { streamLazyApply } from "./streamLazyApply";
|
||||
import { isUnifiedDiffFormat, applyUnifiedDiff } from "./unifiedDiffApply";
|
||||
|
||||
function canUseInstantApply(filename: string) {
|
||||
const fileExtension = getUriFileExtension(filename);
|
||||
|
|
@ -33,5 +34,16 @@ export async function applyCodeBlock(
|
|||
}
|
||||
}
|
||||
|
||||
// If the code block is a diff
|
||||
if (isUnifiedDiffFormat(newFile)) {
|
||||
try {
|
||||
const diffLines = applyUnifiedDiff(oldFile, newFile);
|
||||
const diffGenerator = generateLines(diffLines!);
|
||||
return [true, diffGenerator];
|
||||
} catch (e) {
|
||||
console.error("Failed to apply unified diff", e);
|
||||
}
|
||||
}
|
||||
|
||||
return [false, streamLazyApply(oldFile, filename, newFile, llm, fastLlm)];
|
||||
}
|
||||
|
|
|
|||
415
core/edit/lazy/unifiedDiffApply.test.ts
Normal file
415
core/edit/lazy/unifiedDiffApply.test.ts
Normal file
|
|
@ -0,0 +1,415 @@
|
|||
import { applyUnifiedDiff, isUnifiedDiffFormat } from "./unifiedDiffApply";
|
||||
|
||||
describe("isUnifiedDiffFormat", () => {
|
||||
it("should return true for valid unified diff format", () => {
|
||||
const validDiff = `--- original.txt
|
||||
+++ modified.txt
|
||||
@@ -1,3 +1,4 @@
|
||||
line1
|
||||
-line2
|
||||
+newline2
|
||||
+newline3
|
||||
line3`;
|
||||
expect(isUnifiedDiffFormat(validDiff)).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false for empty diff", () => {
|
||||
expect(isUnifiedDiffFormat("")).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false for diff without hunk header", () => {
|
||||
const invalidDiff = `--- original.txt
|
||||
+++ modified.txt
|
||||
+line1
|
||||
-line2
|
||||
+line3`;
|
||||
expect(isUnifiedDiffFormat(invalidDiff)).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false for diff without valid content", () => {
|
||||
const invalidDiff = `--- original.txt
|
||||
+++ modified.txt
|
||||
@@ -1,3 +1,4 @@`;
|
||||
expect(isUnifiedDiffFormat(invalidDiff)).toBe(false);
|
||||
});
|
||||
|
||||
it("should return true even without file headers if hunk headers exist", () => {
|
||||
const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@
|
||||
line1
|
||||
-line2
|
||||
+newline2
|
||||
+newline3
|
||||
line3`;
|
||||
expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true);
|
||||
});
|
||||
|
||||
it("should return true in case of empty lines", () => {
|
||||
const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@
|
||||
line1
|
||||
|
||||
-line2
|
||||
+newline2
|
||||
|
||||
line3`;
|
||||
expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyUnifiedDiff", () => {
|
||||
it("should correctly apply a add line of unified diff", () => {
|
||||
const sourceCode = `func main() {
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
fmt.Println("Calculator started! Available operations:")
|
||||
fmt.Println(" + : Addition")
|
||||
fmt.Println(" - : Subtraction")
|
||||
fmt.Println(" * : Multiplication")
|
||||
fmt.Println(" / : Division")
|
||||
fmt.Println(" ^ : Power")
|
||||
fmt.Println(" √ : Square root (use only one number)")
|
||||
}
|
||||
// End of file`;
|
||||
|
||||
const diffText = `--- original.go
|
||||
+++ updated.go
|
||||
@@ -30,6 +30,7 @@
|
||||
fmt.Println(" / : Division")
|
||||
fmt.Println(" ^ : Power")
|
||||
fmt.Println(" √ : Square root (use only one number)")
|
||||
+ fmt.Println(" log: Logarithm (use 'log base number')")
|
||||
}`;
|
||||
|
||||
const result = applyUnifiedDiff(sourceCode, diffText);
|
||||
|
||||
const expected = [
|
||||
{ type: "same", line: "func main() {" },
|
||||
{ type: "same", line: " scanner := bufio.NewScanner(os.Stdin)" },
|
||||
{ type: "same", line: " fmt.Println(\"Calculator started! Available operations:\")" },
|
||||
{ type: "same", line: " fmt.Println(\" + : Addition\")" },
|
||||
{ type: "same", line: " fmt.Println(\" - : Subtraction\")" },
|
||||
{ type: "same", line: " fmt.Println(\" * : Multiplication\")" },
|
||||
{ type: "same", line: " fmt.Println(\" / : Division\")" },
|
||||
{ type: "same", line: " fmt.Println(\" ^ : Power\")" },
|
||||
{ type: "same", line: " fmt.Println(\" √ : Square root (use only one number)\")" },
|
||||
{ type: "new", line: " fmt.Println(\" log: Logarithm (use 'log base number')\")" },
|
||||
{ type: "same", line: "}" },
|
||||
{ type: "same", line: "// End of file" }
|
||||
];
|
||||
|
||||
expect(result).toEqual(expected);
|
||||
});
|
||||
|
||||
it("should correctly apply multiple insertions and deletions", () => {
|
||||
const sourceCode = `package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
fmt.Println("Hello")
|
||||
fmt.Println("World")
|
||||
}`;
|
||||
|
||||
const diffText = `--- original.go
|
||||
+++ updated.go
|
||||
@@ -1,8 +1,11 @@
|
||||
package main
|
||||
|
||||
-import "fmt"
|
||||
+import (
|
||||
+ "fmt"
|
||||
+ "time"
|
||||
+)
|
||||
|
||||
func main() {
|
||||
- fmt.Println("Hello")
|
||||
+ fmt.Printf("The time is: %v\\n", time.Now())
|
||||
- fmt.Println("World")
|
||||
+ fmt.Println("Goodbye!")
|
||||
}`;
|
||||
const result = applyUnifiedDiff(sourceCode, diffText);
|
||||
|
||||
const expected = [
|
||||
{ type: "same", line: "package main" },
|
||||
{ type: "same", line: "" },
|
||||
{ type: "old", line: "import \"fmt\"" },
|
||||
{ type: "new", line: "import (" },
|
||||
{ type: "new", line: " \"fmt\"" },
|
||||
{ type: "new", line: " \"time\"" },
|
||||
{ type: "new", line: ")" },
|
||||
{ type: "same", line: "" },
|
||||
{ type: "same", line: "func main() {" },
|
||||
{ type: "old", line: " fmt.Println(\"Hello\")" },
|
||||
{ type: "new", line: " fmt.Printf(\"The time is: %v\\n\", time.Now())" },
|
||||
{ type: "old", line: " fmt.Println(\"World\")" },
|
||||
{ type: "new", line: " fmt.Println(\"Goodbye!\")" },
|
||||
{ type: "same", line: "}" }
|
||||
];
|
||||
|
||||
expect(result).toEqual(expected);
|
||||
});
|
||||
|
||||
it("should correctly apply multiple diff blocks", () => {
|
||||
const sourceCode = `package main
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
func main() {
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
fmt.Println("Calculator started! Available operations:")
|
||||
fmt.Println(" + : Addition")
|
||||
fmt.Println(" - : Subtraction")
|
||||
fmt.Println(" * : Multiplication")
|
||||
fmt.Println(" / : Division")
|
||||
fmt.Println(" ^ : Power")
|
||||
fmt.Println(" √ : Square root (use only one number)")
|
||||
for {
|
||||
fmt.Print("Enter calculation (e.g., 5 + 3 or √ 16) or 'q' to quit: ")
|
||||
scanner.Scan()
|
||||
input := scanner.Text()
|
||||
if strings.ToLower(input) == "q" {
|
||||
fmt.Println("Goodbye!")
|
||||
break
|
||||
}
|
||||
result, err := calculate(input)
|
||||
if err != nil {
|
||||
fmt.Printf("Error: %v\n", err)
|
||||
continue
|
||||
}
|
||||
fmt.Printf("Result: %v\n", result)
|
||||
}
|
||||
}
|
||||
func calculate(input string) (float64, error) {
|
||||
parts := strings.Fields(input)
|
||||
if len(parts) < 2 {
|
||||
return 0, fmt.Errorf("invalid input format: please use 'number operator number' or '√ number'")
|
||||
}
|
||||
if parts[0] == "√" {
|
||||
if len(parts) != 2 {
|
||||
return 0, fmt.Errorf("square root operation requires exactly one number")
|
||||
}
|
||||
num, err := strconv.ParseFloat(parts[1], 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid number for square root: %v", err)
|
||||
}
|
||||
if num < 0 {
|
||||
return 0, fmt.Errorf("cannot calculate square root of a negative number")
|
||||
}
|
||||
return math.Sqrt(num), nil
|
||||
}
|
||||
if len(parts) != 3 {
|
||||
return 0, fmt.Errorf("invalid input format: please use 'number operator number'")
|
||||
}
|
||||
num1, err := strconv.ParseFloat(parts[0], 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid first number: %v", err)
|
||||
}
|
||||
operator := parts[1]
|
||||
num2, err := strconv.ParseFloat(parts[2], 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid second number: %v", err)
|
||||
}
|
||||
switch operator {
|
||||
case "+":
|
||||
return num1 + num2, nil
|
||||
case "-":
|
||||
return num1 - num2, nil
|
||||
case "*":
|
||||
return num1 * num2, nil
|
||||
case "/":
|
||||
if num2 == 0 {
|
||||
return 0, fmt.Errorf("division by zero is not allowed")
|
||||
}
|
||||
return num1 / num2, nil
|
||||
case "^":
|
||||
return math.Pow(num1, num2), nil
|
||||
default:
|
||||
return 0, fmt.Errorf("invalid operator: must be +, -, *, /, ^, or √")
|
||||
}
|
||||
}
|
||||
func TestCalculate(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
expected float64
|
||||
hasError bool
|
||||
}{
|
||||
{"2 + 3", 5, false},
|
||||
{"10 - 5", 5, false},
|
||||
{"4 * 3", 12, false},
|
||||
{"15 / 3", 5, false},
|
||||
{"2 ^ 3", 8, false},
|
||||
{"√ 16", 4, false},
|
||||
{"2 + a", 0, true},
|
||||
{"15 / 0", 0, true},
|
||||
{"√ -4", 0, true},
|
||||
{"3 $ 4", 0, true},
|
||||
{"", 0, true},
|
||||
{"1", 0, true},
|
||||
{"1 +", 0, true},
|
||||
{"+ 1", 0, true},
|
||||
{"√ 2 3", 0, true},
|
||||
}
|
||||
for _, test := range tests {
|
||||
result, err := calculate(test.input)
|
||||
if test.hasError && err == nil {
|
||||
t.Errorf("Expected error for input '%s', but got none", test.input)
|
||||
continue
|
||||
}
|
||||
if !test.hasError && err != nil {
|
||||
t.Errorf("Unexpected error for input '%s': %v", test.input, err)
|
||||
continue
|
||||
}
|
||||
if !test.hasError && result != test.expected {
|
||||
t.Errorf("For input '%s': expected %f, but got %f", test.input, test.expected, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestSpecialCases(t *testing.T) {
|
||||
result, err := calculate("2.5 + 2.5")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error for floating point addition: %v", err)
|
||||
}
|
||||
if result != 5.0 {
|
||||
t.Errorf("Floating point addition failed: expected 5.0, got %f", result)
|
||||
}
|
||||
result, err = calculate("2.5 ^ 2")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error for power operation: %v", err)
|
||||
}
|
||||
expected := 6.25
|
||||
if math.Abs(result-expected) > 0.0001 {
|
||||
t.Errorf("Power operation failed: expected %f, got %f", expected, result)
|
||||
}
|
||||
result, err = calculate("√ 2")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error for square root: %v", err)
|
||||
}
|
||||
expected = math.Sqrt(2)
|
||||
if math.Abs(result-expected) > 0.0001 {
|
||||
t.Errorf("Square root operation failed: expected %f, got %f", expected, result)
|
||||
}
|
||||
}
|
||||
func TestLargeNumbers(t *testing.T) {
|
||||
result, err := calculate("1000000000 + 1000000000")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error for adding large numbers: %v", err)
|
||||
}
|
||||
if result != 2000000000 {
|
||||
t.Errorf("Adding large numbers failed: expected 2000000000, got %f", result)
|
||||
}
|
||||
result, err = calculate("1000000 * 1000000")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error for multiplying large numbers: %v", err)
|
||||
}
|
||||
if result != 1000000000000 {
|
||||
t.Errorf("Multiplying large numbers failed: expected 1000000000000, got %f", result)
|
||||
}
|
||||
result, err = calculate("2 ^ 30")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error for large exponent operation: %v", err)
|
||||
}
|
||||
expected := math.Pow(2, 30)
|
||||
if result != expected {
|
||||
t.Errorf("Power operation with large exponent failed: expected %f, got %f", expected, result)
|
||||
}
|
||||
result, err = calculate("1000000000000 / 1000000")
|
||||
if err != nil {
|
||||
t.Errorf("Unexpected error for dividing large numbers: %v", err)
|
||||
}
|
||||
if result != 1000000 {
|
||||
t.Errorf("Dividing large numbers failed: expected 1000000, got %f", result)
|
||||
}
|
||||
}`;
|
||||
|
||||
const diffText = `--- original.go
|
||||
+++ updated.go
|
||||
@@ -30,6 +30,7 @@
|
||||
fmt.Println(" / : Division")
|
||||
fmt.Println(" ^ : Power")
|
||||
fmt.Println(" √ : Square root (use only one number)")
|
||||
+ fmt.Println(" log: Logarithm (use 'log base number')")
|
||||
+ fmt.Println(" Base must be > 0 and != 1, number must be > 0")
|
||||
for {
|
||||
fmt.Print("Enter calculation (e.g., 5 + 3 or √ 16) or 'q' to quit: ")
|
||||
@@ -73,6 +74,8 @@
|
||||
}
|
||||
return math.Sqrt(num), nil
|
||||
}
|
||||
+
|
||||
+ // Handle logarithmic operations
|
||||
+ if parts[0] == "log" {
|
||||
+ if len(parts) != 3 {
|
||||
+ return 0, fmt.Errorf("logarithm operation requires exactly two arguments: 'log base number'")
|
||||
+ }
|
||||
+ base, err := strconv.ParseFloat(parts[1], 64)
|
||||
+ if err != nil || base <= 0 || base == 1 {
|
||||
+ return 0, fmt.Errorf("invalid base for logarithm: must be > 0 and != 1")
|
||||
+ }
|
||||
+ num, err := strconv.ParseFloat(parts[2], 64)
|
||||
+ if err != nil || num <= 0 {
|
||||
+ return 0, fmt.Errorf("invalid number for logarithm: must be > 0")
|
||||
+ }
|
||||
+ return math.Log(num) / math.Log(base), nil
|
||||
+ }
|
||||
+
|
||||
if len(parts) != 3 {
|
||||
return 0, fmt.Errorf("invalid input format: please use 'number operator number'")
|
||||
@@ -155,6 +158,15 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
+
|
||||
+func TestLogarithmicCases(t *testing.T) {
|
||||
+ tests := []struct {
|
||||
+ input string
|
||||
+ expected float64
|
||||
+ hasError bool
|
||||
+ }{
|
||||
+ {"log 2 8", 3, false},
|
||||
+ {"log 10 100", 2, false},
|
||||
+ {"log 10 -5", 0, true},
|
||||
+ {"log 1 100", 0, true},
|
||||
+ {"log 0.5 0.25", 2, false},
|
||||
+ }`;
|
||||
const result = applyUnifiedDiff(sourceCode, diffText);
|
||||
|
||||
expect(result[0].line).toEqual("package main");
|
||||
// 1st block
|
||||
expect(result[18].line).toEqual("\tfmt.Println(\" √ : Square root (use only one number)\")");
|
||||
expect(result[19].line).toEqual(" fmt.Println(\" log: Logarithm (use 'log base number')\")");
|
||||
expect(result[20].line).toEqual(" fmt.Println(\" Base must be > 0 and != 1, number must be > 0\")");
|
||||
// 2nd block
|
||||
expect(result[56]).toEqual({type: "same", line: "\t}"});
|
||||
expect(result[57]).toEqual({type: "new", line: "\t"});
|
||||
expect(result[58]).toEqual({type: "new", line: "\t// Handle logarithmic operations"});
|
||||
expect(result[73]).toEqual({type: "new", line: ""});
|
||||
expect(result[74]).toEqual({type: "same", line: "\tif len(parts) != 3 {"});
|
||||
// 3rd block
|
||||
expect(result[140]).toEqual({type: "same", line: "}"});
|
||||
expect(result[141]).toEqual({type: "new", line: ""});
|
||||
expect(result[142]).toEqual({type: "new", line: "func TestLogarithmicCases(t *testing.T) {"});
|
||||
expect(result[153]).toEqual({type: "new", line: "\t}"});
|
||||
expect(result[154]).toEqual({type: "same", line: "func TestSpecialCases(t *testing.T) {"});
|
||||
});
|
||||
|
||||
it("should throw error when hunk cannot be matched to source", () => {
|
||||
const sourceCode = `line1
|
||||
line2
|
||||
line3`;
|
||||
|
||||
const diffText = `--- a.txt
|
||||
+++ b.txt
|
||||
@@ -1,3 +1,4 @@
|
||||
missing1
|
||||
-missing2
|
||||
+newline2
|
||||
missing3`;
|
||||
|
||||
expect(() => applyUnifiedDiff(sourceCode, diffText))
|
||||
.toThrow("Hunk could not be applied cleanly to source code.");
|
||||
});
|
||||
});
|
||||
152
core/edit/lazy/unifiedDiffApply.ts
Normal file
152
core/edit/lazy/unifiedDiffApply.ts
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
import { DiffLine } from "../../index";
|
||||
|
||||
/**
|
||||
* Checks if a string matches unified diff format by validating:
|
||||
* 1. Has at least one hunk header (@@ -n,m +n,m @@)
|
||||
* 2. Contains valid diff content lines (starting with +, -, or space) which are not header lines
|
||||
*/
|
||||
export function isUnifiedDiffFormat(diff: string): boolean {
|
||||
const lines = diff.trim().split("\n");
|
||||
|
||||
if (lines.length < 3) {return false;}
|
||||
|
||||
let hasHunkHeader = false;
|
||||
let hasValidContent = false;
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith("---") || line.startsWith("+++")) {
|
||||
// ignore file headers - they are not required or useful
|
||||
} else if (line.match(/^@@ -\d+,?\d* \+\d+,?\d* @@/)) {
|
||||
hasHunkHeader = true;
|
||||
} else if (line.match(/^[+ -]/) || line === "") {
|
||||
hasValidContent = true;
|
||||
}
|
||||
}
|
||||
|
||||
return hasHunkHeader && hasValidContent;
|
||||
}
|
||||
|
||||
function extractBeforeLines(hunkLines: string[]): string[] {
|
||||
return hunkLines
|
||||
.filter((line) => line.startsWith("-") || !line.startsWith("+"))
|
||||
.map((line) => line.substring(1));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a unified diff to source code and returns an array of DiffLine objects.
|
||||
* Each DiffLine contains a type ("same", "new", or "old") and the line content.
|
||||
*
|
||||
* @throws Error if the diff cannot be cleanly applied to the source
|
||||
*/
|
||||
export function applyUnifiedDiff(sourceCode: string, unifiedDiffText: string): DiffLine[] {
|
||||
const sourceLines = sourceCode.split(/\r?\n/);
|
||||
const hunks = parseUnifiedDiff(unifiedDiffText);
|
||||
const diffResult: DiffLine[] = [];
|
||||
let currentPos = 0; // pointer in sourceLines
|
||||
|
||||
for (const hunk of hunks) {
|
||||
const hunkBeforeLines = extractBeforeLines(hunk.lines);
|
||||
const hunkStart = findHunkInSource(sourceLines, hunkBeforeLines, currentPos);
|
||||
if (hunkStart === -1) {
|
||||
// All hunks must be found in the source code. If not, throw an error.
|
||||
throw new Error("Hunk could not be applied cleanly to source code.");
|
||||
}
|
||||
|
||||
// Emit any unchanged lines that come before this hunk.
|
||||
for (let i = currentPos; i < hunkStart; i++) {
|
||||
diffResult.push({ type: "same", line: sourceLines[i] });
|
||||
}
|
||||
let hunkSourcePos = hunkStart;
|
||||
|
||||
for (const dline of hunk.lines) {
|
||||
const srcLine = sourceLines[hunkSourcePos];
|
||||
if (dline.startsWith("+")) {
|
||||
// Insertion: output new line (strip the '+' marker)
|
||||
diffResult.push({ type: "new", line: dline.substring(1) });
|
||||
} else if (dline.startsWith("-")) {
|
||||
// Removal: output the removed (old) line and advance the pointer.
|
||||
diffResult.push({ type: "old", line: srcLine });
|
||||
hunkSourcePos++;
|
||||
} else {
|
||||
// Context line: use the source line (in case the diff’s context has a minor whitespace error)
|
||||
// and advance the pointer.
|
||||
diffResult.push({ type: "same", line: srcLine });
|
||||
hunkSourcePos++;
|
||||
}
|
||||
}
|
||||
currentPos = hunkSourcePos;
|
||||
}
|
||||
|
||||
for (let i = currentPos; i < sourceLines.length; i++) {
|
||||
diffResult.push({ type: "same", line: sourceLines[i] });
|
||||
}
|
||||
return diffResult;
|
||||
}
|
||||
|
||||
interface Hunk {
|
||||
lines: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a unified diff string into an array of hunks.
|
||||
* It skips the file header lines (starting with "---" or "+++") and hunk header lines (starting with "@@"),
|
||||
* then collects the remaining lines (which may start with '+' or '-' or have no prefix).
|
||||
*/
|
||||
function parseUnifiedDiff(diffText: string): Hunk[] {
|
||||
const lines = diffText.split(/\r?\n/);
|
||||
const hunks: Hunk[] = [];
|
||||
let currentHunk: Hunk | null = null;
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith("---") || line.startsWith("+++")) {
|
||||
// Skip file header lines.
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("@@")) {
|
||||
if (currentHunk) {
|
||||
hunks.push(currentHunk);
|
||||
}
|
||||
currentHunk = { lines: [] };
|
||||
continue;
|
||||
}
|
||||
currentHunk?.lines.push(line);
|
||||
}
|
||||
if (currentHunk) {
|
||||
hunks.push(currentHunk);
|
||||
}
|
||||
return hunks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches for an occurrence of the block of lines (the “before” block) in sourceLines,
|
||||
* starting at startIndex. Comparison is done by checking if the lines are exactly equal,
|
||||
* or if their trimmed versions are equal.
|
||||
*
|
||||
* Returns the index in sourceLines where the block begins, or -1 if no match is found.
|
||||
*/
|
||||
function findHunkInSource(sourceLines: string[], hunkBeforeLines: string[], startIndex: number): number {
|
||||
for (let i = startIndex; i <= sourceLines.length - hunkBeforeLines.length; i++) {
|
||||
let match = true;
|
||||
for (let j = 0; j < hunkBeforeLines.length; j++) {
|
||||
const sl = sourceLines[i + j];
|
||||
const hl = hunkBeforeLines[j];
|
||||
if (!linesMatch(sl, hl)) {
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (match) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the two lines are either exactly equal or equal after trimming whitespace and tabs.
|
||||
*/
|
||||
function linesMatch(a: string, b: string): boolean {
|
||||
const trimmedA = a.replace(/^\s+/, "");
|
||||
const trimmedB = b.replace(/^\s+/, "");
|
||||
return trimmedA === trimmedB;
|
||||
}
|
||||
57
core/index.d.ts
vendored
57
core/index.d.ts
vendored
|
|
@ -43,13 +43,13 @@ export interface IndexingProgressUpdate {
|
|||
desc: string;
|
||||
shouldClearIndexes?: boolean;
|
||||
status:
|
||||
| "loading"
|
||||
| "indexing"
|
||||
| "done"
|
||||
| "failed"
|
||||
| "paused"
|
||||
| "disabled"
|
||||
| "cancelled";
|
||||
| "loading"
|
||||
| "indexing"
|
||||
| "done"
|
||||
| "failed"
|
||||
| "paused"
|
||||
| "disabled"
|
||||
| "cancelled";
|
||||
debugInfo?: string;
|
||||
}
|
||||
|
||||
|
|
@ -312,7 +312,7 @@ export interface CompletionOptions extends BaseCompletionOptions {
|
|||
model: string;
|
||||
}
|
||||
|
||||
export type ChatMessageRole = "user" | "assistant" | "system" | "tool";
|
||||
export type ChatMessageRole = "user" | "assistant" | "thinking" | "system" | "tool";
|
||||
|
||||
export type TextMessagePart = {
|
||||
type: "text";
|
||||
|
|
@ -357,6 +357,14 @@ export interface UserChatMessage {
|
|||
content: MessageContent;
|
||||
}
|
||||
|
||||
export interface ThinkingChatMessage {
|
||||
role: "thinking";
|
||||
content: MessageContent;
|
||||
signature?: string;
|
||||
redactedThinking?: string;
|
||||
toolCalls?: ToolCallDelta[];
|
||||
}
|
||||
|
||||
export interface AssistantChatMessage {
|
||||
role: "assistant";
|
||||
content: MessageContent;
|
||||
|
|
@ -371,6 +379,7 @@ export interface SystemChatMessage {
|
|||
export type ChatMessage =
|
||||
| UserChatMessage
|
||||
| AssistantChatMessage
|
||||
| ThinkingChatMessage
|
||||
| SystemChatMessage
|
||||
| ToolResultChatMessage;
|
||||
|
||||
|
|
@ -679,10 +688,10 @@ export interface IDE {
|
|||
getCurrentFile(): Promise<
|
||||
| undefined
|
||||
| {
|
||||
isUntitled: boolean;
|
||||
path: string;
|
||||
contents: string;
|
||||
}
|
||||
isUntitled: boolean;
|
||||
path: string;
|
||||
contents: string;
|
||||
}
|
||||
>;
|
||||
|
||||
getLastFileSaveTimestamp?(): number;
|
||||
|
|
@ -866,11 +875,11 @@ export interface CustomCommand {
|
|||
export interface Prediction {
|
||||
type: "content";
|
||||
content:
|
||||
| string
|
||||
| {
|
||||
type: "text";
|
||||
text: string;
|
||||
}[];
|
||||
| string
|
||||
| {
|
||||
type: "text";
|
||||
text: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface ToolExtras {
|
||||
|
|
@ -921,6 +930,8 @@ export interface BaseCompletionOptions {
|
|||
prediction?: Prediction;
|
||||
tools?: Tool[];
|
||||
toolChoice?: ToolChoice;
|
||||
reasoning?: boolean;
|
||||
reasoningBudgetTokens?: number;
|
||||
}
|
||||
|
||||
export interface ModelCapability {
|
||||
|
|
@ -1208,9 +1219,9 @@ export interface Config {
|
|||
embeddingsProvider?: EmbeddingsProviderDescription | ILLM;
|
||||
/** The model that Continue will use for tab autocompletions. */
|
||||
tabAutocompleteModel?:
|
||||
| CustomLLM
|
||||
| ModelDescription
|
||||
| (CustomLLM | ModelDescription)[];
|
||||
| CustomLLM
|
||||
| ModelDescription
|
||||
| (CustomLLM | ModelDescription)[];
|
||||
/** Options for tab autocomplete */
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
/** UI styles customization */
|
||||
|
|
@ -1302,9 +1313,9 @@ export type PackageDetailsSuccess = PackageDetails & {
|
|||
export type PackageDocsResult = {
|
||||
packageInfo: ParsedPackageInfo;
|
||||
} & (
|
||||
| { error: string; details?: never }
|
||||
| { details: PackageDetailsSuccess; error?: never }
|
||||
);
|
||||
| { error: string; details?: never }
|
||||
| { details: PackageDetailsSuccess; error?: never }
|
||||
);
|
||||
|
||||
export interface TerminalOptions {
|
||||
reuseTerminal?: boolean;
|
||||
|
|
|
|||
|
|
@ -7,12 +7,7 @@ import {
|
|||
getQueryForFile,
|
||||
} from "../util/treeSitter";
|
||||
|
||||
import {
|
||||
DatabaseConnection,
|
||||
SqliteDb,
|
||||
tagToString,
|
||||
truncateSqliteLikePattern,
|
||||
} from "./refreshIndex";
|
||||
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
|
||||
import {
|
||||
IndexResultType,
|
||||
MarkCompleteCallback,
|
||||
|
|
@ -398,18 +393,23 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
|||
|
||||
static async getPathsAndSignatures(
|
||||
workspaceDirs: string[],
|
||||
offset: number = 0,
|
||||
batchSize: number = 100,
|
||||
uriOffset: number = 0,
|
||||
uriBatchSize: number = 100,
|
||||
snippetOffset: number = 0,
|
||||
snippetBatchSize: number = 100,
|
||||
): Promise<{
|
||||
groupedByUri: { [path: string]: string[] };
|
||||
hasMore: boolean;
|
||||
hasMoreSnippets: boolean;
|
||||
hasMoreUris: boolean;
|
||||
}> {
|
||||
const db = await SqliteDb.get();
|
||||
await CodeSnippetsCodebaseIndex._createTables(db);
|
||||
|
||||
const likePatterns = workspaceDirs.map((dir) =>
|
||||
truncateSqliteLikePattern(`${dir}%`),
|
||||
);
|
||||
const endIndex = uriOffset + uriBatchSize;
|
||||
const uriBatch = workspaceDirs.slice(uriOffset, endIndex);
|
||||
|
||||
const likePatterns = uriBatch.map((dir) => `${dir}%`);
|
||||
|
||||
const placeholders = likePatterns.map(() => "?").join(" OR path LIKE ");
|
||||
|
||||
const query = `
|
||||
|
|
@ -420,7 +420,11 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
|||
LIMIT ? OFFSET ?
|
||||
`;
|
||||
|
||||
const rows = await db.all(query, [...likePatterns, batchSize, offset]);
|
||||
const rows = await db.all(query, [
|
||||
...likePatterns,
|
||||
snippetBatchSize,
|
||||
snippetOffset,
|
||||
]);
|
||||
|
||||
const groupedByUri: { [path: string]: string[] } = {};
|
||||
|
||||
|
|
@ -431,8 +435,9 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
|||
groupedByUri[path].push(signature);
|
||||
}
|
||||
|
||||
const hasMore = rows.length === batchSize;
|
||||
const hasMoreUris = endIndex < workspaceDirs.length;
|
||||
const hasMoreSnippets = rows.length === snippetBatchSize;
|
||||
|
||||
return { groupedByUri, hasMore };
|
||||
return { groupedByUri, hasMoreUris, hasMoreSnippets };
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,12 +14,12 @@ import {
|
|||
} from "../test/testDir.js";
|
||||
import { getIndexSqlitePath } from "../util/paths.js";
|
||||
|
||||
import { localPathToUri } from "../util/pathToUri.js";
|
||||
import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js";
|
||||
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
|
||||
import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
|
||||
import { CodebaseIndex } from "./types.js";
|
||||
import { walkDir } from "./walkDir.js";
|
||||
import { localPathToUri } from "../util/pathToUri.js";
|
||||
import { walkDir, walkDirCache } from "./walkDir.js";
|
||||
|
||||
jest.useFakeTimers();
|
||||
|
||||
|
|
@ -87,6 +87,10 @@ describe("CodebaseIndexer", () => {
|
|||
tearDownTestDir();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
walkDirCache.invalidate();
|
||||
});
|
||||
|
||||
async function refreshIndex() {
|
||||
const abortController = new AbortController();
|
||||
const abortSignal = abortController.signal;
|
||||
|
|
|
|||
|
|
@ -97,7 +97,6 @@ export class CodebaseIndexer {
|
|||
const lanceDbIndex = await LanceDbIndex.create(
|
||||
embeddingsModel,
|
||||
this.ide.readFile.bind(this.ide),
|
||||
this.continueServerClient,
|
||||
);
|
||||
|
||||
if (lanceDbIndex) {
|
||||
|
|
@ -282,7 +281,9 @@ export class CodebaseIndexer {
|
|||
status: "indexing",
|
||||
};
|
||||
const directoryFiles = [];
|
||||
for await (const p of walkDirAsync(directory, this.ide)) {
|
||||
for await (const p of walkDirAsync(directory, this.ide, {
|
||||
source: "codebase indexing: refresh dirs",
|
||||
})) {
|
||||
directoryFiles.push(p);
|
||||
if (abortSignal.aborted) {
|
||||
yield {
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ import { DatabaseConnection, SqliteDb } from "./refreshIndex";
|
|||
import {
|
||||
mockPathAndCacheKey,
|
||||
mockTag,
|
||||
testContinueServerClient,
|
||||
updateIndexAndAwaitGenerator,
|
||||
} from "./test/indexing";
|
||||
import { IndexResultType } from "./types";
|
||||
|
|
@ -37,7 +36,6 @@ describe.skip("ChunkCodebaseIndex", () => {
|
|||
index = (await LanceDbIndex.create(
|
||||
mockConfig.selectedModelByRole.embed,
|
||||
testIde.readFile.bind(testIde),
|
||||
testContinueServerClient,
|
||||
))!;
|
||||
|
||||
sqliteDb = await SqliteDb.get();
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { RunResult } from "sqlite3";
|
|||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import { isSupportedLanceDbCpuTargetForLinux } from "../config/util";
|
||||
import { IContinueServerClient } from "../continueServer/interface";
|
||||
import {
|
||||
BranchAndDir,
|
||||
Chunk,
|
||||
|
|
@ -57,7 +56,6 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
static async create(
|
||||
embeddingsProvider: ILLM,
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
continueServerClient?: IContinueServerClient,
|
||||
): Promise<LanceDbIndex | null> {
|
||||
if (!isSupportedLanceDbCpuTargetForLinux()) {
|
||||
return null;
|
||||
|
|
@ -65,11 +63,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
|
||||
try {
|
||||
this.lance = await import("vectordb");
|
||||
return new LanceDbIndex(
|
||||
embeddingsProvider,
|
||||
readFile,
|
||||
continueServerClient,
|
||||
);
|
||||
return new LanceDbIndex(embeddingsProvider, readFile);
|
||||
} catch (err) {
|
||||
console.error("Failed to load LanceDB:", err);
|
||||
return null;
|
||||
|
|
@ -79,7 +73,6 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
private constructor(
|
||||
private readonly embeddingsProvider: ILLM,
|
||||
private readonly readFile: (filepath: string) => Promise<string>,
|
||||
private readonly continueServerClient?: IContinueServerClient,
|
||||
) {
|
||||
if (!LanceDbIndex.lance) {
|
||||
throw new Error("LanceDB not initialized");
|
||||
|
|
@ -278,60 +271,6 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
await markComplete(pathAndCacheKeys, IndexResultType.Compute);
|
||||
};
|
||||
|
||||
if (this.continueServerClient?.connected) {
|
||||
try {
|
||||
const keys = results.compute.map(({ cacheKey }) => cacheKey);
|
||||
const resp = await this.continueServerClient.getFromIndexCache(
|
||||
keys,
|
||||
"embeddings",
|
||||
repoName,
|
||||
);
|
||||
for (const [cacheKey, chunks] of Object.entries(resp.files)) {
|
||||
const path = results.compute.find(
|
||||
(item) => item.cacheKey === cacheKey,
|
||||
)?.path;
|
||||
if (!path) {
|
||||
console.warn(
|
||||
"Continue server sent a cacheKey that wasn't requested",
|
||||
cacheKey,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const rows: LanceDbRow[] = [];
|
||||
for (const chunk of chunks) {
|
||||
const row = {
|
||||
path,
|
||||
cachekey: cacheKey,
|
||||
uuid: uuidv4(),
|
||||
vector: chunk.vector,
|
||||
};
|
||||
rows.push(row);
|
||||
|
||||
await sqliteDb.run(
|
||||
"INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
row.uuid,
|
||||
row.cachekey,
|
||||
row.path,
|
||||
this.artifactId,
|
||||
JSON.stringify(row.vector),
|
||||
chunk.startLine,
|
||||
chunk.endLine,
|
||||
chunk.contents,
|
||||
);
|
||||
}
|
||||
|
||||
await addComputedLanceDbRows([{ cacheKey, path }], rows);
|
||||
}
|
||||
|
||||
results.compute = results.compute.filter(
|
||||
(item) => !resp.files[item.cacheKey],
|
||||
);
|
||||
} catch (e) {
|
||||
console.log("Error checking remote cache: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
yield {
|
||||
progress: 0,
|
||||
desc: `Computing embeddings for ${
|
||||
|
|
|
|||
|
|
@ -1,7 +1,12 @@
|
|||
// Generated by continue
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { walkDir, walkDirAsync, walkDirs } from "../indexing/walkDir";
|
||||
import {
|
||||
walkDir,
|
||||
walkDirAsync,
|
||||
walkDirCache,
|
||||
walkDirs,
|
||||
} from "../indexing/walkDir";
|
||||
import { testIde } from "../test/fixtures";
|
||||
import {
|
||||
addToTestDir,
|
||||
|
|
@ -17,6 +22,7 @@ describe("walkDir functions", () => {
|
|||
|
||||
afterEach(async () => {
|
||||
tearDownTestDir();
|
||||
walkDirCache.invalidate();
|
||||
});
|
||||
|
||||
// describe.only("test speed", () => {
|
||||
|
|
@ -192,12 +198,7 @@ describe("walkDir functions", () => {
|
|||
it("should skip symlinks", async () => {
|
||||
const filePath = path.join(TEST_DIR_PATH, "real.ts");
|
||||
addToTestDir([["real.ts", "content"]]);
|
||||
fs.symlink(
|
||||
filePath,
|
||||
path.join(TEST_DIR_PATH, "symlink.ts"),
|
||||
"file",
|
||||
() => {},
|
||||
);
|
||||
fs.symlinkSync(filePath, path.join(TEST_DIR_PATH, "symlink.ts"), "file");
|
||||
|
||||
const files = await walkDirs(testIde);
|
||||
|
||||
|
|
|
|||
|
|
@ -12,10 +12,15 @@ import {
|
|||
export interface WalkerOptions {
|
||||
onlyDirs?: boolean;
|
||||
returnRelativeUrisPaths?: boolean;
|
||||
source?: string;
|
||||
overrideDefaultIgnores?: Ignore;
|
||||
}
|
||||
|
||||
type Entry = [string, FileType];
|
||||
|
||||
const LIST_DIR_CACHE_TIME = 30_000; // 30 seconds
|
||||
const IGNORE_FILE_CACHE_TIME = 30_000; // 30 seconds
|
||||
|
||||
// helper struct used for the DFS walk
|
||||
type WalkableEntry = {
|
||||
name: string;
|
||||
|
|
@ -36,6 +41,38 @@ type IgnoreContext = {
|
|||
dirname: string;
|
||||
};
|
||||
|
||||
class WalkDirCache {
|
||||
dirListCache: Map<
|
||||
string,
|
||||
{
|
||||
time: number;
|
||||
entries: Promise<[string, FileType][]>;
|
||||
}
|
||||
> = new Map();
|
||||
dirIgnoreCache: Map<
|
||||
string,
|
||||
{
|
||||
time: number;
|
||||
ignore: Promise<Ignore>;
|
||||
}
|
||||
> = new Map();
|
||||
// The super safe approach for now
|
||||
invalidate() {
|
||||
this.dirListCache.clear();
|
||||
this.dirIgnoreCache.clear();
|
||||
}
|
||||
// invalidateIgnore(uri: string) {
|
||||
// this.dirIgnoreCache.delete(uri);
|
||||
// }
|
||||
// invalidateParent(uri: string) {
|
||||
// const splitUri = fileUri.split("/");
|
||||
// splitUri.pop();
|
||||
// const parent = splitUri.join("/");
|
||||
// this.dirListCache.delete(uri);
|
||||
// }
|
||||
}
|
||||
export const walkDirCache = new WalkDirCache(); // TODO - singleton approach better?
|
||||
|
||||
class DFSWalker {
|
||||
constructor(
|
||||
private readonly uri: string,
|
||||
|
|
@ -45,9 +82,19 @@ class DFSWalker {
|
|||
|
||||
// walk is a depth-first search implementation
|
||||
public async *walk(): AsyncGenerator<string> {
|
||||
const start = Date.now();
|
||||
let ignoreFileTime = 0;
|
||||
let ignoreTime = 0;
|
||||
let listDirTime = 0;
|
||||
let dirs = 0;
|
||||
let listDirCacheHits = 0;
|
||||
let ignoreCacheHits = 0;
|
||||
|
||||
let section = Date.now();
|
||||
const defaultAndGlobalIgnores = ignore()
|
||||
.add(defaultIgnoreFileAndDir)
|
||||
.add(this.options.overrideDefaultIgnores ?? defaultIgnoreFileAndDir)
|
||||
.add(getGlobalContinueIgArray());
|
||||
ignoreFileTime += Date.now() - section;
|
||||
|
||||
const rootContext: WalkContext = {
|
||||
walkableEntry: {
|
||||
|
|
@ -62,15 +109,63 @@ class DFSWalker {
|
|||
const stack = [rootContext];
|
||||
|
||||
for (let cur = stack.pop(); cur; cur = stack.pop()) {
|
||||
// Only directories will be added to the stack
|
||||
const entries = await this.ide.listDir(cur.walkableEntry.uri);
|
||||
// Previous no caching approach:
|
||||
// const entries = await this.ide.listDir(cur.walkableEntry.uri);
|
||||
// const newIgnore = await getIgnoreContext(
|
||||
// cur.walkableEntry.uri,
|
||||
// entries,
|
||||
// this.ide,
|
||||
// defaultAndGlobalIgnores,
|
||||
// );
|
||||
|
||||
const newIgnore = await getIgnoreContext(
|
||||
// Only directories will be added to the stack
|
||||
dirs++;
|
||||
|
||||
section = Date.now();
|
||||
let entries: [string, FileType][] = [];
|
||||
const cachedListdir = walkDirCache.dirListCache.get(
|
||||
cur.walkableEntry.uri,
|
||||
entries,
|
||||
this.ide,
|
||||
defaultAndGlobalIgnores,
|
||||
);
|
||||
if (
|
||||
cachedListdir &&
|
||||
cachedListdir.time > Date.now() - LIST_DIR_CACHE_TIME
|
||||
) {
|
||||
entries = await cachedListdir.entries;
|
||||
listDirCacheHits++;
|
||||
} else {
|
||||
const promise = this.ide.listDir(cur.walkableEntry.uri);
|
||||
walkDirCache.dirListCache.set(cur.walkableEntry.uri, {
|
||||
time: Date.now(),
|
||||
entries: promise,
|
||||
});
|
||||
entries = await promise;
|
||||
}
|
||||
listDirTime += Date.now() - section;
|
||||
|
||||
section = Date.now();
|
||||
let newIgnore: Ignore;
|
||||
const cachedIgnore = walkDirCache.dirIgnoreCache.get(
|
||||
cur.walkableEntry.uri,
|
||||
);
|
||||
if (
|
||||
cachedIgnore &&
|
||||
cachedIgnore.time > Date.now() - IGNORE_FILE_CACHE_TIME
|
||||
) {
|
||||
newIgnore = await cachedIgnore.ignore;
|
||||
ignoreCacheHits++;
|
||||
} else {
|
||||
const ignorePromise = getIgnoreContext(
|
||||
cur.walkableEntry.uri,
|
||||
entries,
|
||||
this.ide,
|
||||
defaultAndGlobalIgnores,
|
||||
);
|
||||
walkDirCache.dirIgnoreCache.set(cur.walkableEntry.uri, {
|
||||
time: Date.now(),
|
||||
ignore: ignorePromise,
|
||||
});
|
||||
newIgnore = await ignorePromise;
|
||||
}
|
||||
|
||||
const ignoreContexts = [
|
||||
...cur.ignoreContexts,
|
||||
|
|
@ -79,6 +174,7 @@ class DFSWalker {
|
|||
dirname: cur.walkableEntry.relativeUriPath,
|
||||
},
|
||||
];
|
||||
ignoreFileTime += Date.now() - section;
|
||||
|
||||
for (const entry of entries) {
|
||||
if (this.entryIsSymlink(entry)) {
|
||||
|
|
@ -103,19 +199,24 @@ class DFSWalker {
|
|||
continue;
|
||||
}
|
||||
}
|
||||
let shouldInclude = true;
|
||||
let shouldIgnore = false;
|
||||
for (const ig of ignoreContexts) {
|
||||
if (shouldIgnore) {
|
||||
continue;
|
||||
}
|
||||
// remove the directory name and path separator from the match path, unless this an ignore file
|
||||
// in the root directory
|
||||
const prefixLength =
|
||||
ig.dirname.length === 0 ? 0 : ig.dirname.length + 1;
|
||||
// The ignore library expects a path relative to the ignore file location
|
||||
const matchPath = relPath.substring(prefixLength);
|
||||
section = Date.now();
|
||||
if (ig.ignore.ignores(matchPath)) {
|
||||
shouldInclude = false;
|
||||
shouldIgnore = true;
|
||||
}
|
||||
ignoreTime += Date.now() - section;
|
||||
}
|
||||
if (!shouldInclude) {
|
||||
if (shouldIgnore) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -141,6 +242,9 @@ class DFSWalker {
|
|||
}
|
||||
}
|
||||
}
|
||||
// console.log(
|
||||
// `Walk Dir Result:\nSource: ${this.options.source ?? "unknown"}\nDir: ${this.uri}\nDuration: ${Date.now() - start}ms:\n\tList dir: ${listDirTime}ms (${listDirCacheHits}/${dirs} cache hits)\n\tIgnore files: ${ignoreFileTime}ms (${ignoreCacheHits}/${dirs} cache hits)\n\tIgnoring: ${ignoreTime}ms`,
|
||||
// );
|
||||
}
|
||||
|
||||
private entryIsDirectory(entry: Entry) {
|
||||
|
|
@ -157,6 +261,15 @@ const defaultOptions: WalkerOptions = {
|
|||
returnRelativeUrisPaths: false,
|
||||
};
|
||||
|
||||
export async function* walkDirAsync(
|
||||
path: string,
|
||||
ide: IDE,
|
||||
_optionOverrides?: WalkerOptions,
|
||||
): AsyncGenerator<string> {
|
||||
const options = { ...defaultOptions, ..._optionOverrides };
|
||||
yield* new DFSWalker(path, ide, options).walk();
|
||||
}
|
||||
|
||||
export async function walkDir(
|
||||
uri: string,
|
||||
ide: IDE,
|
||||
|
|
@ -169,15 +282,6 @@ export async function walkDir(
|
|||
return urisOrRelativePaths;
|
||||
}
|
||||
|
||||
export async function* walkDirAsync(
|
||||
path: string,
|
||||
ide: IDE,
|
||||
_optionOverrides?: WalkerOptions,
|
||||
): AsyncGenerator<string> {
|
||||
const options = { ...defaultOptions, ..._optionOverrides };
|
||||
yield* new DFSWalker(path, ide, options).walk();
|
||||
}
|
||||
|
||||
export async function walkDirs(
|
||||
ide: IDE,
|
||||
_optionOverrides?: WalkerOptions,
|
||||
|
|
@ -227,6 +331,10 @@ export async function getIgnoreContext(
|
|||
getContinueIgnorePatterns(),
|
||||
]);
|
||||
|
||||
if (ignoreArrays[0].length === 0 && ignoreArrays[1].length === 0) {
|
||||
return defaultAndGlobalIgnores;
|
||||
}
|
||||
|
||||
// Note precedence here!
|
||||
const ignoreContext = ignore()
|
||||
.add(ignoreArrays[0]) // gitignore
|
||||
|
|
|
|||
|
|
@ -8,15 +8,18 @@ import { normalizeToMessageParts } from "../util/messageContent";
|
|||
|
||||
import { modelSupportsTools } from "./autodetect";
|
||||
|
||||
const TOOL_USE_RULES = `When using tools, follow the following guidelines:
|
||||
- Avoid calling tools unless they are absolutely necessary. For example, if you are asked a simple programming question you do not need web search. As another example, if the user asks you to explain something about code, do not create a new file.`;
|
||||
const TOOL_USE_RULES = `<tool_use_rules>
|
||||
When using tools, follow the following guidelines:
|
||||
- Avoid calling tools unless they are absolutely necessary. For example, if you are asked a simple programming question you do not need web search. As another example, if the user asks you to explain something about code, do not create a new file.
|
||||
</tool_use_rules>`;
|
||||
|
||||
function constructSystemPrompt(
|
||||
modelDescription: ModelDescription,
|
||||
useTools: boolean,
|
||||
): string | null {
|
||||
let systemMessage =
|
||||
"Always include the language and file name in the info string when you write code blocks, for example '```python file.py'.";
|
||||
let systemMessage = `<important_rules>
|
||||
Always include the language and file name in the info string when you write code blocks. If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'.
|
||||
</important_rules>`;
|
||||
if (useTools && modelSupportsTools(modelDescription)) {
|
||||
systemMessage += "\n\n" + TOOL_USE_RULES;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,9 +27,9 @@ class LlamaEncoding implements Encoding {
|
|||
}
|
||||
|
||||
class NonWorkerAsyncEncoder implements AsyncEncoder {
|
||||
constructor(private readonly encoding: Encoding) {}
|
||||
constructor(private readonly encoding: Encoding) { }
|
||||
|
||||
async close(): Promise<void> {}
|
||||
async close(): Promise<void> { }
|
||||
|
||||
async encode(text: string): Promise<number[]> {
|
||||
return this.encoding.encode(text);
|
||||
|
|
@ -366,6 +366,7 @@ function chatMessageIsEmpty(message: ChatMessage): boolean {
|
|||
message.content.trim() === "" &&
|
||||
!message.toolCalls
|
||||
);
|
||||
case "thinking":
|
||||
case "tool":
|
||||
return false;
|
||||
}
|
||||
|
|
@ -383,8 +384,8 @@ function compileChatMessages(
|
|||
): ChatMessage[] {
|
||||
let msgsCopy = msgs
|
||||
? msgs
|
||||
.map((msg) => ({ ...msg }))
|
||||
.filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system")
|
||||
.map((msg) => ({ ...msg }))
|
||||
.filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system")
|
||||
: [];
|
||||
|
||||
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
|
||||
|
|
@ -469,5 +470,6 @@ export {
|
|||
pruneLinesFromTop,
|
||||
pruneRawPromptFromTop,
|
||||
pruneStringFromBottom,
|
||||
pruneStringFromTop,
|
||||
pruneStringFromTop
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -59,15 +59,17 @@ import {
|
|||
toFimBody,
|
||||
} from "./openaiTypeConverters.js";
|
||||
|
||||
|
||||
export class LLMError extends Error {
|
||||
constructor(message: string, public llm: ILLM) {
|
||||
constructor(
|
||||
message: string,
|
||||
public llm: ILLM,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export function isModelInstaller(provider: any): provider is ModelInstaller {
|
||||
return provider && typeof provider.installModel === 'function';
|
||||
return provider && typeof provider.installModel === "function";
|
||||
}
|
||||
|
||||
export abstract class BaseLLM implements ILLM {
|
||||
|
|
@ -193,11 +195,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
options.completionOptions?.maxTokens ??
|
||||
(llmInfo?.maxCompletionTokens
|
||||
? Math.min(
|
||||
llmInfo.maxCompletionTokens,
|
||||
// Even if the model has a large maxTokens, we don't want to use that every time,
|
||||
// because it takes away from the context length
|
||||
this.contextLength / 4,
|
||||
)
|
||||
llmInfo.maxCompletionTokens,
|
||||
// Even if the model has a large maxTokens, we don't want to use that every time,
|
||||
// because it takes away from the context length
|
||||
this.contextLength / 4,
|
||||
)
|
||||
: DEFAULT_MAX_TOKENS),
|
||||
};
|
||||
this.requestOptions = options.requestOptions;
|
||||
|
|
@ -396,7 +398,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
let model = error?.match(/model '(.*)' not found/)?.[1];
|
||||
if (model && resp.url.match("127.0.0.1:11434")) {
|
||||
text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`;
|
||||
throw new LLMError(text, this);// No need to add HTTP status details
|
||||
throw new LLMError(text, this); // No need to add HTTP status details
|
||||
} else if (text.includes("/api/chat")) {
|
||||
text =
|
||||
"The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue.";
|
||||
|
|
@ -780,8 +782,9 @@ export abstract class BaseLLM implements ILLM {
|
|||
}
|
||||
}
|
||||
|
||||
let thinking = "";
|
||||
let completion = "";
|
||||
let citations: null | string[] = null
|
||||
let citations: null | string[] = null;
|
||||
|
||||
try {
|
||||
if (this.templateMessages) {
|
||||
|
|
@ -809,8 +812,6 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion = renderChatMessage(msg);
|
||||
} else {
|
||||
// Stream true
|
||||
console.log("Streaming");
|
||||
|
||||
const stream = this.openaiAdapter.chatCompletionStream(
|
||||
{
|
||||
...body,
|
||||
|
|
@ -821,9 +822,14 @@ export abstract class BaseLLM implements ILLM {
|
|||
for await (const chunk of stream) {
|
||||
const result = fromChatCompletionChunk(chunk);
|
||||
if (result) {
|
||||
completion += result.content;
|
||||
yield result;
|
||||
}
|
||||
if (!citations && (chunk as any).citations && Array.isArray((chunk as any).citations)) {
|
||||
if (
|
||||
!citations &&
|
||||
(chunk as any).citations &&
|
||||
Array.isArray((chunk as any).citations)
|
||||
) {
|
||||
citations = (chunk as any).citations;
|
||||
}
|
||||
}
|
||||
|
|
@ -834,8 +840,16 @@ export abstract class BaseLLM implements ILLM {
|
|||
signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
completion += chunk.content;
|
||||
yield chunk;
|
||||
|
||||
if (chunk.role === "assistant") {
|
||||
completion += chunk.content;
|
||||
yield chunk;
|
||||
}
|
||||
|
||||
if (chunk.role === "thinking") {
|
||||
thinking += chunk.content;
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -847,10 +861,24 @@ export abstract class BaseLLM implements ILLM {
|
|||
this._logTokensGenerated(completionOptions.model, prompt, completion);
|
||||
|
||||
if (logEnabled && this.writeLog) {
|
||||
if (thinking) {
|
||||
await this.writeLog(`Thinking:\n${thinking}\n\n`);
|
||||
}
|
||||
/*
|
||||
TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
|
||||
During tool use, you must pass thinking and redacted_thinking blocks back to the API,
|
||||
and you must include the complete unmodified block back to the API. This is critical
|
||||
for maintaining the model's reasoning flow and conversation integrity.
|
||||
|
||||
On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent
|
||||
requests when not using tools, so it's the simplest option to always add to history.
|
||||
*/
|
||||
await this.writeLog(`Completion:\n${completion}\n\n`);
|
||||
|
||||
if (citations) {
|
||||
await this.writeLog(`Citations:\n${citations.map((c, i) => `${i + 1}: ${c}`).join("\n")}\n\n`);
|
||||
await this.writeLog(
|
||||
`Citations:\n${citations.map((c, i) => `${i + 1}: ${c}`).join("\n")}\n\n`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -920,7 +948,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
);
|
||||
}
|
||||
|
||||
protected async *_streamComplete(
|
||||
protected async * _streamComplete(
|
||||
prompt: string,
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
|
|
@ -928,7 +956,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
throw new Error("Not implemented");
|
||||
}
|
||||
|
||||
protected async *_streamChat(
|
||||
protected async * _streamChat(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
|
|
|
|||
|
|
@ -30,11 +30,15 @@ class Anthropic extends BaseLLM {
|
|||
description: tool.function.description,
|
||||
input_schema: tool.function.parameters,
|
||||
})),
|
||||
thinking: options.reasoning ? {
|
||||
type: "enabled",
|
||||
budget_tokens: options.reasoningBudgetTokens,
|
||||
} : undefined,
|
||||
tool_choice: options.toolChoice
|
||||
? {
|
||||
type: "tool",
|
||||
name: options.toolChoice.function.name,
|
||||
}
|
||||
type: "tool",
|
||||
name: options.toolChoice.function.name,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
|
||||
|
|
@ -63,6 +67,23 @@ class Anthropic extends BaseLLM {
|
|||
input: JSON.parse(toolCall.function?.arguments || "{}"),
|
||||
})),
|
||||
};
|
||||
} else if (message.role === "thinking" && !message.redactedThinking) {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [{
|
||||
type: "thinking",
|
||||
thinking: message.content,
|
||||
signature: message.signature
|
||||
}]
|
||||
};
|
||||
} else if (message.role === "thinking" && message.redactedThinking) {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [{
|
||||
type: "redacted_thinking",
|
||||
data: message.redactedThinking
|
||||
}]
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof message.content === "string") {
|
||||
|
|
@ -174,12 +195,12 @@ class Anthropic extends BaseLLM {
|
|||
messages: msgs,
|
||||
system: shouldCacheSystemMessage
|
||||
? [
|
||||
{
|
||||
type: "text",
|
||||
text: this.systemMessage,
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
]
|
||||
{
|
||||
type: "text",
|
||||
text: this.systemMessage,
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
]
|
||||
: systemMessage,
|
||||
}),
|
||||
signal,
|
||||
|
|
@ -216,6 +237,11 @@ class Anthropic extends BaseLLM {
|
|||
lastToolUseId = value.content_block.id;
|
||||
lastToolUseName = value.content_block.name;
|
||||
}
|
||||
// handle redacted thinking
|
||||
if (value.content_block.type === "redacted_thinking") {
|
||||
console.log("redacted thinking", value.content_block.data);
|
||||
yield { role: "thinking", content: "", redactedThinking: value.content_block.data };
|
||||
}
|
||||
break;
|
||||
case "content_block_delta":
|
||||
// https://docs.anthropic.com/en/api/messages-streaming#delta-types
|
||||
|
|
@ -223,6 +249,12 @@ class Anthropic extends BaseLLM {
|
|||
case "text_delta":
|
||||
yield { role: "assistant", content: value.delta.text };
|
||||
break;
|
||||
case "thinking_delta":
|
||||
yield { role: "thinking", content: value.delta.thinking };
|
||||
break;
|
||||
case "signature_delta":
|
||||
yield { role: "thinking", content: "", signature: value.delta.signature };
|
||||
break;
|
||||
case "input_json_delta":
|
||||
if (!lastToolUseId || !lastToolUseName) {
|
||||
throw new Error("No tool use found");
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
|
||||
import { fromIni } from "@aws-sdk/credential-providers";
|
||||
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
|
||||
import Bedrock from "./Bedrock.js";
|
||||
import { ChatMessage, Chunk, CompletionOptions, UserChatMessage } from "../../index.js";
|
||||
|
||||
|
|
@ -15,7 +15,7 @@ jest.mock("@aws-sdk/client-bedrock-runtime", () => ({
|
|||
|
||||
// Mock credential provider
|
||||
jest.mock("@aws-sdk/credential-providers", () => ({
|
||||
fromIni: jest.fn().mockImplementation(() => async () => ({
|
||||
fromNodeProviderChain: jest.fn().mockImplementation(() => async () => ({
|
||||
accessKeyId: "test-access-key",
|
||||
secretAccessKey: "test-secret-key",
|
||||
sessionToken: "test-session-token",
|
||||
|
|
|
|||
|
|
@ -1,15 +1,17 @@
|
|||
import {
|
||||
BedrockRuntimeClient,
|
||||
ContentBlock,
|
||||
ConverseStreamCommand,
|
||||
InvokeModelCommand,
|
||||
Message
|
||||
} from "@aws-sdk/client-bedrock-runtime";
|
||||
import { fromIni } from "@aws-sdk/credential-providers";
|
||||
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
|
||||
|
||||
import {
|
||||
ChatMessage,
|
||||
Chunk,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
LLMOptions
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
|
@ -86,9 +88,9 @@ class Bedrock extends BaseLLM {
|
|||
});
|
||||
|
||||
let config_headers =
|
||||
this.requestOptions && this.requestOptions.headers
|
||||
? this.requestOptions.headers
|
||||
: {};
|
||||
this.requestOptions && this.requestOptions.headers
|
||||
? this.requestOptions.headers
|
||||
: {};
|
||||
// AWS SigV4 requires strict canonicalization of headers.
|
||||
// DO NOT USE "_" in your header name. It will return an error like below.
|
||||
// "The request signature we calculated does not match the signature you provided."
|
||||
|
|
@ -113,6 +115,7 @@ class Bedrock extends BaseLLM {
|
|||
try {
|
||||
response = await client.send(command, { abortSignal: signal });
|
||||
} catch (error: unknown) {
|
||||
console.error(error);
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
throw new Error(`Failed to communicate with Bedrock API: ${message}`);
|
||||
}
|
||||
|
|
@ -124,16 +127,34 @@ class Bedrock extends BaseLLM {
|
|||
try {
|
||||
for await (const chunk of response.stream) {
|
||||
|
||||
console.log(chunk);
|
||||
|
||||
if (chunk.contentBlockDelta?.delta) {
|
||||
|
||||
const delta: any = chunk.contentBlockDelta.delta
|
||||
|
||||
// Handle text content
|
||||
if (chunk.contentBlockDelta.delta.text) {
|
||||
yield { role: "assistant", content: chunk.contentBlockDelta.delta.text };
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle text content
|
||||
if ((chunk.contentBlockDelta.delta as any).reasoningContent?.text) {
|
||||
yield { role: "thinking", content: (chunk.contentBlockDelta.delta as any).reasoningContent.text };
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle signature for thinking
|
||||
if (delta.reasoningContent?.signature) {
|
||||
yield { role: "thinking", content: "", signature: delta.reasoningContent.signature };
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle redacted thinking
|
||||
if (delta.redactedReasoning?.data) {
|
||||
yield { role: "thinking", content: "", redactedThinking: delta.redactedReasoning.data };
|
||||
continue;
|
||||
}
|
||||
|
||||
if (chunk.contentBlockDelta.delta.toolUse?.input && this._currentToolResponse) {
|
||||
// Append the new input to the existing string
|
||||
if (this._currentToolResponse.input === undefined) {
|
||||
|
|
@ -145,6 +166,12 @@ class Bedrock extends BaseLLM {
|
|||
}
|
||||
|
||||
if (chunk.contentBlockStart?.start) {
|
||||
const start: any = chunk.contentBlockStart.start
|
||||
if (start.redactedReasoning) {
|
||||
yield { role: "thinking", content: "", redactedThinking: start.redactedReasoning.data };
|
||||
continue;
|
||||
}
|
||||
|
||||
const toolUse = chunk.contentBlockStart.start.toolUse;
|
||||
if (toolUse?.toolUseId && toolUse?.name) {
|
||||
this._currentToolResponse = {
|
||||
|
|
@ -186,6 +213,7 @@ class Bedrock extends BaseLLM {
|
|||
}
|
||||
throw new Error("Error processing Bedrock stream: Unknown error occurred");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -232,13 +260,19 @@ class Bedrock extends BaseLLM {
|
|||
?.filter((stop) => stop.trim() !== "")
|
||||
.slice(0, 4),
|
||||
},
|
||||
additionalModelRequestFields: {
|
||||
"thinking": options.reasoning ? {
|
||||
"type": "enabled",
|
||||
"budget_tokens": options.reasoningBudgetTokens
|
||||
} : undefined,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private _convertMessage(message: ChatMessage): any {
|
||||
private _convertMessage(message: ChatMessage): Message | null {
|
||||
// Handle system messages explicitly
|
||||
if (message.role === "system") {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
// Tool response handling
|
||||
|
|
@ -265,15 +299,43 @@ class Bedrock extends BaseLLM {
|
|||
return {
|
||||
role: "assistant",
|
||||
content: message.toolCalls.map((toolCall) => ({
|
||||
toolUse: {
|
||||
toolUseId: toolCall.id,
|
||||
name: toolCall.function?.name,
|
||||
input: JSON.parse(toolCall.function?.arguments || "{}"),
|
||||
}
|
||||
toolUse: {
|
||||
toolUseId: toolCall.id,
|
||||
name: toolCall.function?.name,
|
||||
input: JSON.parse(toolCall.function?.arguments || "{}"),
|
||||
}
|
||||
}))
|
||||
};
|
||||
}
|
||||
|
||||
if (message.role === "thinking") {
|
||||
if (message.redactedThinking) {
|
||||
const content: ContentBlock.ReasoningContentMember = {
|
||||
reasoningContent: {
|
||||
redactedContent: new Uint8Array(Buffer.from(message.redactedThinking))
|
||||
}
|
||||
};
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [content]
|
||||
};
|
||||
} else {
|
||||
const content: ContentBlock.ReasoningContentMember = {
|
||||
reasoningContent: {
|
||||
reasoningText: {
|
||||
text: (message.content as string) || "",
|
||||
signature: message.signature
|
||||
}
|
||||
|
||||
}
|
||||
};
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [content]
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Standard text message
|
||||
if (typeof message.content === "string") {
|
||||
return {
|
||||
|
|
@ -309,12 +371,14 @@ class Bedrock extends BaseLLM {
|
|||
}
|
||||
return null;
|
||||
}).filter(Boolean)
|
||||
};
|
||||
} as Message;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private _convertMessages(messages: ChatMessage[]): any[] {
|
||||
return messages
|
||||
|
||||
const converted = messages
|
||||
.map((message) => {
|
||||
try {
|
||||
return this._convertMessage(message);
|
||||
|
|
@ -324,11 +388,13 @@ class Bedrock extends BaseLLM {
|
|||
}
|
||||
})
|
||||
.filter(Boolean);
|
||||
return converted;
|
||||
|
||||
}
|
||||
|
||||
private async _getCredentials() {
|
||||
try {
|
||||
return await fromIni({
|
||||
return await fromNodeProviderChain({
|
||||
profile: this.profile,
|
||||
ignoreCache: true,
|
||||
})();
|
||||
|
|
@ -336,7 +402,7 @@ class Bedrock extends BaseLLM {
|
|||
console.warn(
|
||||
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
|
||||
);
|
||||
return await fromIni()();
|
||||
return await fromNodeProviderChain()();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import {
|
||||
BedrockRuntimeClient,
|
||||
InvokeModelWithResponseStreamCommand,
|
||||
BedrockRuntimeClient,
|
||||
InvokeModelWithResponseStreamCommand,
|
||||
} from "@aws-sdk/client-bedrock-runtime";
|
||||
import { fromIni } from "@aws-sdk/credential-providers";
|
||||
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
|
||||
|
||||
import { CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
|
@ -77,7 +77,7 @@ class BedrockImport extends BaseLLM {
|
|||
|
||||
private async _getCredentials() {
|
||||
try {
|
||||
return await fromIni({
|
||||
return await fromNodeProviderChain({
|
||||
profile: this.profile,
|
||||
ignoreCache: true,
|
||||
})();
|
||||
|
|
@ -85,7 +85,7 @@ class BedrockImport extends BaseLLM {
|
|||
console.warn(
|
||||
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
|
||||
);
|
||||
return await fromIni()();
|
||||
return await fromNodeProviderChain()();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -117,7 +117,7 @@ class Cohere extends BaseLLM {
|
|||
}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
const resp = await fetch(new URL("rerank", this.apiBase), {
|
||||
const resp = await this.fetch(new URL("rerank", this.apiBase), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
|
|
|
|||
|
|
@ -134,21 +134,11 @@ class Gemini extends BaseLLM {
|
|||
};
|
||||
}
|
||||
|
||||
private async *streamChatGemini(
|
||||
public prepareBody(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const apiURL = new URL(
|
||||
`models/${options.model}:streamGenerateContent?key=${this.apiKey}`,
|
||||
this.apiBase,
|
||||
);
|
||||
// This feels hacky to repeat code from above function but was the quickest
|
||||
// way to ensure system message re-formatting isn't done if user has specified v1
|
||||
const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase
|
||||
const isV1API = apiBase.includes("/v1/");
|
||||
|
||||
// Convert chat messages to contents
|
||||
isV1API: boolean,
|
||||
): GeminiChatRequestBody {
|
||||
const body: GeminiChatRequestBody = {
|
||||
contents: messages
|
||||
.filter((msg) => !(msg.role === "system" && isV1API))
|
||||
|
|
@ -303,15 +293,14 @@ class Gemini extends BaseLLM {
|
|||
}
|
||||
}
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
const response = await this.fetch(apiURL, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
|
||||
public async *processGeminiResponse(
|
||||
stream: AsyncIterable<string>,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
let buffer = "";
|
||||
for await (const chunk of streamResponse(response)) {
|
||||
for await (const chunk of stream) {
|
||||
buffer += chunk;
|
||||
if (buffer.startsWith("[")) {
|
||||
buffer = buffer.slice(1);
|
||||
|
|
@ -425,6 +414,35 @@ class Gemini extends BaseLLM {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async *streamChatGemini(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const apiURL = new URL(
|
||||
`models/${options.model}:streamGenerateContent?key=${this.apiKey}`,
|
||||
this.apiBase,
|
||||
);
|
||||
// This feels hacky to repeat code from above function but was the quickest
|
||||
// way to ensure system message re-formatting isn't done if user has specified v1
|
||||
const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase
|
||||
const isV1API = apiBase.includes("/v1/");
|
||||
|
||||
// Convert chat messages to contents
|
||||
const body = this.prepareBody(messages, options, isV1API);
|
||||
|
||||
const response = await this.fetch(apiURL, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
for await (const message of this.processGeminiResponse(
|
||||
streamResponse(response),
|
||||
)) {
|
||||
yield message;
|
||||
}
|
||||
}
|
||||
private async *streamChatBison(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import { Chunk, LLMOptions } from "../../index.js";
|
||||
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
|
||||
|
|
@ -36,17 +35,15 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
|
|||
}
|
||||
|
||||
async doEmbedRequest(batch: string[]): Promise<number[][]> {
|
||||
const resp = await withExponentialBackoff<Response>(() =>
|
||||
this.fetch(new URL("embed", this.apiBase), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
inputs: batch,
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
const resp = await this.fetch(new URL("embed", this.apiBase), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
inputs: batch,
|
||||
}),
|
||||
);
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
if (!resp.ok) {
|
||||
const text = await resp.text();
|
||||
const embedError = JSON.parse(text) as TEIEmbedErrorResponse;
|
||||
|
|
@ -59,11 +56,10 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
|
|||
}
|
||||
|
||||
async doInfoRequest(): Promise<TEIInfoResponse> {
|
||||
const resp = await withExponentialBackoff<Response>(() =>
|
||||
this.fetch(new URL("info", this.apiBase), {
|
||||
method: "GET",
|
||||
}),
|
||||
);
|
||||
// TODO - need to use custom fetch for this request?
|
||||
const resp = await this.fetch(new URL("info", this.apiBase), {
|
||||
method: "GET",
|
||||
});
|
||||
if (!resp.ok) {
|
||||
throw new Error(await resp.text());
|
||||
}
|
||||
|
|
@ -79,7 +75,7 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
|
|||
headers["Authorization"] = `Bearer ${this.apiKey}`;
|
||||
}
|
||||
|
||||
const resp = await fetch(new URL("rerank", this.apiBase), {
|
||||
const resp = await this.fetch(new URL("rerank", this.apiBase), {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
|
|
|
|||
|
|
@ -1,13 +1,19 @@
|
|||
import { JSONSchema7, JSONSchema7Object } from "json-schema";
|
||||
|
||||
import { ChatMessage, CompletionOptions, ModelInstaller, LLMOptions } from "../../index.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
ChatMessageRole,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
ModelInstaller,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { getRemoteModelInfo } from "../../util/ollamaHelper.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { streamResponse } from "../stream.js";
|
||||
import { getRemoteModelInfo } from "../../util/ollamaHelper.js";
|
||||
|
||||
type OllamaChatMessage = {
|
||||
role: "tool" | "user" | "assistant" | "system";
|
||||
role: ChatMessageRole;
|
||||
content: string;
|
||||
images?: string[] | null;
|
||||
tool_calls?: {
|
||||
|
|
@ -83,10 +89,10 @@ type OllamaBaseResponse = {
|
|||
model: string;
|
||||
created_at: string;
|
||||
} & (
|
||||
| {
|
||||
| {
|
||||
done: false;
|
||||
}
|
||||
| {
|
||||
| {
|
||||
done: true;
|
||||
done_reason: string;
|
||||
total_duration: number; // Time spent generating the response in nanoseconds
|
||||
|
|
@ -97,7 +103,7 @@ type OllamaBaseResponse = {
|
|||
eval_duration: number; // Time spent generating the response in nanoseconds
|
||||
context: number[]; // An encoding of the conversation used in this response; can be sent in the next request to keep conversational memory
|
||||
}
|
||||
);
|
||||
);
|
||||
|
||||
type OllamaErrorResponse = {
|
||||
error: string;
|
||||
|
|
@ -106,14 +112,14 @@ type OllamaErrorResponse = {
|
|||
type OllamaRawResponse =
|
||||
| OllamaErrorResponse
|
||||
| (OllamaBaseResponse & {
|
||||
response: string; // the generated response
|
||||
});
|
||||
response: string; // the generated response
|
||||
});
|
||||
|
||||
type OllamaChatResponse =
|
||||
| OllamaErrorResponse
|
||||
| (OllamaBaseResponse & {
|
||||
message: OllamaChatMessage;
|
||||
});
|
||||
message: OllamaChatMessage;
|
||||
});
|
||||
|
||||
interface OllamaTool {
|
||||
type: "function";
|
||||
|
|
@ -124,7 +130,7 @@ interface OllamaTool {
|
|||
};
|
||||
}
|
||||
|
||||
class Ollama extends BaseLLM implements ModelInstaller{
|
||||
class Ollama extends BaseLLM implements ModelInstaller {
|
||||
static providerName = "ollama";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "http://localhost:11434/",
|
||||
|
|
@ -143,7 +149,7 @@ class Ollama extends BaseLLM implements ModelInstaller{
|
|||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
|
||||
if (this.apiKey) {
|
||||
headers.Authorization = `Bearer ${this.apiKey}`;
|
||||
}
|
||||
|
|
@ -332,7 +338,7 @@ class Ollama extends BaseLLM implements ModelInstaller{
|
|||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
|
||||
if (this.apiKey) {
|
||||
headers.Authorization = `Bearer ${this.apiKey}`;
|
||||
}
|
||||
|
|
@ -359,6 +365,7 @@ class Ollama extends BaseLLM implements ModelInstaller{
|
|||
if ("error" in j) {
|
||||
throw new Error(j.error);
|
||||
}
|
||||
j.response ??= ''
|
||||
yield j.response;
|
||||
} catch (e) {
|
||||
throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
|
||||
|
|
@ -397,7 +404,7 @@ class Ollama extends BaseLLM implements ModelInstaller{
|
|||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
|
||||
if (this.apiKey) {
|
||||
headers.Authorization = `Bearer ${this.apiKey}`;
|
||||
}
|
||||
|
|
@ -483,7 +490,7 @@ class Ollama extends BaseLLM implements ModelInstaller{
|
|||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
|
||||
if (this.apiKey) {
|
||||
headers.Authorization = `Bearer ${this.apiKey}`;
|
||||
}
|
||||
|
|
@ -524,7 +531,7 @@ class Ollama extends BaseLLM implements ModelInstaller{
|
|||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
|
||||
if (this.apiKey) {
|
||||
headers.Authorization = `Bearer ${this.apiKey}`;
|
||||
}
|
||||
|
|
@ -550,7 +557,7 @@ class Ollama extends BaseLLM implements ModelInstaller{
|
|||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
|
||||
if (this.apiKey) {
|
||||
headers.Authorization = `Bearer ${this.apiKey}`;
|
||||
}
|
||||
|
|
@ -560,7 +567,7 @@ class Ollama extends BaseLLM implements ModelInstaller{
|
|||
model: this.model,
|
||||
input: chunks,
|
||||
}),
|
||||
headers: headers
|
||||
headers: headers,
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
|
|
@ -576,36 +583,43 @@ class Ollama extends BaseLLM implements ModelInstaller{
|
|||
return embedding;
|
||||
}
|
||||
|
||||
public async installModel(modelName: string, signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void): Promise<any> {
|
||||
const modelInfo = await getRemoteModelInfo(modelName, signal);
|
||||
if (!modelInfo) {
|
||||
throw new Error(`'${modelName}' not found in the Ollama registry!`);
|
||||
}
|
||||
const response = await fetch(this.getEndpoint("api/pull"), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({ name: modelName }),
|
||||
signal
|
||||
});
|
||||
public async installModel(
|
||||
modelName: string,
|
||||
signal: AbortSignal,
|
||||
progressReporter?: (task: string, increment: number, total: number) => void,
|
||||
): Promise<any> {
|
||||
const modelInfo = await getRemoteModelInfo(modelName, signal);
|
||||
if (!modelInfo) {
|
||||
throw new Error(`'${modelName}' not found in the Ollama registry!`);
|
||||
}
|
||||
const response = await fetch(this.getEndpoint("api/pull"), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({ name: modelName }),
|
||||
signal,
|
||||
});
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
//TODO: generate proper progress based on modelInfo size
|
||||
while (true) {
|
||||
const { done, value } = await reader?.read() || { done: true, value: undefined };
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
const chunk = new TextDecoder().decode(value);
|
||||
const lines = chunk.split('\n').filter(Boolean);
|
||||
for (const line of lines) {
|
||||
const data = JSON.parse(line);
|
||||
progressReporter?.(data.status, data.completed, data.total);
|
||||
}
|
||||
const reader = response.body?.getReader();
|
||||
//TODO: generate proper progress based on modelInfo size
|
||||
while (true) {
|
||||
const { done, value } = (await reader?.read()) || {
|
||||
done: true,
|
||||
value: undefined,
|
||||
};
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
const chunk = new TextDecoder().decode(value);
|
||||
const lines = chunk.split("\n").filter(Boolean);
|
||||
for (const line of lines) {
|
||||
const data = JSON.parse(line);
|
||||
progressReporter?.(data.status, data.completed, data.total);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -97,6 +97,10 @@ class OpenAI extends BaseLLM {
|
|||
return !!model && (model.startsWith("o1") || model.startsWith("o3"));
|
||||
}
|
||||
|
||||
private isFireworksAiModel(model?: string): boolean {
|
||||
return !!model && model.startsWith("accounts/fireworks/models");
|
||||
}
|
||||
|
||||
protected supportsPrediction(model: string): boolean {
|
||||
const SUPPORTED_MODELS = ["gpt-4o-mini", "gpt-4o", "mistral-large"];
|
||||
return SUPPORTED_MODELS.some((m) => model.includes(m));
|
||||
|
|
@ -274,7 +278,13 @@ class OpenAI extends BaseLLM {
|
|||
body.max_completion_tokens = undefined;
|
||||
}
|
||||
|
||||
if (body.tools?.length && !body.model?.startsWith("o3")) {
|
||||
if (body.tools?.length) {
|
||||
if (this.isFireworksAiModel(body.model)) {
|
||||
// fireworks.ai does not support parallel tool calls, but their api expects this to be true anyway otherwise they return an error.
|
||||
// tooling works with them as a inference provider once this is set to true.
|
||||
// https://docs.fireworks.ai/guides/function-calling#openai-compatibility
|
||||
body.parallel_tool_calls = true;
|
||||
}
|
||||
// To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs
|
||||
// In practice, setting this to true and asking for multiple tool calls
|
||||
// leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}'
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import {
|
||||
InvokeEndpointCommand,
|
||||
InvokeEndpointWithResponseStreamCommand,
|
||||
SageMakerRuntimeClient,
|
||||
InvokeEndpointCommand,
|
||||
InvokeEndpointWithResponseStreamCommand,
|
||||
SageMakerRuntimeClient,
|
||||
} from "@aws-sdk/client-sagemaker-runtime";
|
||||
import { fromIni } from "@aws-sdk/credential-providers";
|
||||
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
|
||||
|
||||
// @ts-ignore
|
||||
import jinja from "jinja-js";
|
||||
|
|
@ -130,14 +130,14 @@ class SageMaker extends BaseLLM {
|
|||
|
||||
private async _getCredentials() {
|
||||
try {
|
||||
return await fromIni({
|
||||
return await fromNodeProviderChain({
|
||||
profile: this.profile,
|
||||
})();
|
||||
} catch (e) {
|
||||
console.warn(
|
||||
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
|
||||
);
|
||||
return await fromIni()();
|
||||
return await fromNodeProviderChain()();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ class VertexAI extends BaseLLM {
|
|||
declare geminiInstance: Gemini;
|
||||
|
||||
static defaultOptions: Partial<LLMOptions> | undefined = {
|
||||
maxEmbeddingBatchSize: 5,
|
||||
maxEmbeddingBatchSize: 250,
|
||||
region: "us-central1",
|
||||
};
|
||||
|
||||
|
|
@ -35,6 +35,13 @@ class VertexAI extends BaseLLM {
|
|||
}
|
||||
|
||||
constructor(_options: LLMOptions) {
|
||||
if (_options.region !== "us-central1") {
|
||||
// Any region outside of us-central1 has a max batch size of 5.
|
||||
_options.maxEmbeddingBatchSize = Math.min(
|
||||
_options.maxEmbeddingBatchSize ?? 5,
|
||||
5,
|
||||
);
|
||||
}
|
||||
super(_options);
|
||||
this.apiBase ??= VertexAI.getDefaultApiBaseFrom(_options);
|
||||
this.vertexProvider =
|
||||
|
|
@ -143,97 +150,16 @@ class VertexAI extends BaseLLM {
|
|||
`publishers/google/models/${options.model}:streamGenerateContent`,
|
||||
this.apiBase,
|
||||
);
|
||||
// This feels hacky to repeat code from above function but was the quickest
|
||||
// way to ensure system message re-formatting isn't done if user has specified v1
|
||||
const isV1API = this.apiBase.includes("/v1/");
|
||||
|
||||
const contents = messages
|
||||
.map((msg) => {
|
||||
if (msg.role === "system" && !isV1API) {
|
||||
return null; // Don't include system message in contents
|
||||
}
|
||||
if (msg.role === "tool") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
role: msg.role === "assistant" ? "model" : "user",
|
||||
parts:
|
||||
typeof msg.content === "string"
|
||||
? [{ text: msg.content }]
|
||||
: msg.content.map(this.geminiInstance.continuePartToGeminiPart),
|
||||
};
|
||||
})
|
||||
.filter((c) => c !== null);
|
||||
|
||||
const body = {
|
||||
...this.geminiInstance.convertArgs(options),
|
||||
contents,
|
||||
// if this.systemMessage is defined, reformat it for Gemini API
|
||||
...(this.systemMessage &&
|
||||
!isV1API && {
|
||||
systemInstruction: { parts: [{ text: this.systemMessage }] },
|
||||
}),
|
||||
};
|
||||
const body = this.geminiInstance.prepareBody(messages, options, false);
|
||||
const response = await this.fetch(apiURL, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
let buffer = "";
|
||||
for await (const chunk of streamResponse(response)) {
|
||||
buffer += chunk;
|
||||
if (buffer.startsWith("[")) {
|
||||
buffer = buffer.slice(1);
|
||||
}
|
||||
if (buffer.endsWith("]")) {
|
||||
buffer = buffer.slice(0, -1);
|
||||
}
|
||||
if (buffer.startsWith(",")) {
|
||||
buffer = buffer.slice(1);
|
||||
}
|
||||
|
||||
const parts = buffer.split("\n,");
|
||||
|
||||
let foundIncomplete = false;
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const part = parts[i];
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(part);
|
||||
} catch (e) {
|
||||
foundIncomplete = true;
|
||||
continue; // yo!
|
||||
}
|
||||
if (data.error) {
|
||||
throw new Error(data.error.message);
|
||||
}
|
||||
// Check for existence of each level before accessing the final 'text' property
|
||||
if (data?.candidates?.[0]?.content?.parts?.[0]?.text) {
|
||||
// Incrementally stream the content to make it smoother
|
||||
const content = data.candidates[0].content.parts[0].text;
|
||||
const words = content.split(/(\s+)/);
|
||||
const delaySeconds = Math.min(4.0 / (words.length + 1), 0.1);
|
||||
while (words.length > 0) {
|
||||
const wordsToYield = Math.min(3, words.length);
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: words.splice(0, wordsToYield).join(""),
|
||||
};
|
||||
await delay(delaySeconds);
|
||||
}
|
||||
} else {
|
||||
// Handle the case where the expected data structure is not found
|
||||
if (data?.candidates?.[0]?.finishReason !== "STOP") {
|
||||
console.warn("Unexpected response format:", data);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (foundIncomplete) {
|
||||
buffer = parts[parts.length - 1];
|
||||
} else {
|
||||
buffer = "";
|
||||
}
|
||||
for await (const message of this.geminiInstance.processGeminiResponse(
|
||||
streamResponse(response),
|
||||
)) {
|
||||
yield message;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -337,7 +263,9 @@ class VertexAI extends BaseLLM {
|
|||
});
|
||||
|
||||
for await (const chunk of streamSse(response)) {
|
||||
yield chunk.choices[0].delta.content;
|
||||
if (chunk.choices?.[0].delta) {
|
||||
yield chunk.choices[0].delta.content;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -432,7 +360,9 @@ class VertexAI extends BaseLLM {
|
|||
}
|
||||
|
||||
supportsFim(): boolean {
|
||||
return ["code-gecko", "codestral-latest"].includes(this.model);
|
||||
return (
|
||||
this.model.includes("code-gecko") || this.model.includes("codestral")
|
||||
);
|
||||
}
|
||||
|
||||
protected async _embed(chunks: string[]): Promise<number[][]> {
|
||||
|
|
|
|||
|
|
@ -6,7 +6,10 @@ class Vllm extends OpenAI {
|
|||
static providerName = "vllm";
|
||||
constructor(options: LLMOptions) {
|
||||
super(options);
|
||||
this._setupCompletionOptions();
|
||||
|
||||
if (options.model === "AUTODETECT") {
|
||||
this._setupCompletionOptions();
|
||||
}
|
||||
}
|
||||
|
||||
private _setupCompletionOptions() {
|
||||
|
|
@ -22,7 +25,7 @@ class Vllm extends OpenAI {
|
|||
return;
|
||||
}
|
||||
const json = await response.json();
|
||||
const data = json.data;
|
||||
const data = json.data[0];
|
||||
this.model = data.id;
|
||||
this.contextLength = Number.parseInt(data.max_model_len);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ class Voyage extends OpenAI {
|
|||
return [];
|
||||
}
|
||||
const url = new URL("rerank", this.apiBase);
|
||||
const resp = await fetch(url, {
|
||||
const resp = await this.fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
|
|
|
|||
|
|
@ -65,7 +65,7 @@ class ContinueProxy extends OpenAI {
|
|||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
const url = new URL("rerank", this.apiBase);
|
||||
const resp = await fetch(url, {
|
||||
const resp = await this.fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
|
|
@ -75,6 +75,7 @@ class ContinueProxy extends OpenAI {
|
|||
query,
|
||||
documents: chunks.map((chunk) => chunk.content),
|
||||
model: this.model,
|
||||
...this.extraBodyProperties(),
|
||||
}),
|
||||
});
|
||||
const data: any = await resp.json();
|
||||
|
|
|
|||
|
|
@ -39,11 +39,28 @@ export const PROVIDER_TOOL_SUPPORT: Record<
|
|||
) {
|
||||
return true;
|
||||
}
|
||||
// firworks-ai https://docs.fireworks.ai/guides/function-calling
|
||||
if (model.startsWith("accounts/fireworks/models/")) {
|
||||
switch (model.substring(26)) {
|
||||
case "llama-v3p1-405b-instruct":
|
||||
case "llama-v3p1-70b-instruct":
|
||||
case "qwen2p5-72b-instruct":
|
||||
case "firefunction-v1":
|
||||
case "firefunction-v2":
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
},
|
||||
gemini: (model) => {
|
||||
// All gemini models support function calling
|
||||
return model.toLowerCase().includes("gemini");
|
||||
},
|
||||
vertexai: (model) => {
|
||||
// All gemini models except flash 2.0 lite support function calling
|
||||
return model.toLowerCase().includes("gemini") && !model.toLowerCase().includes("lite");;
|
||||
},
|
||||
bedrock: (model) => {
|
||||
// For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7
|
||||
if (
|
||||
|
|
|
|||
1478
core/package-lock.json
generated
1478
core/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@continuedev/core",
|
||||
"version": "1.0.13",
|
||||
"version": "1.1.0",
|
||||
"description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js",
|
||||
"scripts": {
|
||||
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest",
|
||||
|
|
@ -17,7 +17,7 @@
|
|||
"@babel/preset-env": "^7.24.7",
|
||||
"@biomejs/biome": "1.6.4",
|
||||
"@google/generative-ai": "^0.11.4",
|
||||
"@types/diff": "^5.2.2",
|
||||
"@types/diff": "^7.0.1",
|
||||
"@types/follow-redirects": "^1.14.4",
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/jquery": "^3.5.29",
|
||||
|
|
@ -42,11 +42,11 @@
|
|||
"ts-jest": "^29.1.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
|
||||
"@aws-sdk/credential-providers": "^3.620.1",
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.758.0",
|
||||
"@aws-sdk/credential-providers": "^3.758.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "^1.0.52",
|
||||
"@continuedev/config-yaml": "^1.0.60",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.2",
|
||||
"@continuedev/openai-adapters": "^1.0.10",
|
||||
|
|
|
|||
|
|
@ -16,7 +16,9 @@ export async function getPromptFilesFromDir(
|
|||
return [];
|
||||
}
|
||||
|
||||
const uris = await walkDir(dir, ide);
|
||||
const uris = await walkDir(dir, ide, {
|
||||
source: "get dir prompt files",
|
||||
});
|
||||
const promptFilePaths = uris.filter((p) => p.endsWith(".prompt"));
|
||||
const results = promptFilePaths.map(async (uri) => {
|
||||
const content = await ide.readFile(uri); // make a try catch
|
||||
|
|
|
|||
|
|
@ -68,7 +68,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
"config/deleteModel": [{ title: string }, void];
|
||||
"config/addContextProvider": [ContextProviderWithParams, void];
|
||||
"config/reload": [undefined, ConfigResult<BrowserSerializedContinueConfig>];
|
||||
"config/listProfiles": [undefined, ProfileDescription[] | null];
|
||||
"config/listProfiles": [
|
||||
undefined,
|
||||
{ profiles: ProfileDescription[] | null; selectedProfileId: string | null },
|
||||
];
|
||||
"config/refreshProfiles": [undefined, void];
|
||||
"config/openProfile": [{ profileId: string | undefined }, void];
|
||||
"config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema];
|
||||
|
|
@ -184,6 +187,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
"files/opened": [{ uris?: string[] }, void];
|
||||
"files/created": [{ uris?: string[] }, void];
|
||||
"files/deleted": [{ uris?: string[] }, void];
|
||||
"files/closed": [{ uris?: string[] }, void];
|
||||
|
||||
// Docs etc. Indexing. TODO move codebase to this
|
||||
"indexing/reindex": [{ type: string; id: string }, void];
|
||||
|
|
|
|||
|
|
@ -15,4 +15,5 @@ export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
|||
{ profiles: ProfileDescription[]; selectedProfileId: string | null },
|
||||
void,
|
||||
];
|
||||
didSelectOrganization: [{ orgId: string | null }, void];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -72,7 +72,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
|
||||
[
|
||||
"configUpdate",
|
||||
"configError",
|
||||
"getDefaultModelTitle",
|
||||
"indexProgress", // Codebase
|
||||
"indexing/statusUpdate", // Docs, etc.
|
||||
|
|
@ -84,4 +83,6 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
|
|||
"getWebviewHistoryLength",
|
||||
"getCurrentSessionId",
|
||||
"docs/suggestions",
|
||||
"didCloseFiles",
|
||||
"didSelectOrganization",
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml";
|
||||
import { ConfigResult } from "@continuedev/config-yaml";
|
||||
import type {
|
||||
BrowserSerializedContinueConfig,
|
||||
ContextItemWithId,
|
||||
|
|
@ -16,8 +16,7 @@ export type ToWebviewFromIdeOrCoreProtocol = {
|
|||
},
|
||||
void,
|
||||
];
|
||||
configError: [ConfigValidationError[] | undefined, void];
|
||||
getDefaultModelTitle: [undefined, string];
|
||||
getDefaultModelTitle: [undefined, string | undefined];
|
||||
indexProgress: [IndexingProgressUpdate, void]; // Codebase
|
||||
"indexing/statusUpdate": [IndexingStatus, void]; // Docs, etc.
|
||||
refreshSubmenuItems: [
|
||||
|
|
@ -26,6 +25,7 @@ export type ToWebviewFromIdeOrCoreProtocol = {
|
|||
},
|
||||
void,
|
||||
];
|
||||
didCloseFiles: [{ uris: string[] }, void];
|
||||
isContinueInputFocused: [undefined, boolean];
|
||||
addContextItem: [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import childProcess from "node:child_process";
|
||||
import util from "node:util";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ToolImpl } from ".";
|
||||
|
||||
const asyncExec = util.promisify(childProcess.exec);
|
||||
|
||||
|
|
@ -26,7 +26,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: error.stderr ?? error.toString(),
|
||||
content: error.stderr || error.stdout || error.toString(),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
// Generated by continue
|
||||
|
||||
import generateRepoMap from "./generateRepoMap";
|
||||
import { testIde, testLLM } from "../test/fixtures";
|
||||
import {
|
||||
setUpTestDir,
|
||||
tearDownTestDir,
|
||||
addToTestDir,
|
||||
TEST_DIR,
|
||||
} from "../test/testDir";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { getRepoMapFilePath } from "./paths";
|
||||
import { CodeSnippetsCodebaseIndex } from "../indexing/CodeSnippetsIndex";
|
||||
import { testIde, testLLM } from "../test/fixtures";
|
||||
import {
|
||||
addToTestDir,
|
||||
setUpTestDir,
|
||||
tearDownTestDir,
|
||||
TEST_DIR,
|
||||
} from "../test/testDir";
|
||||
import generateRepoMap from "./generateRepoMap";
|
||||
import { getRepoMapFilePath } from "./paths";
|
||||
|
||||
describe.skip("generateRepoMap", () => {
|
||||
beforeEach(() => {
|
||||
|
|
@ -49,7 +49,8 @@ describe.skip("generateRepoMap", () => {
|
|||
"def bar():",
|
||||
],
|
||||
},
|
||||
hasMore: false,
|
||||
hasMoreSnippets: false,
|
||||
hasMoreUris: false,
|
||||
};
|
||||
});
|
||||
|
||||
|
|
@ -108,7 +109,8 @@ describe.skip("generateRepoMap", () => {
|
|||
[path.join(TEST_DIR, "file1.js")]: [],
|
||||
[path.join(TEST_DIR, "subdir/file2.py")]: [],
|
||||
},
|
||||
hasMore: false,
|
||||
hasMoreSnippets: false,
|
||||
hasMoreUris: false,
|
||||
};
|
||||
});
|
||||
|
||||
|
|
@ -161,7 +163,8 @@ describe.skip("generateRepoMap", () => {
|
|||
[path.join(TEST_DIR, "file1.js")]: ["function foo() {}"],
|
||||
[path.join(TEST_DIR, "subdir/file2.py")]: ["def foo():"],
|
||||
},
|
||||
hasMore: false,
|
||||
hasMoreSnippets: false,
|
||||
hasMoreUris: false,
|
||||
};
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -24,7 +24,8 @@ class RepoMapGenerator {
|
|||
private allUris: string[] = [];
|
||||
private pathsInDirsWithSnippets: Set<string> = new Set();
|
||||
|
||||
private BATCH_SIZE = 100;
|
||||
private SNIPPETS_BATCH_SIZE = 100;
|
||||
private URI_BATCH_SIZE = 100;
|
||||
private REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5;
|
||||
private PREAMBLE =
|
||||
"Below is a repository map. \n" +
|
||||
|
|
@ -50,20 +51,29 @@ class RepoMapGenerator {
|
|||
|
||||
async generate(): Promise<string> {
|
||||
this.dirs = this.options.dirUris ?? (await this.ide.getWorkspaceDirs());
|
||||
this.allUris = await walkDirs(this.ide, undefined, this.dirs);
|
||||
this.allUris = await walkDirs(
|
||||
this.ide,
|
||||
{
|
||||
source: "generate repo map",
|
||||
},
|
||||
this.dirs,
|
||||
);
|
||||
|
||||
// Initialize
|
||||
await this.writeToStream(this.PREAMBLE);
|
||||
|
||||
if (this.options.includeSignatures) {
|
||||
// Process uris and signatures
|
||||
let offset = 0;
|
||||
let snippetOffset = 0;
|
||||
let uriOffset = 0;
|
||||
while (true) {
|
||||
const { groupedByUri, hasMore } =
|
||||
const { groupedByUri, hasMoreSnippets, hasMoreUris } =
|
||||
await CodeSnippetsCodebaseIndex.getPathsAndSignatures(
|
||||
this.allUris,
|
||||
offset,
|
||||
this.BATCH_SIZE,
|
||||
uriOffset,
|
||||
this.URI_BATCH_SIZE,
|
||||
snippetOffset,
|
||||
this.SNIPPETS_BATCH_SIZE,
|
||||
);
|
||||
// process batch
|
||||
for (const [uri, signatures] of Object.entries(groupedByUri)) {
|
||||
|
|
@ -103,10 +113,17 @@ class RepoMapGenerator {
|
|||
await this.writeToStream(content);
|
||||
}
|
||||
}
|
||||
if (!hasMore || this.contentTokens >= this.maxRepoMapTokens) {
|
||||
if (this.contentTokens >= this.maxRepoMapTokens) {
|
||||
break;
|
||||
}
|
||||
if (hasMoreSnippets) {
|
||||
snippetOffset += this.SNIPPETS_BATCH_SIZE;
|
||||
} else if (hasMoreUris) {
|
||||
snippetOffset = 0;
|
||||
uriOffset += this.URI_BATCH_SIZE;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
offset += this.BATCH_SIZE;
|
||||
}
|
||||
|
||||
// Remaining Uris just so that written repo map isn't incomplete
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ export function renderChatMessage(message: ChatMessage): string {
|
|||
switch (message.role) {
|
||||
case "user":
|
||||
case "assistant":
|
||||
case "thinking":
|
||||
case "system":
|
||||
return stripImages(message.content);
|
||||
case "tool":
|
||||
|
|
@ -36,6 +37,7 @@ export function normalizeToMessageParts(message: ChatMessage): MessagePart[] {
|
|||
switch (message.role) {
|
||||
case "user":
|
||||
case "assistant":
|
||||
case "thinking":
|
||||
case "system":
|
||||
return Array.isArray(message.content)
|
||||
? message.content
|
||||
|
|
|
|||
|
|
@ -6,6 +6,11 @@ import * as URI from "uri-js";
|
|||
|
||||
// Converts a local path to a file:/// URI
|
||||
export function localPathToUri(path: string) {
|
||||
// This may incidentally solve bugs, but it is primarily here to warn us if we accidentally try to double-convert. It doesn't handle other URI schemes.
|
||||
if (path.startsWith("file://")) {
|
||||
console.warn("localPathToUri: path already starts with file://");
|
||||
return path;
|
||||
}
|
||||
const url = pathToFileURL(path);
|
||||
return URI.normalize(url.toString());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -103,7 +103,7 @@ export function getConfigJsonPath(ideType: IdeType = "vscode"): string {
|
|||
return p;
|
||||
}
|
||||
|
||||
export function getConfigYamlPath(ideType: IdeType): string {
|
||||
export function getConfigYamlPath(ideType?: IdeType): string {
|
||||
const p = path.join(getContinueGlobalPath(), "config.yaml");
|
||||
// if (!fs.existsSync(p)) {
|
||||
// if (ideType === "jetbrains") {
|
||||
|
|
@ -115,6 +115,14 @@ export function getConfigYamlPath(ideType: IdeType): string {
|
|||
return p;
|
||||
}
|
||||
|
||||
export function getPrimaryConfigFilePath(): string {
|
||||
const configYamlPath = getConfigYamlPath();
|
||||
if (fs.existsSync(configYamlPath)) {
|
||||
return configYamlPath;
|
||||
}
|
||||
return getConfigJsonPath();
|
||||
}
|
||||
|
||||
export function getConfigTsPath(): string {
|
||||
const p = path.join(getContinueGlobalPath(), "config.ts");
|
||||
if (!fs.existsSync(p)) {
|
||||
|
|
@ -353,6 +361,10 @@ export function getGlobalPromptsPath(): string {
|
|||
return path.join(getContinueGlobalPath(), "prompts");
|
||||
}
|
||||
|
||||
export function getGlobalAssistantsPath(): string {
|
||||
return path.join(getContinueGlobalPath(), "assistants");
|
||||
}
|
||||
|
||||
export function readAllGlobalPromptFiles(
|
||||
folderPath: string = getGlobalPromptsPath(),
|
||||
): { path: string; content: string }[] {
|
||||
|
|
@ -406,6 +418,10 @@ export function migrateV1DevDataFiles() {
|
|||
moveToV1FolderIfExists("autocomplete", "autocomplete");
|
||||
}
|
||||
|
||||
export function getLocalEnvironmentDotFilePath(): string {
|
||||
return path.join(getContinueGlobalPath(), ".local");
|
||||
}
|
||||
|
||||
export function getStagingEnvironmentDotFilePath(): string {
|
||||
return path.join(getContinueGlobalPath(), ".staging");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -879,6 +879,11 @@ assignee = currentUser() AND resolution = Unresolved order by updated DESC
|
|||
|
||||
You can override this query by setting the `issueQuery` parameter.
|
||||
|
||||
#### Max results
|
||||
|
||||
You can set the `maxResults` parameter to limit the number of results returned. The default is `50`.
|
||||
|
||||
|
||||
### `@Discord`
|
||||
|
||||
Reference the messages in a Discord channel.
|
||||
|
|
|
|||
16
docs/docs/customize/deep-dives/_apply.md
Normal file
16
docs/docs/customize/deep-dives/_apply.md
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
---
|
||||
description: Learn how to use the Apply feature
|
||||
keywords: [apply, speculative]
|
||||
toc_max_heading_level: 5
|
||||
---
|
||||
|
||||
<!-- This is a work in progress and excluded by prefixing the file name with an underscore -->
|
||||
|
||||
# Apply
|
||||
|
||||
## Instant Diff Apply
|
||||
|
||||
If you have large files (exeeding the output token of your model) the edit apply will delete all lines that exceed the model window. To mitigate you can instead of applying the changes directly, ask the chat LLM to "generate a unified diff".
|
||||
The resulting diff (if the LLM has not made a mistake) can be instantly applied, changing only the lines that need to change.
|
||||
|
||||
Explainer Video: https://youtu.be/b7Xxsot4gyw
|
||||
|
|
@ -49,8 +49,8 @@ There are a few options that let you configure the behavior of the `@codebase` c
|
|||
context:
|
||||
- provider: codebase
|
||||
params:
|
||||
nRetrieve: 25,
|
||||
nFinal: 5,
|
||||
nRetrieve: 25
|
||||
nFinal: 5
|
||||
useReranking: true
|
||||
```
|
||||
</TabItem>
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ keywords: [config, settings, customize]
|
|||
|
||||
Continue can be deeply customized. 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 Config File` to open the file. When editing this file, you can see the available options suggested as you type, or check the reference below.
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ Most custom configuration is done by editing `config.yaml` (or the older `config
|
|||
- MacOS and Linux: `~/.continue/config.yaml`
|
||||
- Windows: `%USERPROFILE%\.continue\config.yaml`
|
||||
|
||||
You can easily access config file from the Continue Chat sidebar. Open the sidebar by pressing <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains) and click the "gear" icon in header to open the Settings page. Then click the button labeled `Open configuration file`.
|
||||
You can easily access config file from the Continue Chat sidebar. Open the sidebar by pressing <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains) and click the "gear" icon in header to open the Settings page. Then click the button labeled `Open Assistant configuration`.
|
||||
|
||||

|
||||
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ Which takes you to this page:
|
|||
|
||||

|
||||
|
||||
Click the `Open Config File` button to open your configuration file. See the [Configuration Reference](../reference.md) for more information.
|
||||
Click the `Open Assistant configuration` button to open your configuration file. See the [Configuration Reference](../reference.md) for more information.
|
||||
|
||||
Below that, the following settings which are not part of a configuration file are available:
|
||||
|
||||
|
|
|
|||
|
|
@ -36,6 +36,7 @@ Each model has specific configuration options tailored to its provider and funct
|
|||
- `engine`: Engine for Azure OpenAI requests.
|
||||
- `capabilities`: Override auto-detected capabilities:
|
||||
- `uploadImage`: Boolean indicating if the model supports image uploads.
|
||||
- `tools`: Boolean indicating if the model supports tool calls.
|
||||
|
||||
_(AWS Only)_
|
||||
|
||||
|
|
|
|||
|
|
@ -31,6 +31,10 @@ Hub blocks and assistants are identified with a slug in the format `owner-slug/b
|
|||
|
||||
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.
|
||||
|
||||
:::info
|
||||
Note that `uses` blocks cannot be used with a local `config.yaml`
|
||||
:::
|
||||
|
||||
For example, the following assistant imports an Anthropic model and defines an Ollama DeepSeek one.
|
||||
|
||||
```yaml title="Assistant models section"
|
||||
|
|
@ -134,6 +138,7 @@ The `models` section defines the language models used in your configuration. Mod
|
|||
- `provider` (**required**): The provider of the model (e.g., `openai`, `ollama`).
|
||||
- `model` (**required**): The specific model name (e.g., `gpt-4`, `starcoder`).
|
||||
- `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`.
|
||||
- `embedOptions`: If the model includes role `embed`, these settings apply for embeddings:
|
||||
|
||||
- `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens.
|
||||
|
|
@ -187,6 +192,17 @@ models:
|
|||
model: codestral-latest
|
||||
roles:
|
||||
- autocomplete
|
||||
|
||||
- name: My Model - OpenAI-Compatible
|
||||
provider: openai
|
||||
apiBase: http://my-endpoint/v1
|
||||
model: my-custom-model
|
||||
capabilities:
|
||||
- tool_use
|
||||
- image_input
|
||||
roles:
|
||||
- chat
|
||||
- edit
|
||||
```
|
||||
|
||||
---
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ const config = {
|
|||
favicon: "img/favicon.ico",
|
||||
|
||||
// Set the production url of your site here
|
||||
url: "https://continue.dev",
|
||||
url: "https://docs.continue.dev",
|
||||
// Set the /<baseUrl>/ pathname under which your site is served
|
||||
// For GitHub pages deployment, it is often '/<projectName>/'
|
||||
baseUrl: "/",
|
||||
|
|
|
|||
|
|
@ -45,13 +45,13 @@ We recommend configuring **Codestral** or **code-gecko** as your autocomplete mo
|
|||
|
||||
## Embeddings model
|
||||
|
||||
We recommend configuring **text-embedding-004** as your embeddings model.
|
||||
We recommend configuring **text-embedding-005** as your embeddings model.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"embeddingsProvider": {
|
||||
"provider": "vertexai",
|
||||
"model": "text-embedding-004",
|
||||
"model": "text-embedding-005",
|
||||
"projectId": "[PROJECT_ID]",
|
||||
"region": "us-central1"
|
||||
}
|
||||
|
|
|
|||
13
docs/package-lock.json
generated
13
docs/package-lock.json
generated
|
|
@ -1756,9 +1756,9 @@
|
|||
}
|
||||
},
|
||||
"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.26.10",
|
||||
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.10.tgz",
|
||||
"integrity": "sha512-2WJMeRQPHKSPemqk/awGrAiuFfzBmOIPXKizAsVhWH9YJqLZ0H+HS4c8loHGgW6utJ3E/ejXQUsiGaQy2NZ9Fw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"regenerator-runtime": "^0.14.0"
|
||||
|
|
@ -1768,9 +1768,10 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@babel/runtime-corejs3": {
|
||||
"version": "7.26.0",
|
||||
"resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.26.0.tgz",
|
||||
"integrity": "sha512-YXHu5lN8kJCb1LOb9PgV6pvak43X2h4HvRApcN5SdWeaItQOzfn1hgP6jasD6KWQyJDBxrVmA9o9OivlnNJK/w==",
|
||||
"version": "7.26.10",
|
||||
"resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.26.10.tgz",
|
||||
"integrity": "sha512-uITFQYO68pMEYR46AHgQoyBg7KPPJDAbGn4jUTIRgCFJIp88MIBUianVOplhZDEec07bp9zIyr4Kp0FCyQzmWg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"core-js-pure": "^3.30.2",
|
||||
"regenerator-runtime": "^0.14.0"
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
|
|||
pluginName=continue-intellij-extension
|
||||
pluginRepositoryUrl=https://github.com/continuedev/continue
|
||||
# SemVer format -> https://semver.org
|
||||
pluginVersion=1.0.2
|
||||
pluginVersion=1.0.4
|
||||
# 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
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
package com.github.continuedev.continueintellijextension.activities
|
||||
|
||||
import com.intellij.openapi.fileEditor.FileEditorManagerListener
|
||||
import com.github.continuedev.continueintellijextension.auth.AuthListener
|
||||
import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
|
||||
import com.github.continuedev.continueintellijextension.auth.ControlPlaneSessionInfo
|
||||
|
|
@ -37,6 +37,7 @@ import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent
|
|||
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
|
||||
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent
|
||||
import com.intellij.ide.ui.LafManagerListener
|
||||
import com.intellij.openapi.vfs.VirtualFile
|
||||
|
||||
fun showTutorial(project: Project) {
|
||||
val tutorialFileName = getTutorialFileName()
|
||||
|
|
@ -199,6 +200,24 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
|
|||
}
|
||||
})
|
||||
|
||||
|
||||
connection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, object : FileEditorManagerListener {
|
||||
override fun fileClosed(source: FileEditorManager, file: VirtualFile) {
|
||||
file.toUriOrNull()?.let { uri ->
|
||||
val data = mapOf("uris" to listOf(uri))
|
||||
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))
|
||||
continuePluginService.coreMessenger?.request("files/opened", data, null) { _ -> }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
|
||||
// Listen for theme changes
|
||||
connection.subscribe(LafManagerListener.TOPIC, LafManagerListener {
|
||||
val colors = GetTheme().getTheme();
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.auth
|
|||
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.github.continuedev.continueintellijextension.utils.Desktop
|
||||
import com.google.gson.Gson
|
||||
import com.intellij.credentialStore.Credentials
|
||||
import com.intellij.ide.passwordSafe.PasswordSafe
|
||||
|
|
@ -12,7 +13,6 @@ import com.intellij.openapi.components.service
|
|||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.remoteServer.util.CloudConfigurationUtil.createCredentialAttributes
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import java.awt.Desktop
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
|
@ -153,8 +153,7 @@ class ContinueAuthService {
|
|||
) { response ->
|
||||
val authUrl = ((response as? Map<*, *>)?.get("content") as? Map<*, *>)?.get("url") as? String
|
||||
if (authUrl != null) {
|
||||
// Open the auth URL in the browser
|
||||
Desktop.getDesktop().browse(java.net.URI(authUrl))
|
||||
Desktop.browse(java.net.URI(authUrl))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -58,7 +58,6 @@ class MessageTypes {
|
|||
// Note: If updating these values, make a corresponding update in
|
||||
// core/protocol/passThrough.ts
|
||||
val PASS_THROUGH_TO_WEBVIEW = listOf(
|
||||
"configError",
|
||||
"configUpdate",
|
||||
"getDefaultModelTitle",
|
||||
"indexProgress", // Codebase
|
||||
|
|
@ -71,6 +70,8 @@ class MessageTypes {
|
|||
"getWebviewHistoryLength",
|
||||
"getCurrentSessionId",
|
||||
"docs/suggestions",
|
||||
"didCloseFiles",
|
||||
"didSelectOrganization"
|
||||
)
|
||||
|
||||
// Note: If updating these values, make a corresponding update in
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import com.github.continuedev.continueintellijextension.utils.OS
|
|||
import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID
|
||||
import com.github.continuedev.continueintellijextension.utils.getOS
|
||||
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
|
||||
import com.github.continuedev.continueintellijextension.utils.Desktop
|
||||
import com.google.gson.Gson
|
||||
import com.intellij.codeInsight.daemon.impl.HighlightInfo
|
||||
import com.intellij.execution.configurations.GeneralCommandLine
|
||||
|
|
@ -36,7 +37,6 @@ import okhttp3.MediaType.Companion.toMediaType
|
|||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.awt.Desktop
|
||||
import java.awt.Toolkit
|
||||
import java.awt.datatransfer.DataFlavor
|
||||
import java.io.BufferedReader
|
||||
|
|
@ -239,7 +239,7 @@ class IntelliJIDE(
|
|||
|
||||
override suspend fun openUrl(url: String) {
|
||||
withContext(Dispatchers.IO) {
|
||||
Desktop.getDesktop().browse(URI(url))
|
||||
Desktop.browse(java.net.URI(url))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import com.intellij.openapi.fileEditor.FileEditorManager
|
|||
import com.intellij.openapi.fileEditor.TextEditor
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.vfs.VirtualFile
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
|
||||
|
|
@ -179,7 +180,7 @@ class DiffStreamHandler(
|
|||
// Update the highlighter to show the current line
|
||||
curLine.highlighter?.let { editor.markupModel.removeHighlighter(it) }
|
||||
curLine.highlighter = editor.markupModel.addLineHighlighter(
|
||||
curLineKey, min(curLine.index, editor.document.lineCount - 1), HighlighterLayer.LAST
|
||||
curLineKey, min(curLine.index, max(0, editor.document.lineCount - 1)), HighlighterLayer.LAST
|
||||
)
|
||||
|
||||
// Remove the unfinished lines highlighter
|
||||
|
|
|
|||
|
|
@ -0,0 +1,214 @@
|
|||
/*
|
||||
* Copyright © 2017 jjYBdx4IL (https://github.com/jjYBdx4IL)
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package com.github.continuedev.continueintellijextension.utils
|
||||
|
||||
import org.apache.commons.lang3.SystemUtils
|
||||
import org.slf4j.LoggerFactory
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.net.URI
|
||||
|
||||
object Desktop {
|
||||
private val LOG = LoggerFactory.getLogger(Desktop::class.java)
|
||||
|
||||
fun browse(uri: URI): Boolean {
|
||||
if (browseDESKTOP(uri)) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (openSystemSpecific(uri.toString())) {
|
||||
return true
|
||||
}
|
||||
|
||||
LOG.warn("failed to browse {}", uri)
|
||||
return false
|
||||
}
|
||||
|
||||
fun open(file: File): Boolean {
|
||||
if (openDESKTOP(file)) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (openSystemSpecific(file.path)) {
|
||||
return true
|
||||
}
|
||||
|
||||
LOG.warn("failed to open {}", file.absolutePath)
|
||||
return false
|
||||
}
|
||||
|
||||
fun edit(file: File): Boolean {
|
||||
if (editDESKTOP(file)) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (openSystemSpecific(file.path)) {
|
||||
return true
|
||||
}
|
||||
|
||||
LOG.warn("failed to edit {}", file.absolutePath)
|
||||
return false
|
||||
}
|
||||
|
||||
private fun openSystemSpecific(what: String): Boolean {
|
||||
if (SystemUtils.IS_OS_LINUX) {
|
||||
if (isXDG() && runCommand("xdg-open", "%s", what)) {
|
||||
return true
|
||||
}
|
||||
if (isKDE() && runCommand("kde-open", "%s", what)) {
|
||||
return true
|
||||
}
|
||||
if (isGNOME() && runCommand("gnome-open", "%s", what)) {
|
||||
return true
|
||||
}
|
||||
if (runCommand("kde-open", "%s", what)) {
|
||||
return true
|
||||
}
|
||||
if (runCommand("gnome-open", "%s", what)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
if (SystemUtils.IS_OS_MAC && runCommand("open", "%s", what)) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (SystemUtils.IS_OS_WINDOWS && runCommand("explorer", "%s", what)) {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
private fun browseDESKTOP(uri: URI): Boolean {
|
||||
return try {
|
||||
if (!java.awt.Desktop.isDesktopSupported()) {
|
||||
LOG.debug("Platform is not supported.")
|
||||
return false
|
||||
}
|
||||
|
||||
if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.BROWSE)) {
|
||||
LOG.debug("BROWSE is not supported.")
|
||||
return false
|
||||
}
|
||||
|
||||
LOG.info("Trying to use Desktop.getDesktop().browse() with {}", uri.toString())
|
||||
java.awt.Desktop.getDesktop().browse(uri)
|
||||
true
|
||||
} catch (t: Throwable) {
|
||||
LOG.error("Error using desktop browse.", t)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun openDESKTOP(file: File): Boolean {
|
||||
return try {
|
||||
if (!java.awt.Desktop.isDesktopSupported()) {
|
||||
LOG.debug("Platform is not supported.")
|
||||
return false
|
||||
}
|
||||
|
||||
if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.OPEN)) {
|
||||
LOG.debug("OPEN is not supported.")
|
||||
return false
|
||||
}
|
||||
|
||||
LOG.info("Trying to use Desktop.getDesktop().open() with {}", file.toString())
|
||||
java.awt.Desktop.getDesktop().open(file)
|
||||
true
|
||||
} catch (t: Throwable) {
|
||||
LOG.error("Error using desktop open.", t)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun editDESKTOP(file: File): Boolean {
|
||||
return try {
|
||||
if (!java.awt.Desktop.isDesktopSupported()) {
|
||||
LOG.debug("Platform is not supported.")
|
||||
return false
|
||||
}
|
||||
|
||||
if (!java.awt.Desktop.getDesktop().isSupported(java.awt.Desktop.Action.EDIT)) {
|
||||
LOG.debug("EDIT is not supported.")
|
||||
return false
|
||||
}
|
||||
|
||||
LOG.info("Trying to use Desktop.getDesktop().edit() with {}", file)
|
||||
java.awt.Desktop.getDesktop().edit(file)
|
||||
true
|
||||
} catch (t: Throwable) {
|
||||
LOG.error("Error using desktop edit.", t)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun runCommand(command: String, args: String, file: String): Boolean {
|
||||
LOG.info("Trying to exec:\n cmd = {}\n args = {}\n %s = {}", command, args, file)
|
||||
|
||||
val parts = prepareCommand(command, args, file)
|
||||
|
||||
return try {
|
||||
val p = Runtime.getRuntime().exec(parts)
|
||||
if (p == null) {
|
||||
false
|
||||
} else {
|
||||
try {
|
||||
val retval = p.exitValue()
|
||||
if (retval == 0) {
|
||||
LOG.error("Process ended immediately.")
|
||||
false
|
||||
} else {
|
||||
LOG.error("Process crashed.")
|
||||
false
|
||||
}
|
||||
} catch (itse: IllegalThreadStateException) {
|
||||
LOG.error("Process is running.")
|
||||
true
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
LOG.error("Error running command.", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun prepareCommand(command: String, args: String?, file: String): Array<String> {
|
||||
val parts = mutableListOf<String>()
|
||||
parts.add(command)
|
||||
|
||||
args?.split(" ")?.forEach { s ->
|
||||
parts.add(String.format(s, file).trim())
|
||||
}
|
||||
|
||||
return parts.toTypedArray()
|
||||
}
|
||||
|
||||
private fun isXDG(): Boolean {
|
||||
val xdgSessionId = System.getenv("XDG_SESSION_ID")
|
||||
return !xdgSessionId.isNullOrEmpty()
|
||||
}
|
||||
|
||||
private fun isGNOME(): Boolean {
|
||||
val gdmSession = System.getenv("GDMSESSION")
|
||||
return gdmSession?.lowercase()?.contains("gnome") == true
|
||||
}
|
||||
|
||||
private fun isKDE(): Boolean {
|
||||
val gdmSession = System.getenv("GDMSESSION")
|
||||
return gdmSession?.lowercase()?.contains("kde") == true
|
||||
}
|
||||
}
|
||||
|
|
@ -175,6 +175,7 @@
|
|||
"openai",
|
||||
"free-trial",
|
||||
"anthropic",
|
||||
"anthropic-vertexai",
|
||||
"cohere",
|
||||
"bedrock",
|
||||
"bedrockimport",
|
||||
|
|
@ -187,9 +188,11 @@
|
|||
"llama.cpp",
|
||||
"replicate",
|
||||
"gemini",
|
||||
"gemini-vertexai",
|
||||
"lmstudio",
|
||||
"llamafile",
|
||||
"mistral",
|
||||
"mistral-vertexai",
|
||||
"deepinfra",
|
||||
"groq",
|
||||
"fireworks",
|
||||
|
|
@ -251,6 +254,8 @@
|
|||
"### vLLM\nvLLM is a highly performant way of hosting LLMs for a team. To get started, follow their [quickstart](https://docs.vllm.ai/en/latest/getting_started/quickstart.html) to set up your server.",
|
||||
"### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/).",
|
||||
"### Ask Sage\nAsk Sage is an agnostic hosted service that provides language models. To get started with Ask Sage:\n1. Obtain an API key from your account. For more information, visit [Ask Sage](https://docs.asksage.ai/).\n2. Paste the API key below.\n3. Select a model preset.\n> [Reference](https://docs.asksage.ai/)",
|
||||
"### Nebius\nNebius AI platform is a cloud service for machine learning model inference and training. To get started, obtain an API key from the [Nebius console](https://console.nebius.ai/).",
|
||||
"### Vertex AI\nVertex AI provides access to Google's foundation models and ML tools. To get started, enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc).",
|
||||
"### xAI offers a world class developer tool set to build scalable applications powered by Grok. To get started, obtain an API key from [the x Console](https://console.x.ai/), and see the [docs](https://docs.x.ai/docs/)",
|
||||
"### Secure AI management software that helps enterprises adopt and manage AI across their workforce. To get started, obtain an API key from [the Kindo console](https://app.kindo.ai/settings/api), and see the [website](https://app.kindo.ai//)",
|
||||
"### Moonshot\nTo get started with Moonshot AI, obtain your API key from [Moonshot AI](https://platform.moonshot.cn/). Moonshot AI provides high-quality large language models with competitive pricing.\n> [Reference](https://platform.moonshot.cn/docs/api)",
|
||||
|
|
@ -946,7 +951,10 @@
|
|||
"gemini-1.5-flash",
|
||||
"gemini-1.5-flash-8b",
|
||||
"gemini-2.0-flash-exp",
|
||||
"gemini-2.0-flash"
|
||||
"gemini-2.0-flash",
|
||||
"gemini-2.0-flash-thinking-exp-01-21",
|
||||
"gemini-2.0-pro-exp-02-05",
|
||||
"gemini-2.0-flash-lite-preview-02-05"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -1319,7 +1327,17 @@
|
|||
"nvidia/Llama-3.1-Nemotron-70B-Instruct",
|
||||
"Qwen/Qwen2-VL-72B-Instruct",
|
||||
"TeleAI/TeleMM",
|
||||
"deepseek-ai/DeepSeek-V2.5"
|
||||
"deepseek-ai/DeepSeek-V2.5",
|
||||
"deepseek-ai/deepseek-vl2",
|
||||
"deepseek-ai/Janus-Pro-7B",
|
||||
"deepseek-ai/DeepSeek-V3",
|
||||
"deepseek-ai/DeepSeek-R1",
|
||||
"deepseek-ai/DeepSeek-R1-Distill-Qwen-14B",
|
||||
"deepseek-ai/DeepSeek-R1-Distill-Qwen-32B",
|
||||
"deepseek-ai/DeepSeek-R1-Distill-Llama-70B",
|
||||
"deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B",
|
||||
"deepseek-ai/DeepSeek-R1-Distill-Qwen-7B",
|
||||
"deepseek-ai/DeepSeek-R1-Distill-Llama-8B"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -2311,6 +2329,10 @@
|
|||
"type": "string",
|
||||
"description": "Customize the query used to find Jira issues"
|
||||
},
|
||||
"maxResults": {
|
||||
"type": "string",
|
||||
"description": "The maximum number of issues that will be returned. Defaults to 50."
|
||||
},
|
||||
"apiVersion": {
|
||||
"type": "integer",
|
||||
"markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property.",
|
||||
|
|
@ -2837,11 +2859,11 @@
|
|||
"description": "The name of your VertexAI project"
|
||||
},
|
||||
"region": {
|
||||
"description": "The region your VertexAI model is hosted in - typically central1",
|
||||
"default": "central1"
|
||||
"description": "The region your VertexAI model is hosted in - typically us-central1",
|
||||
"default": "us-central1"
|
||||
},
|
||||
"model": {
|
||||
"default": "text-embedding-004"
|
||||
"default": "text-embedding-005"
|
||||
}
|
||||
},
|
||||
"required": ["projectId", "model", "region"]
|
||||
|
|
|
|||
16
extensions/vscode/package-lock.json
generated
16
extensions/vscode/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"version": "1.1.4",
|
||||
"version": "1.1.11",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "continue",
|
||||
"version": "1.1.4",
|
||||
"version": "1.1.11",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/fetch": "^1.0.3",
|
||||
|
|
@ -99,14 +99,14 @@
|
|||
},
|
||||
"../../core": {
|
||||
"name": "@continuedev/core",
|
||||
"version": "1.0.13",
|
||||
"version": "1.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
|
||||
"@aws-sdk/credential-providers": "^3.620.1",
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.758.0",
|
||||
"@aws-sdk/credential-providers": "^3.758.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "^1.0.52",
|
||||
"@continuedev/config-yaml": "^1.0.60",
|
||||
"@continuedev/fetch": "^1.0.4",
|
||||
"@continuedev/llm-info": "^1.0.2",
|
||||
"@continuedev/openai-adapters": "^1.0.10",
|
||||
|
|
@ -171,7 +171,7 @@
|
|||
"@babel/preset-env": "^7.24.7",
|
||||
"@biomejs/biome": "1.6.4",
|
||||
"@google/generative-ai": "^0.11.4",
|
||||
"@types/diff": "^5.2.2",
|
||||
"@types/diff": "^7.0.1",
|
||||
"@types/follow-redirects": "^1.14.4",
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/jquery": "^3.5.29",
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"author": "Continue Dev, Inc",
|
||||
"version": "1.1.5",
|
||||
"version": "1.1.12",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/continuedev/continue"
|
||||
|
|
@ -320,7 +320,7 @@
|
|||
"group": "Continue"
|
||||
},
|
||||
{
|
||||
"command": "continue.focusContinueSessionId",
|
||||
"command": "continue.focusContinueInput",
|
||||
"category": "Continue",
|
||||
"title": "Focus Continue Chat",
|
||||
"group": "Continue"
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue