Merge branch 'staging' into nate/existing-user-onboarding

This commit is contained in:
Nate 2025-02-22 19:13:12 -08:00
commit cc36e3b62a
104 changed files with 5582 additions and 6600 deletions

View file

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

View file

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

22
.vscode/tasks.json vendored
View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -50,7 +50,7 @@ export class ConfigHandler {
private profiles: ProfileLifecycleManager[] | null = null; // null until profiles are loaded
private selectedProfileId: string | null = null;
private localProfileManager: ProfileLifecycleManager;
private controlPlaneClient: ControlPlaneClient;
controlPlaneClient: ControlPlaneClient;
initializedPromise: Promise<void>;

View file

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

View file

@ -18,6 +18,7 @@ import {
EmbeddingsProviderDescription,
IContextProvider,
IDE,
IdeInfo,
IdeSettings,
IdeType,
ILLM,
@ -62,7 +63,11 @@ import {
getEsbuildBinaryPath,
} from "../util/paths";
import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml";
import {
ConfigResult,
ConfigValidationError,
ModelRole,
} from "@continuedev/config-yaml";
import { useHub } from "../control-plane/env";
import { localPathToUri } from "../util/pathToUri";
import {
@ -72,7 +77,8 @@ import {
defaultSlashCommandsVscode,
} from "./default";
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
import { modifyContinueConfigWithSharedConfig } from "./sharedConfig";
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
import { getModelByRole } from "./util";
import { validateConfig } from "./validation.js";
export function resolveSerializedConfig(
@ -238,6 +244,7 @@ async function intermediateToFinalConfig(
config: Config,
ide: IDE,
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
@ -326,7 +333,7 @@ async function intermediateToFinalConfig(
...model.requestOptions,
...config.requestOptions,
};
model.roles = model.roles ?? ["chat"]; // Default to chat role if not specified
model.roles = model.roles ?? ["chat", "apply", "edit", "summarize"]; // Default to chat role if not specified
}
if (allowFreeTrial) {
@ -436,23 +443,28 @@ async function intermediateToFinalConfig(
}
// Embeddings Provider
const embeddingsProviderDescription = config.embeddingsProvider as
| EmbeddingsProviderDescription
| undefined;
if (embeddingsProviderDescription?.provider) {
const { provider, ...options } = embeddingsProviderDescription;
function getEmbeddingsILLM(
embedConfig: EmbeddingsProviderDescription | ILLM | undefined,
): ILLM | null {
if (!embedConfig) {
return null;
}
if ("providerName" in embedConfig) {
return embedConfig;
}
const { provider, ...options } = embedConfig;
const embeddingsProviderClass = allEmbeddingsProviders[provider];
if (embeddingsProviderClass) {
if (
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
) {
config.embeddingsProvider = new embeddingsProviderClass();
return new embeddingsProviderClass();
} else {
const llmOptions: LLMOptions = {
model: options.model ?? "UNSPECIFIED",
...options,
};
config.embeddingsProvider = new embeddingsProviderClass(
return new embeddingsProviderClass(
llmOptions,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
@ -461,42 +473,74 @@ async function intermediateToFinalConfig(
}),
);
}
} else {
errors.push({
fatal: false,
message: `Embeddings provider ${provider} not found. Using default`,
});
}
return null;
}
if (!config.embeddingsProvider) {
config.embeddingsProvider = new TransformersJsEmbeddingsProvider();
}
const newEmbedder = getEmbeddingsILLM(config.embeddingsProvider);
// Reranker
if (config.reranker && !(config.reranker as ILLM | undefined)?.rerank) {
function getRerankingILLM(
rerankingConfig: ILLM | RerankerDescription | undefined,
): ILLM | null {
if (!rerankingConfig) {
return null;
}
if ("providerName" in rerankingConfig) {
return rerankingConfig;
}
const { name, params } = config.reranker as RerankerDescription;
const rerankerClass = AllRerankers[name];
if (name === "llm") {
const llm = models.find((model) => model.title === params?.modelTitle);
if (!llm) {
console.warn(`Unknown model ${params?.modelTitle}`);
errors.push({
fatal: false,
message: `Unknown reranking model ${params?.modelTitle}`,
});
return null;
} else {
config.reranker = new LLMReranker(llm);
return new LLMReranker(llm);
}
} else if (rerankerClass) {
const llmOptions: LLMOptions = {
model: "rerank-2",
...params,
};
config.reranker = new rerankerClass(llmOptions);
return new rerankerClass(llmOptions);
}
return null;
}
const newReranker = getRerankingILLM(config.reranker);
let continueConfig: ContinueConfig = {
const continueConfig: ContinueConfig = {
...config,
contextProviders,
models,
embeddingsProvider: config.embeddingsProvider as any,
tabAutocompleteModels,
reranker: config.reranker as any,
tools: allTools,
modelsByRole: {
chat: models,
edit: models,
apply: models,
summarize: models,
autocomplete: [...tabAutocompleteModels],
embed: newEmbedder ? [newEmbedder] : [],
rerank: newReranker ? [newReranker] : [],
},
selectedModelByRole: {
chat: null, // Not implemented (uses GUI defaultModel)
edit: null,
apply: null,
embed: newEmbedder ?? null,
autocomplete: null,
rerank: newReranker ?? null,
summarize: null, // Not implemented
},
};
// Apply MCP if specified
@ -538,48 +582,112 @@ async function intermediateToFinalConfig(
);
}
// Handle experimental modelRole config values for apply and edit
const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
if (inlineEditModel) {
const match = continueConfig.models.find(
(m) => m.title === inlineEditModel,
);
if (match) {
continueConfig.selectedModelByRole.edit = match;
continueConfig.modelsByRole.edit = [match]; // The only option if inlineEdit role is set
} else {
errors.push({
fatal: false,
message: `experimental.modelRoles.inlineEdit model title ${inlineEditModel} not found in models array`,
});
}
}
const applyBlockModel = getModelByRole(
continueConfig,
"applyCodeBlock",
)?.title;
if (applyBlockModel) {
const match = continueConfig.models.find(
(m) => m.title === applyBlockModel,
);
if (match) {
continueConfig.selectedModelByRole.apply = match;
continueConfig.modelsByRole.apply = [match]; // The only option if applyCodeBlock role is set
} else {
errors.push({
fatal: false,
message: `experimental.modelRoles.applyCodeBlock model title ${inlineEditModel} not found in models array`,
});
}
}
// Add transformers JS to the embed models list if not already added
if (
ideInfo.ideType === "vscode" &&
!continueConfig.modelsByRole.embed.find(
(m) => m.providerName === "transformers.js",
)
) {
continueConfig.modelsByRole.embed.push(
new TransformersJsEmbeddingsProvider(),
);
}
return { config: continueConfig, errors };
}
function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
return {
provider: llm.providerName,
model: llm.model,
title: llm.title ?? llm.model,
apiKey: llm.apiKey,
apiBase: llm.apiBase,
contextLength: llm.contextLength,
template: llm.template,
completionOptions: llm.completionOptions,
systemMessage: llm.systemMessage,
requestOptions: llm.requestOptions,
promptTemplates: llm.promptTemplates as any,
capabilities: llm.capabilities,
roles: llm.roles,
};
}
async function finalToBrowserConfig(
final: ContinueConfig,
ide: IDE,
): Promise<BrowserSerializedContinueConfig> {
return {
allowAnonymousTelemetry: final.allowAnonymousTelemetry,
models: final.models.map((m) => ({
provider: m.providerName,
model: m.model,
title: m.title ?? m.model,
apiKey: m.apiKey,
apiBase: m.apiBase,
contextLength: m.contextLength,
template: m.template,
completionOptions: m.completionOptions,
systemMessage: m.systemMessage,
requestOptions: m.requestOptions,
promptTemplates: m.promptTemplates as any,
capabilities: m.capabilities,
roles: m.roles,
})),
models: final.models.map(llmToSerializedModelDescription),
systemMessage: final.systemMessage,
completionOptions: final.completionOptions,
slashCommands: final.slashCommands?.map((s) => ({
name: s.name,
description: s.description,
params: s.params, //PZTODO: is this why params aren't referenced properly by slash commands?
params: s.params, // TODO: is this why params aren't referenced properly by slash commands?
})),
contextProviders: final.contextProviders?.map((c) => c.description),
disableIndexing: final.disableIndexing,
disableSessionTitles: final.disableSessionTitles,
userToken: final.userToken,
embeddingsProvider: final.embeddingsProvider?.embeddingId,
ui: final.ui,
experimental: final.experimental,
docs: final.docs,
tools: final.tools,
tabAutocompleteOptions: final.tabAutocompleteOptions,
usePlatform: await useHub(ide.getIdeSettings()),
modelsByRole: Object.fromEntries(
Object.entries(final.modelsByRole).map(([k, v]) => [
k,
v.map(llmToSerializedModelDescription),
]),
) as Record<ModelRole, ModelDescription[]>, // TODO better types here
selectedModelByRole: Object.fromEntries(
Object.entries(final.selectedModelByRole).map(([k, v]) => [
k,
v ? llmToSerializedModelDescription(v) : null,
]),
) as Record<ModelRole, ModelDescription | null>, // TODO better types here
// data not included here because client doesn't need
};
}
@ -767,7 +875,7 @@ async function loadContinueConfigFromJson(
ide: IDE,
workspaceConfigs: ContinueRcJson[],
ideSettings: IdeSettings,
ideType: IdeType,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
@ -781,7 +889,7 @@ async function loadContinueConfigFromJson(
} = loadSerializedConfig(
workspaceConfigs,
ideSettings,
ideType,
ideInfo.ideType,
overrideConfigJson,
ide,
);
@ -798,16 +906,16 @@ async function loadContinueConfigFromJson(
// Apply shared config
// TODO: override several of these values with user/org shared config
const sharedConfig = new GlobalContext().getSharedConfig();
const withShared = modifyContinueConfigWithSharedConfig(
serialized,
sharedConfig,
);
const withShared = modifyAnyConfigWithSharedConfig(serialized, sharedConfig);
// Convert serialized to intermediate config
let intermediate = await serializedToIntermediateConfig(withShared, ide);
// Apply config.ts to modify intermediate config
const configJsContents = await buildConfigTsandReadConfigJs(ide, ideType);
const configJsContents = await buildConfigTsandReadConfigJs(
ide,
ideInfo.ideType,
);
if (configJsContents) {
try {
// Try config.ts first
@ -867,6 +975,7 @@ async function loadContinueConfigFromJson(
intermediate,
ide,
ideSettings,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,

View file

@ -38,6 +38,7 @@ export default class LocalProfileLoader implements IProfileLoader {
undefined,
undefined,
undefined,
this.description.id,
);
this.description.errors = result.errors;

View file

@ -1,7 +1,8 @@
import { ConfigResult, AssistantUnrolled } from "@continuedev/config-yaml";
import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
import doLoadConfig from "./doLoadConfig.js";
@ -68,6 +69,7 @@ export default class PlatformProfileLoader implements IProfileLoader {
ownerSlug: this.ownerSlug,
packageSlug: this.packageSlug,
},
this.description.id,
);
return {

View file

@ -4,6 +4,7 @@ import {
AssistantUnrolled,
ConfigResult,
ConfigValidationError,
ModelRole,
} from "@continuedev/config-yaml";
import {
ContinueConfig,
@ -24,6 +25,7 @@ import { loadContinueConfigFromJson } from "../load";
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
import { PlatformConfigMetadata } from "./PlatformProfileLoader";
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
export default async function doLoadConfig(
ide: IDE,
@ -33,7 +35,7 @@ export default async function doLoadConfig(
overrideConfigJson: SerializedContinueConfig | undefined,
overrideConfigYaml: AssistantUnrolled | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
workspaceId?: string,
profileId: string,
): Promise<ConfigResult<ContinueConfig>> {
const workspaceConfigs = await getWorkspaceConfigs(ide);
const ideInfo = await ide.getIdeInfo();
@ -59,7 +61,7 @@ export default async function doLoadConfig(
ide,
workspaceConfigs.map((c) => JSON.stringify(c)),
ideSettings,
ideInfo.ideType,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,
@ -75,7 +77,7 @@ export default async function doLoadConfig(
ide,
workspaceConfigs,
ideSettings,
ideInfo.ideType,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,
@ -86,6 +88,11 @@ export default async function doLoadConfig(
configLoadInterrupted = result.configLoadInterrupted;
}
// Rectify model selections for each role
if (newConfig) {
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
}
if (configLoadInterrupted || !newConfig) {
return { errors, config: newConfig, configLoadInterrupted: true };
}
@ -117,7 +124,7 @@ export default async function doLoadConfig(
controlPlaneProxyUrl += "/";
}
const controlPlaneProxyInfo = {
workspaceId,
profileId,
controlPlaneProxyUrl,
workOsAccessToken,
};
@ -147,21 +154,26 @@ async function injectControlPlaneProxyInfo(
config: ContinueConfig,
info: ControlPlaneProxyInfo,
): Promise<ContinueConfig> {
[...config.models, ...(config.tabAutocompleteModels ?? [])].forEach(
async (model) => {
Object.keys(config.modelsByRole).forEach((key) => {
config.modelsByRole[key as ModelRole].forEach((model) => {
if (model.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
},
);
});
});
if (config.embeddingsProvider?.providerName === "continue-proxy") {
(config.embeddingsProvider as ContinueProxy).controlPlaneProxyInfo = info;
}
Object.keys(config.selectedModelByRole).forEach((key) => {
const model = config.selectedModelByRole[key as ModelRole];
if (model?.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
});
if (config.reranker?.providerName === "continue-proxy") {
(config.reranker as ContinueProxy).controlPlaneProxyInfo = info;
}
config.models.forEach((model) => {
if (model.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
});
return config;
}

View file

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

View file

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

View file

@ -15,10 +15,11 @@ export function convertConfigJsonToConfigYaml(
name: model.title,
// defaultCompletionOptions: model.completionOptions,
provider: model.provider,
roles: ["chat"],
roles: ["chat", "edit", "apply", "summarize"],
}),
),
// ... tabAutocompleteModels
// TODO
// tabAutocompleteModels
// embeddingsModels
// rerankModels
],

View file

@ -14,8 +14,8 @@ import {
ContinueConfig,
IContextProvider,
IDE,
IdeInfo,
IdeSettings,
IdeType,
SlashCommand,
} from "../..";
import { slashFromCustomCommand } from "../../commands";
@ -37,7 +37,7 @@ import { GlobalContext } from "../../util/GlobalContext";
import { getConfigYamlPath } from "../../util/paths";
import { getSystemPromptDotFile } from "../getSystemPromptDotFile";
import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader";
import { modifyContinueConfigWithSharedConfig } from "../sharedConfig";
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { llmsFromModelConfig } from "./models";
@ -98,6 +98,7 @@ async function configYamlToContinueConfig(
config: AssistantUnrolled,
ide: IDE,
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
@ -111,10 +112,8 @@ async function configYamlToContinueConfig(
...(config.prompts?.map(slashFromCustomCommand) ?? []),
],
models: [],
tabAutocompleteModels: [],
tools: allTools,
systemMessage: config.rules?.join("\n"),
embeddingsProvider: new TransformersJsEmbeddingsProvider(),
experimental: {
modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({
transport: {
@ -132,59 +131,125 @@ async function configYamlToContinueConfig(
faviconUrl: doc.faviconUrl,
})),
contextProviders: [],
modelsByRole: {
chat: [],
edit: [],
apply: [],
embed: [],
autocomplete: [],
rerank: [],
summarize: [],
},
selectedModelByRole: {
chat: null, // not currently used - defaultModel on GUI is used
edit: null, // not currently used
apply: null,
embed: null,
autocomplete: null,
rerank: null,
summarize: null,
},
data: config.data,
};
// Models
const modelsArrayRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
for (const model of config.models ?? []) {
model.roles = model.roles ?? ["chat"]; // Default to chat role if not specified
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,
);
//
if (modelsArrayRoles.some((role) => model.roles?.includes(role))) {
// Main model array
const llms = await llmsFromModelConfig(
model,
ide,
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
continueConfig.systemMessage,
);
continueConfig.models.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("apply")) {
continueConfig.modelsByRole.apply.push(...llms);
}
if (model.roles?.includes("edit")) {
continueConfig.modelsByRole.edit.push(...llms);
}
if (model.roles?.includes("autocomplete")) {
// Autocomplete models array
const llms = await llmsFromModelConfig(
model,
ide,
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
continueConfig.systemMessage,
);
continueConfig.tabAutocompleteModels?.push(...llms);
continueConfig.modelsByRole.autocomplete.push(...llms);
}
if (
model.roles?.includes("apply") &&
!continueConfig.experimental?.modelRoles?.applyCodeBlock
) {
continueConfig.experimental ??= {};
continueConfig.experimental!.modelRoles ??= {};
continueConfig.experimental!.modelRoles!.applyCodeBlock = model.name;
if (model.roles?.includes("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 {
errors.push({
fatal: false,
message: `Unsupported embeddings model provider found: ${provider}`,
});
}
}
if (
model.roles?.includes("edit") &&
!continueConfig.experimental?.modelRoles?.inlineEdit
) {
continueConfig.experimental ??= {};
continueConfig.experimental!.modelRoles ??= {};
continueConfig.experimental!.modelRoles!.inlineEdit = model.name;
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}`,
});
}
}
}
// Add transformers js to the embed models in vs code if not already added
if (
ideInfo.ideType === "vscode" &&
!continueConfig.modelsByRole.embed.find(
(m) => m.providerName === "transformers.js",
)
) {
continueConfig.modelsByRole.embed.push(
new TransformersJsEmbeddingsProvider(),
);
}
if (allowFreeTrial) {
// Obtain auth token (iff free trial being used)
const freeTrialModels = continueConfig.models.filter(
@ -203,8 +268,6 @@ async function configYamlToContinueConfig(
);
}
// TODO: Split into model roles.
// Context providers
const codebaseContextParams: IContextProvider[] =
(config.context || []).find((cp) => cp.provider === "codebase")?.params ||
@ -243,51 +306,6 @@ async function configYamlToContinueConfig(
continueConfig.contextProviders.push(new DocsContextProvider({}));
}
// Embeddings Provider
// IMPORTANT this currently will grab the first model found with an embed role
const embedConfig = config.models?.find((model) =>
model.roles?.includes("embed"),
);
if (embedConfig) {
const { provider, ...options } = embedConfig;
const embeddingsProviderClass = allEmbeddingsProviders[provider];
if (embeddingsProviderClass) {
if (
embeddingsProviderClass.name === "_TransformersJsEmbeddingsProvider"
) {
continueConfig.embeddingsProvider = new embeddingsProviderClass();
} else {
continueConfig.embeddingsProvider = new embeddingsProviderClass(
options,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...options.requestOptions,
}),
);
}
}
}
// Reranker
// IMPORTANT this currently will grab the first model found with a rerank role
const rerankConfig = config.models?.find((model) =>
model.roles?.includes("rerank"),
);
if (rerankConfig) {
const { provider, ...options } = rerankConfig;
const rerankerClass = AllRerankers[provider];
if (rerankerClass) {
continueConfig.reranker = new rerankerClass(
options,
(url: string | URL, init: any) =>
fetchwithRequestOptions(url, init, {
...options.requestOptions,
}),
);
}
}
// Apply MCP if specified
const mcpManager = MCPManagerSingleton.getInstance();
await Promise.all(
@ -341,7 +359,7 @@ export async function loadContinueConfigFromYaml(
ide: IDE,
workspaceConfigs: string[],
ideSettings: IdeSettings,
ideType: IdeType,
ideInfo: IdeInfo,
uniqueId: string,
writeLog: (log: string) => Promise<void>,
workOsAccessToken: string | undefined,
@ -351,7 +369,7 @@ export async function loadContinueConfigFromYaml(
): Promise<ConfigResult<ContinueConfig>> {
const rawYaml =
overrideConfigYaml === undefined
? fs.readFileSync(getConfigYamlPath(ideType), "utf-8")
? fs.readFileSync(getConfigYamlPath(ideInfo.ideType), "utf-8")
: "";
const configYamlResult = await loadConfigYaml(
@ -374,6 +392,7 @@ export async function loadContinueConfigFromYaml(
configYamlResult.config,
ide,
ideSettings,
ideInfo,
uniqueId,
writeLog,
workOsAccessToken,
@ -392,7 +411,7 @@ export async function loadContinueConfigFromYaml(
// Apply shared config
// TODO: override several of these values with user/org shared config
const sharedConfig = new GlobalContext().getSharedConfig();
const withShared = modifyContinueConfigWithSharedConfig(
const withShared = modifyAnyConfigWithSharedConfig(
continueConfig,
sharedConfig,
);

View file

@ -42,10 +42,10 @@ async function getContextProviderExtras(
fullInput,
ide,
config,
embeddingsProvider: config.embeddingsProvider,
embeddingsProvider: config.selectedModelByRole.embed,
fetch: fetch,
llm: config.models[0],
reranker: config.reranker,
reranker: config.selectedModelByRole.rerank,
selectedCode: [],
};
}

View file

@ -7,6 +7,8 @@ import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCod
import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache";
const DEFAULT_CHUNK_SIZE = 384;
export interface RetrievalPipelineOptions {
llm: ILLM;
config: ContinueConfig;
@ -16,13 +18,13 @@ export interface RetrievalPipelineOptions {
nFinal: number;
tags: BranchAndDir[];
filterDirectory?: string;
includeEmbeddings?: boolean; // Used to handle JB w/o an embeddings model
}
export interface RetrievalPipelineRunArguments {
query: string;
tags: BranchAndDir[];
filterDirectory?: string;
includeEmbeddings: boolean;
}
export interface IRetrievalPipeline {
@ -35,7 +37,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
constructor(protected readonly options: RetrievalPipelineOptions) {
this.lanceDbIndex = new LanceDbIndex(
options.config.embeddingsProvider,
options.config.selectedModelByRole.embed,
(uri) => options.ide.readFile(uri),
);
}
@ -109,7 +111,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
filepath,
contents,
maxChunkSize:
this.options.config.embeddingsProvider.maxEmbeddingChunkSize,
this.options.config.selectedModelByRole.embed?.maxEmbeddingChunkSize ?? DEFAULT_CHUNK_SIZE,
digest: filepath,
});

View file

@ -9,7 +9,7 @@ import BaseRetrievalPipeline, {
export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
async run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
const { input, nFinal, filterDirectory, includeEmbeddings } = this.options;
const { input, nFinal, filterDirectory, config } = this.options;
// We give 1/4 weight to recently edited files, 1/4 to full text search,
// and the remaining 1/2 to embeddings
@ -21,7 +21,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
const ftsChunks = await this.retrieveFts(args, ftsNFinal);
const embeddingsChunks = includeEmbeddings
const embeddingsChunks = !!config.selectedModelByRole.embed
? await this.retrieveEmbeddings(input, embeddingsNFinal)
: [];

View file

@ -12,13 +12,12 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
private async _retrieveInitial(
args: RetrievalPipelineRunArguments,
): Promise<Chunk[]> {
const { input, nRetrieve, filterDirectory, includeEmbeddings } =
this.options;
const { input, nRetrieve, filterDirectory, config } = this.options;
let retrievalResults: Chunk[] = [];
const ftsChunks = await this.retrieveFts(args, nRetrieve);
const embeddingsChunks = includeEmbeddings
const embeddingsChunks = !!config.selectedModelByRole.embed
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
const recentlyEditedFilesChunks =
@ -53,17 +52,18 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
}
private async _rerank(input: string, chunks: Chunk[]): Promise<Chunk[]> {
if (!this.options.config.reranker) {
throw new Error("No reranker provided");
if (!this.options.config.selectedModelByRole.rerank) {
throw new Error("No reranker set up");
}
// remove empty chunks -- some APIs fail on that
chunks = chunks.filter((chunk) => chunk.content);
let scores: number[] = await this.options.config.reranker.rerank(
input,
chunks,
);
let scores: number[] =
await this.options.config.selectedModelByRole.rerank.rerank(
input,
chunks,
);
// Filter out low-scoring results
let results = chunks;

View file

@ -2,7 +2,6 @@ import { Chunk, ContinueConfig, IDE, ILLM } from "../..";
import { getModelByRole } from "../../config/util";
import generateRepoMap from "../../util/generateRepoMap";
import { renderChatMessage } from "../../util/messageContent";
import { getUriPathBasename } from "../../util/uri";
const SUPPORTED_MODEL_TITLE_FAMILIES = [
"claude-3",
@ -16,7 +15,7 @@ function isSupportedModel(
config: ContinueConfig,
modelTitle?: string,
): boolean {
if (config.experimental?.modelRoles?.applyCodeBlock) {
if (config.experimental?.modelRoles?.repoMapFileSelection) {
return true;
}

View file

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

View file

@ -14,6 +14,8 @@ import {
setupQuickstartConfig,
} from "./config/onboarding";
import { addContextProvider, addModel, deleteModel } from "./config/util";
import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache";
import { ContinueServerClient } from "./continueServer/stubs/client";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
@ -28,14 +30,14 @@ import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
import { callTool } from "./tools/callTool";
import { ChatDescriber } from "./util/chatDescriber";
import { clipboardCache } from "./util/clipboardCache";
import { logDevData } from "./util/devdata";
import { DevDataSqliteDb } from "./util/devdataSqlite";
import { DataLogger } from "./data/log";
import { DevDataSqliteDb } from "./data/devdataSqlite";
import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
import {
editConfigJson,
getConfigJsonPath,
setupInitialDotContinueDirectory,
migrateV1DevDataFiles,
} from "./util/paths";
import { localPathToUri } from "./util/pathToUri";
import { Telemetry } from "./util/posthog";
@ -51,8 +53,6 @@ import {
type IndexingProgressUpdate,
} from ".";
import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./protocol/messenger";
@ -94,7 +94,7 @@ export class Core {
private readonly onWrite: (text: string) => Promise<void> = async () => {},
) {
// Ensure .continue directory is created
setupInitialDotContinueDirectory();
migrateV1DevDataFiles();
this.codebaseIndexingState = {
status: "loading",
@ -102,6 +102,7 @@ export class Core {
progress: 0,
};
const ideInfoPromise = messenger.request("getIdeInfo", undefined);
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
silent: true,
@ -146,6 +147,12 @@ export class Core {
}),
);
// Dev Data Logger
const dataLogger = DataLogger.getInstance();
dataLogger.core = this;
dataLogger.ideInfoPromise = ideInfoPromise;
dataLogger.ideSettingsPromise = ideSettingsPromise;
// Codebase Indexer and ContinueServerClient depend on IdeSettings
let codebaseIndexerResolve: (_: any) => void | undefined;
this.codebaseIndexerPromise = new Promise(
@ -192,12 +199,10 @@ export class Core {
const getLlm = async () => {
const { config } = await this.configHandler.loadConfig();
const selected = this.globalContext.get("selectedTabAutocompleteModel");
return (
config?.tabAutocompleteModels?.find(
(model) => model.title === selected,
) ?? config?.tabAutocompleteModels?.[0]
);
if (!config) {
return undefined;
}
return config.selectedModelByRole.autocomplete ?? undefined;
};
this.completionProvider = new CompletionProvider(
this.configHandler,
@ -231,11 +236,6 @@ export class Core {
}
});
on("update/selectTabAutocompleteModel", async (msg) => {
this.globalContext.update("selectedTabAutocompleteModel", msg.data);
void this.configHandler.reloadConfig();
});
// Special
on("abort", (msg) => {
this.abortedMessageIds.add(msg.messageId);
@ -266,8 +266,8 @@ export class Core {
});
// Dev data
on("devdata/log", (msg) => {
logDevData(msg.data.tableName, msg.data.data);
on("devdata/log", async (msg) => {
void DataLogger.getInstance().logDevData(msg.data);
});
// Edit config
@ -310,8 +310,19 @@ export class Core {
});
on("config/updateSharedConfig", async (msg) => {
this.globalContext.updateSharedConfig(msg.data);
const newSharedConfig = this.globalContext.updateSharedConfig(msg.data);
await this.configHandler.reloadConfig();
return newSharedConfig;
});
on("config/updateSelectedModel", async (msg) => {
const newSelectedModels = this.globalContext.updateSelectedModel(
msg.data.profileId,
msg.data.role,
msg.data.title,
);
await this.configHandler.reloadConfig();
return newSelectedModels;
});
on("controlPlane/openUrl", async (msg) => {
@ -391,11 +402,11 @@ export class Core {
const items = await provider.getContextItems(query, {
config,
llm,
embeddingsProvider: config.embeddingsProvider,
embeddingsProvider: config.selectedModelByRole.embed,
fullInput,
ide,
selectedCode,
reranker: config.reranker,
reranker: config.selectedModelByRole.rerank,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
});
@ -416,26 +427,25 @@ export class Core {
let knownError = false;
if (e instanceof Error) {
// A specific error where we're forcing the presence of embeddings provider on the config
// But Jetbrains doesn't support transformers JS
// So if a context provider needs it it will throw this error when the file isn't found
if (e.message.includes("all-MiniLM-L6-v2")) {
knownError = true;
const toastOption = "See Docs";
void this.ide
.showToast(
"error",
`Set up an embeddings model to use @${name}`,
toastOption,
)
.then((userSelection) => {
if (userSelection === toastOption) {
void this.ide.openUrl(
"https://docs.continue.dev/customize/model-types/embeddings",
);
}
});
}
// After removing transformers JS embeddings provider from jetbrains
// Should no longer see this error
// if (e.message.toLowerCase().includes("embeddings provider")) {
// knownError = true;
// const toastOption = "See Docs";
// void this.ide
// .showToast(
// "error",
// `Set up an embeddings model to use @${name}`,
// toastOption,
// )
// .then((userSelection) => {
// if (userSelection === toastOption) {
// void this.ide.openUrl(
// "https://docs.continue.dev/customize/model-types/embeddings",
// );
// }
// });
// }
}
if (!knownError) {
void this.ide.showToast(

View file

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

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

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

66
core/index.d.ts vendored
View file

@ -1,4 +1,4 @@
import { ModelRole } from "@continuedev/config-yaml";
import { DataDestination, ModelRole } from "@continuedev/config-yaml";
import Parser from "web-tree-sitter";
import { GetGhTokenArgs } from "./protocol/ide";
declare global {
@ -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;
}
@ -60,7 +60,7 @@ export interface IndexingStatus {
progress: number;
description: string;
status: "indexing" | "complete" | "paused" | "failed" | "aborted" | "pending";
embeddingsProviderId: string;
embeddingsProviderId?: string;
isReindexing?: boolean;
debugInfo?: string;
title: string;
@ -179,8 +179,8 @@ export type FetchFunction = (url: string | URL, init?: any) => Promise<any>;
export interface ContextProviderExtras {
config: ContinueConfig;
fullInput: string;
embeddingsProvider: ILLM;
reranker: ILLM | undefined;
embeddingsProvider: ILLM | null;
reranker: ILLM | null;
llm: ILLM;
ide: IDE;
selectedCode: RangeInFile[];
@ -667,10 +667,10 @@ export interface IDE {
getCurrentFile(): Promise<
| undefined
| {
isUntitled: boolean;
path: string;
contents: string;
}
isUntitled: boolean;
path: string;
contents: string;
}
>;
getLastFileSaveTimestamp?(): number;
@ -853,11 +853,11 @@ export interface CustomCommand {
export interface Prediction {
type: "content";
content:
| string
| {
type: "text";
text: string;
}[];
| string
| {
type: "text";
text: string;
}[];
}
export interface ToolExtras {
@ -1028,9 +1028,9 @@ export interface ContextMenuConfig {
}
export interface ExperimentalModelRoles {
repoMapFileSelection?: string;
inlineEdit?: string;
applyCodeBlock?: string;
repoMapFileSelection?: string;
}
export type EditStatus =
@ -1147,6 +1147,7 @@ export interface SerializedContinueConfig {
experimental?: ExperimentalConfig;
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
data?: DataDestination[];
}
export type ConfigMergeType = "merge" | "overwrite";
@ -1186,9 +1187,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 */
@ -1199,6 +1200,7 @@ export interface Config {
experimental?: ExperimentalConfig;
/** Analytics configuration */
analytics?: AnalyticsConfig;
data?: DataDestination[];
}
// in the actual Continue source code
@ -1213,15 +1215,15 @@ export interface ContinueConfig {
disableSessionTitles?: boolean;
disableIndexing?: boolean;
userToken?: string;
embeddingsProvider: ILLM;
tabAutocompleteModels?: ILLM[];
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
ui?: ContinueUIConfig;
reranker?: ILLM;
experimental?: ExperimentalConfig;
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
tools: Tool[];
modelsByRole: Record<ModelRole, ILLM[]>;
selectedModelByRole: Record<ModelRole, ILLM | null>;
data?: DataDestination[];
}
export interface BrowserSerializedContinueConfig {
@ -1235,15 +1237,15 @@ export interface BrowserSerializedContinueConfig {
disableIndexing?: boolean;
disableSessionTitles?: boolean;
userToken?: string;
embeddingsProvider?: string;
ui?: ContinueUIConfig;
reranker?: RerankerDescription;
experimental?: ExperimentalConfig;
analytics?: AnalyticsConfig;
docs?: SiteIndexingConfig[];
tools: Tool[];
usePlatform: boolean;
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
modelsByRole: Record<ModelRole, ModelDescription[]>;
selectedModelByRole: Record<ModelRole, ModelDescription | null>;
}
// DOCS SUGGESTIONS AND PACKAGE INFO
@ -1279,9 +1281,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;

View file

@ -5,8 +5,8 @@ import { IContinueServerClient } from "../continueServer/interface.js";
import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
@ -80,14 +80,19 @@ export class CodebaseIndexer {
return [];
}
const embeddingsModel = config.selectedModelByRole.embed;
if (!embeddingsModel) {
return [];
}
const indexes = [
new ChunkCodebaseIndex(
this.ide.readFile.bind(this.ide),
this.continueServerClient,
config.embeddingsProvider.maxEmbeddingChunkSize,
embeddingsModel.maxEmbeddingChunkSize,
), // Chunking must come first
new LanceDbIndex(
config.embeddingsProvider,
embeddingsModel,
this.ide.readFile.bind(this.ide),
this.continueServerClient,
),

View file

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

View file

@ -40,11 +40,11 @@ type ChunkMap = Map<string, ItemWithChunks>;
export class LanceDbIndex implements CodebaseIndex {
relativeExpectedTime: number = 13;
get artifactId(): string {
return `vectordb::${this.embeddingsProvider.embeddingId}`;
return `vectordb::${this.embeddingsProvider?.embeddingId}`;
}
constructor(
private readonly embeddingsProvider: ILLM,
private readonly embeddingsProvider: ILLM | null,
private readonly readFile: (filepath: string) => Promise<string>,
private readonly continueServerClient?: IContinueServerClient,
) {}
@ -142,6 +142,9 @@ export class LanceDbIndex implements CodebaseIndex {
item: PathAndCacheKey,
content: string,
): Promise<Chunk[]> {
if (!this.embeddingsProvider) {
return [];
}
const chunks: Chunk[] = [];
const chunkParams = {
@ -163,6 +166,9 @@ export class LanceDbIndex implements CodebaseIndex {
}
private async getEmbeddings(chunks: Chunk[]): Promise<number[][]> {
if (!this.embeddingsProvider) {
return [];
}
try {
return await this.embeddingsProvider.embed(chunks.map((c) => c.content));
} catch (err) {
@ -436,6 +442,9 @@ export class LanceDbIndex implements CodebaseIndex {
tags: BranchAndDir[],
filterDirectory: string | undefined,
): Promise<Chunk[]> {
if (!this.embeddingsProvider) {
return [];
}
const [vector] = await this.embeddingsProvider.embed([query]);
const db = await lance.connect(getLanceDbPath());

View file

@ -1,3 +1,4 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { open, type Database } from "sqlite";
import sqlite3 from "sqlite3";
import lancedb, { Connection } from "vectordb";
@ -19,6 +20,7 @@ import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbed
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol";
import { IMessenger } from "../../protocol/messenger";
import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon";
import { GlobalContext } from "../../util/GlobalContext";
import {
editConfigJson,
getDocsSqlitePath,
@ -26,8 +28,6 @@ import {
} from "../../util/paths";
import { Telemetry } from "../../util/posthog";
import { ConfigResult } from "@continuedev/config-yaml";
import { GlobalContext } from "../../util/GlobalContext";
import {
ArticleWithChunks,
htmlPageToArticleWithChunks,
@ -161,16 +161,22 @@ export default class DocsService {
return;
}
const sharedStatus = {
type: "docs" as IndexingStatus["type"],
const sharedStatus: Omit<
IndexingStatus,
"progress" | "description" | "status"
> = {
type: "docs",
id: doc.startUrl,
embeddingsProviderId: this.config.embeddingsProvider.embeddingId,
isReindexing: false,
title: doc.title,
debugInfo: `max depth: ${doc.maxDepth}`,
icon: doc.faviconUrl,
url: doc.startUrl,
};
if (this.config.selectedModelByRole.embed) {
sharedStatus.embeddingsProviderId =
this.config.selectedModelByRole.embed.embeddingId;
}
const indexedStatus: IndexingStatus = metadata.find(
(meta) => meta.startUrl === doc.startUrl,
)
@ -214,7 +220,9 @@ export default class DocsService {
}
// Handle embeddings provider change mid-indexing
if (this.config.embeddingsProvider.embeddingId !== startedWithEmbedder) {
if (
this.config.selectedModelByRole.embed?.embeddingId !== startedWithEmbedder
) {
this.abort(startUrl);
return true;
}
@ -234,14 +242,6 @@ export default class DocsService {
return true;
}
async isUsingUnsupportedPreIndexedEmbeddingsProvider() {
const isPreIndexedDocsProvider =
this.config.embeddingsProvider.embeddingId ===
DocsService.preIndexedDocsEmbeddingsProvider.embeddingId;
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
return isPreIndexedDocsProvider && !canUsePreindexedDocs;
}
// Determines if using preIndexed and returns proper embeddings provider
async getEmbeddingsProvider(startUrl: string) {
// Conditions for using a pre-indexed doc
@ -262,7 +262,7 @@ export default class DocsService {
}
}
return {
provider: this.config.embeddingsProvider,
provider: this.config.selectedModelByRole.embed,
isPreindexed: false,
};
}
@ -282,9 +282,7 @@ export default class DocsService {
// Skip docs indexing if not supported
// No warning message here because would show on ANY config update
const unsupported =
await this.isUsingUnsupportedPreIndexedEmbeddingsProvider();
if (unsupported) {
if (!this.config.selectedModelByRole.embed) {
return;
}
@ -323,18 +321,21 @@ export default class DocsService {
// Returns true if startUrl has been indexed with current embeddingsProvider
async hasMetadata(startUrl: string): Promise<boolean> {
if (!this.config.selectedModelByRole.embed) {
return false;
}
const db = await this.getOrCreateSqliteDb();
const title = await db.get(
`SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
startUrl,
this.config.embeddingsProvider.embeddingId,
this.config.selectedModelByRole.embed.embeddingId,
);
return !!title;
}
async listMetadata() {
const embeddingsProvider = this.config.embeddingsProvider;
const embeddingsProvider = this.config.selectedModelByRole.embed;
if (!embeddingsProvider) {
return [];
}
@ -376,6 +377,11 @@ export default class DocsService {
console.warn("Attempted to indexAndAdd pre-indexed doc");
return;
}
if (!provider) {
console.warn("@docs indexAndAdd: no embeddings provider found");
return;
}
const startedWithEmbedder = provider.embeddingId;
// Check if doc has been successfully indexed with the given embedder
@ -716,21 +722,18 @@ export default class DocsService {
startUrl: string,
nRetrieve: number,
) {
if (await this.isUsingUnsupportedPreIndexedEmbeddingsProvider()) {
await this.ide.showToast(
"error",
`${DocsService.preIndexedDocsEmbeddingsProvider.embeddingId} is configured as ` +
"the embeddings provider, but it cannot be used with JetBrains. " + // TODO "with this IDE"
"Please select a different embeddings provider to use the '@docs' " +
"context provider.",
);
return [];
}
const { isPreindexed, provider } =
await this.getEmbeddingsProvider(startUrl);
if (!provider) {
void this.ide.showToast(
"error",
"Set up an embeddings model to use the @docs context provider. See: " +
"https://docs.continue.dev/customize/model-types/embeddings",
);
return [];
}
if (isPreindexed) {
void Telemetry.capture("docs_pre_indexed_doc_used", {
doc: preIndexedDocs[startUrl]!["title"],
@ -761,8 +764,10 @@ export default class DocsService {
try {
const { isPreindexed, provider } =
await this.getEmbeddingsProvider(startUrl);
const preIndexedDoc = preIndexedDocs[startUrl];
const isPreIndexedDoc = !!preIndexedDoc;
if (!provider) {
throw new Error("No embeddings model set");
}
const result = await db.get(
`SELECT startUrl, title, favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
@ -793,7 +798,7 @@ export default class DocsService {
config: siteIndexingConfig,
indexingStatus: this.statuses.get(startUrl),
chunks: rows.map(this.lanceDBRowToChunk),
isPreIndexedDoc,
isPreIndexedDoc: isPreindexed,
};
} catch (e) {
console.warn("Error getting details", e);
@ -867,7 +872,7 @@ export default class DocsService {
}
async getFavicon(startUrl: string) {
if (!this.config.embeddingsProvider) {
if (!this.config.selectedModelByRole.embed) {
console.warn(
"Attempting to get favicon without embeddings provider specified",
);
@ -877,7 +882,7 @@ export default class DocsService {
const result = await db.get(
`SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
startUrl,
this.config.embeddingsProvider.embeddingId,
this.config.selectedModelByRole.embed.embeddingId,
);
if (!result) {
@ -941,7 +946,7 @@ export default class DocsService {
type: "docs",
id: doc.startUrl,
embeddingsProviderId:
this.config.embeddingsProvider.embeddingId,
this.config.selectedModelByRole.embed?.embeddingId,
isReindexing: false,
title: doc.title,
debugInfo: "Config sync: not changed",
@ -1033,6 +1038,13 @@ export default class DocsService {
const conn = await lancedb.connect(getLanceDbPath());
const tableNames = await conn.tableNames();
const { provider } = await this.getEmbeddingsProvider(startUrl);
if (!provider) {
throw new Error(
"Could not retrieve @docs Lance Table: no embeddings provider specified",
);
}
const tableNameFromEmbeddingsProvider =
await this.getLanceTableName(provider);
@ -1089,13 +1101,19 @@ export default class DocsService {
siteIndexingConfig: { title, startUrl },
favicon,
}: AddParams) {
if (!this.config.selectedModelByRole.embed) {
console.warn(
`Attempting to add metadata for ${startUrl} without embeddings provider specified`,
);
return;
}
const db = await this.getOrCreateSqliteDb();
await db.run(
`INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon, embeddingsProviderId) VALUES (?, ?, ?, ?)`,
title,
startUrl,
favicon,
this.config.embeddingsProvider.embeddingId,
this.config.selectedModelByRole.embed.embeddingId,
);
}
@ -1147,7 +1165,7 @@ export default class DocsService {
}
private async deleteMetadataFromSqlite(startUrl: string) {
if (!this.config.embeddingsProvider) {
if (!this.config.selectedModelByRole.embed) {
console.warn(
`Attempting to delete metadata for ${startUrl} without embeddings provider specified`,
);
@ -1158,7 +1176,7 @@ export default class DocsService {
await db.run(
`DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
startUrl,
this.config.embeddingsProvider.embeddingId,
this.config.selectedModelByRole.embed.embeddingId,
);
}

View file

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

View file

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

View file

@ -1,3 +1,4 @@
import { ModelRole } from "@continuedev/config-yaml";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import { findLlmInfo } from "@continuedev/llm-info";
import {
@ -7,6 +8,8 @@ import {
} from "@continuedev/openai-adapters";
import Handlebars from "handlebars";
import { DevDataSqliteDb } from "../data/devdataSqlite.js";
import { DataLogger } from "../data/log.js";
import {
CacheBehavior,
ChatMessage,
@ -21,8 +24,6 @@ import {
RequestOptions,
TemplateType,
} from "../index.js";
import { logDevData } from "../util/devdata.js";
import { DevDataSqliteDb } from "../util/devdataSqlite.js";
import mergeJson from "../util/merge.js";
import { renderChatMessage } from "../util/messageContent.js";
import { isOllamaInstalled } from "../util/ollamaHelper.js";
@ -56,7 +57,6 @@ import {
toCompleteBody,
toFimBody,
} from "./openaiTypeConverters.js";
import { ModelRole } from "@continuedev/config-yaml";
export abstract class BaseLLM implements ILLM {
static providerName: string;
@ -288,7 +288,7 @@ export abstract class BaseLLM implements ILLM {
return this.templateMessages(msgs);
}
private _compileLogMessage(
private _compilePromptForLog(
prompt: string,
completionOptions: CompletionOptions,
): string {
@ -343,11 +343,14 @@ export abstract class BaseLLM implements ILLM {
generatedTokens,
);
logDevData("tokens_generated", {
model: model,
provider: this.providerName,
promptTokens: promptTokens,
generatedTokens: generatedTokens,
void DataLogger.getInstance().logDevData({
name: "tokensGenerated",
data: {
model: model,
provider: this.providerName,
promptTokens: promptTokens,
generatedTokens: generatedTokens,
},
});
}
@ -447,7 +450,7 @@ export abstract class BaseLLM implements ILLM {
options,
);
return { completionOptions, log, raw };
return { completionOptions, logEnabled: log, raw };
}
private _formatChatMessages(messages: ChatMessage[]): string {
@ -500,12 +503,15 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
): AsyncGenerator<string> {
const { completionOptions, log } = this._parseCompletionOptions(options);
const { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
const fimLog = `Prefix: ${prefix}\nSuffix: ${suffix}`;
if (log) {
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(fimLog, completionOptions));
await this.writeLog(
this._compilePromptForLog(fimLog, completionOptions),
);
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, fimLog);
@ -541,7 +547,7 @@ export abstract class BaseLLM implements ILLM {
this._logTokensGenerated(completionOptions.model, fimLog, completion);
if (log && this.writeLog) {
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
}
@ -557,7 +563,7 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
) {
const { completionOptions, log, raw } =
const { completionOptions, logEnabled, raw } =
this._parseCompletionOptions(options);
let prompt = pruneRawPromptFromTop(
@ -571,9 +577,11 @@ export abstract class BaseLLM implements ILLM {
prompt = this._templatePromptLikeMessages(prompt);
}
if (log) {
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(prompt, completionOptions));
await this.writeLog(
this._compilePromptForLog(prompt, completionOptions),
);
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
@ -618,7 +626,7 @@ export abstract class BaseLLM implements ILLM {
} finally {
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
}
}
@ -636,7 +644,7 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
) {
const { completionOptions, log, raw } =
const { completionOptions, logEnabled, raw } =
this._parseCompletionOptions(options);
let prompt = pruneRawPromptFromTop(
@ -650,9 +658,11 @@ export abstract class BaseLLM implements ILLM {
prompt = this._templatePromptLikeMessages(prompt);
}
if (log) {
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(prompt, completionOptions));
await this.writeLog(
this._compilePromptForLog(prompt, completionOptions),
);
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
@ -675,7 +685,7 @@ export abstract class BaseLLM implements ILLM {
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
}
@ -719,7 +729,8 @@ export abstract class BaseLLM implements ILLM {
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
): AsyncGenerator<ChatMessage, PromptLog> {
let { completionOptions, log } = this._parseCompletionOptions(options);
let { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
completionOptions = this._modifyCompletionOptions(completionOptions);
@ -728,9 +739,11 @@ export abstract class BaseLLM implements ILLM {
const prompt = this.templateMessages
? this.templateMessages(messages)
: this._formatChatMessages(messages);
if (log) {
if (logEnabled) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(prompt, completionOptions));
await this.writeLog(
this._compilePromptForLog(prompt, completionOptions),
);
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
@ -797,7 +810,7 @@ export abstract class BaseLLM implements ILLM {
this._logTokensGenerated(completionOptions.model, prompt, completion);
if (log && this.writeLog) {
if (logEnabled && this.writeLog) {
await this.writeLog(`Completion:\n${completion}\n\n`);
}

View file

@ -43,6 +43,7 @@ export class TransformersJsEmbeddingsProvider extends BaseLLM {
static maxGroupSize: number = 1;
static model: string = "all-MiniLM-L6-v2";
static mockVector: number[] = Array.from({ length: 384 }).fill(2) as number[];
static title: string = "Transformers.js (Built-In)";
static defaultOptions: Partial<LLMOptions> | undefined = {
model: TransformersJsEmbeddingsProvider.model,

View file

@ -445,7 +445,7 @@ class VertexAI extends BaseLLM {
}
const resp = await this.fetch(
new URL(this.apiBase + `/publishers/google/models/${this.model}:predict`),
new URL(`publishers/google/models/${this.model}:predict`, this.apiBase),
{
method: "POST",
body: JSON.stringify({

3479
core/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -46,7 +46,7 @@
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "^1.0.31",
"@continuedev/config-yaml": "^1.0.38",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/openai-adapters": "^1.0.10",

View file

@ -19,12 +19,12 @@ export function getContextProviderHelpers(
async (helperContext: any) => {
const items = await provider.getContextItems(helperContext, {
config: context.config,
embeddingsProvider: context.config.embeddingsProvider,
embeddingsProvider: context.config.selectedModelByRole.embed,
fetch: context.fetch,
fullInput: context.input,
ide: context.ide,
llm: context.llm,
reranker: context.config.reranker,
reranker: context.config.selectedModelByRole.rerank,
selectedCode: context.selectedCode,
});

View file

@ -1,4 +1,4 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { ConfigResult, ModelRole } from "@continuedev/config-yaml";
import { AutocompleteInput } from "../autocomplete/util/types";
import { ProfileDescription } from "../config/ConfigHandler";
@ -27,6 +27,8 @@ import type {
SiteIndexingConfig,
ToolCall,
} from "../";
import { DevDataLogEvent } from "../../packages/config-yaml/src/schemas/data";
import { GlobalContextModelSelections } from "../util/GlobalContext";
export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart";
@ -36,8 +38,6 @@ export interface ListHistoryOptions {
}
export type ToCoreFromIdeOrWebviewProtocol = {
"update/selectTabAutocompleteModel": [string, void];
// Special
ping: [string, string];
abort: [undefined, void];
@ -47,7 +47,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"history/delete": [{ id: string }, void];
"history/load": [{ id: string }, Session];
"history/save": [Session, void];
"devdata/log": [{ tableName: string; data: any }, void];
"devdata/log": [DevDataLogEvent, void];
"config/addOpenAiKey": [string, void];
"config/addModel": [
{
@ -70,7 +70,15 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"config/reload": [undefined, ConfigResult<BrowserSerializedContinueConfig>];
"config/listProfiles": [undefined, ProfileDescription[] | null];
"config/openProfile": [{ profileId: string | undefined }, void];
"config/updateSharedConfig": [SharedConfigSchema, void];
"config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema];
"config/updateSelectedModel": [
{
profileId: string;
role: ModelRole;
title: string | null;
},
GlobalContextModelSelections,
];
"context/getContextItems": [
{
name: string;

View file

@ -49,11 +49,11 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
acceptDiff: [{ filepath: string; streamId?: string }, void];
rejectDiff: [{ filepath: string; streamId?: string }, void];
"edit/sendPrompt": [
{ prompt: MessageContent; range: RangeInFileWithContents },
void,
];
"edit/acceptReject": [
{ accept: boolean; onlyFirst: boolean; filepath: string },
{
prompt: MessageContent;
range: RangeInFileWithContents;
selectedModelTitle: string;
},
void,
];
"edit/exit": [{ shouldFocusEditor: boolean }, void];

View file

@ -24,6 +24,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"config/listProfiles",
"config/openProfile",
"config/updateSharedConfig",
"config/updateSelectedModel",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",

View file

@ -29,12 +29,6 @@ describe("GlobalContext", () => {
expect(value).toBe(true);
});
it("should update and get a string value correctly", () => {
globalContext.update("selectedTabAutocompleteModel", "test-model");
const value = globalContext.get("selectedTabAutocompleteModel");
expect(value).toBe("test-model");
});
it("should update and get an object value correctly", () => {
const workspaceIdentifier = "workspace-1";
globalContext.update("lastSelectedProfileForWorkspace", {
@ -108,13 +102,9 @@ describe("GlobalContext", () => {
it("should update and retrieve multiple values correctly", () => {
globalContext.update("indexingPaused", true);
globalContext.update("selectedTabAutocompleteModel", "test-model");
globalContext.update("hasDismissedConfigTsNoticeJetBrains", false);
expect(globalContext.get("indexingPaused")).toBe(true);
expect(globalContext.get("selectedTabAutocompleteModel")).toBe(
"test-model",
);
expect(globalContext.get("hasDismissedConfigTsNoticeJetBrains")).toBe(
false,
);

View file

@ -1,5 +1,8 @@
import fs from "node:fs";
import { ModelRole } from "@continuedev/config-yaml";
import { SiteIndexingConfig } from "..";
import {
salvageSharedConfig,
sharedConfigSchema,
@ -7,17 +10,22 @@ import {
} from "../config/sharedConfig";
import { getGlobalContextFilePath } from "./paths";
import { SiteIndexingConfig } from "..";
export type GlobalContextModelSelections = Partial<
Record<ModelRole, string | null>
>;
export type GlobalContextType = {
indexingPaused: boolean;
selectedTabAutocompleteModel: string;
lastSelectedProfileForWorkspace: {
[workspaceIdentifier: string]: string | null;
};
lastSelectedOrgIdForWorkspace: {
[workspaceIdentifier: string]: string | null;
};
selectedModelsByProfileId: {
[profileId: string]: GlobalContextModelSelections;
};
/**
* This is needed to handle the case where a JetBrains user has created
@ -113,4 +121,23 @@ export class GlobalContext {
this.update("sharedConfig", updatedSharedConfig);
return updatedSharedConfig;
}
updateSelectedModel(
profileId: string,
role: ModelRole,
title: string | null,
): GlobalContextModelSelections {
const currentSelections = this.get("selectedModelsByProfileId") ?? {};
const forProfile = currentSelections[profileId] ?? {};
const newSelections = {
...forProfile,
[role]: title,
};
this.update("selectedModelsByProfileId", {
...currentSelections,
[profileId]: newSelections,
});
return newSelections;
}
}

View file

@ -1,9 +0,0 @@
import fs from "fs";
import { getDevDataFilePath } from "./paths.js";
export function logDevData(tableName: string, data: any) {
const filepath: string = getDevDataFilePath(tableName);
const jsonLine = JSON.stringify(data);
fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
}

View file

@ -8,6 +8,7 @@ import dotenv from "dotenv";
import { IdeType, SerializedContinueConfig } from "../";
import { defaultConfig, defaultConfigJetBrains } from "../config/default";
import Types from "../config/types";
import { DevEventName } from "../../packages/config-yaml/src/schemas/data";
dotenv.config();
@ -202,7 +203,7 @@ export function getContinueRcPath(): string {
return continuercPath;
}
export function devDataPath(): string {
function getDevDataPath(): string {
const sPath = path.join(getContinueGlobalPath(), "dev_data");
if (!fs.existsSync(sPath)) {
fs.mkdirSync(sPath);
@ -211,11 +212,18 @@ export function devDataPath(): string {
}
export function getDevDataSqlitePath(): string {
return path.join(devDataPath(), "devdata.sqlite");
return path.join(getDevDataPath(), "devdata.sqlite");
}
export function getDevDataFilePath(fileName: string): string {
return path.join(devDataPath(), `${fileName}.jsonl`);
export function getDevDataFilePath(
eventName: DevEventName,
schema: string,
): string {
const versionPath = path.join(getDevDataPath(), schema);
if (!fs.existsSync(versionPath)) {
fs.mkdirSync(versionPath);
}
return path.join(versionPath, `${String(eventName)}.jsonl`);
}
export function editConfigJson(
@ -377,23 +385,33 @@ export function getEsbuildBinaryPath(): string {
return path.join(getContinueUtilsPath(), "esbuild");
}
export function getStagingEnvironmentDotFilePath(): string {
return path.join(getContinueGlobalPath(), ".staging");
export function migrateV1DevDataFiles() {
const devDataPath = getDevDataPath();
function moveToV1FolderIfExists(
oldFileName: string,
newFileName: DevEventName,
) {
const oldFilePath = path.join(devDataPath, `${oldFileName}.jsonl`);
if (fs.existsSync(oldFilePath)) {
const newFilePath = getDevDataFilePath(newFileName, "0.1.0");
if (!fs.existsSync(newFilePath)) {
fs.copyFileSync(oldFilePath, newFilePath);
fs.unlinkSync(oldFilePath);
} else {
console.warn(
`V1 Dev data migration: ${newFilePath} already exists, skipping ${oldFileName}`,
);
}
}
}
moveToV1FolderIfExists("tokens_generated", "tokensGenerated");
moveToV1FolderIfExists("chat", "chatFeedback");
moveToV1FolderIfExists("quickEdit", "quickEdit");
moveToV1FolderIfExists("autocomplete", "autocomplete");
}
export function setupInitialDotContinueDirectory() {
const devDataTypes = [
"chat",
"autocomplete",
"quickEdit",
"tokens_generated",
];
devDataTypes.forEach((p) => {
const devDataPath = getDevDataFilePath(p);
if (!fs.existsSync(devDataPath)) {
fs.writeFileSync(devDataPath, "");
}
});
export function getStagingEnvironmentDotFilePath(): string {
return path.join(getContinueGlobalPath(), ".staging");
}
export function getDiffsDirectoryPath(): string {

View file

@ -93,6 +93,7 @@ export const supportedLanguages: { [key: string]: LanguageName } = {
htm: LanguageName.HTML,
java: LanguageName.JAVA,
lua: LanguageName.LUA,
luau: LanguageName.LUA,
ocaml: LanguageName.OCAML,
ml: LanguageName.OCAML,
mli: LanguageName.OCAML,

View file

@ -143,7 +143,7 @@ models:
- apply
```
Note that the `repoMapFileSelection` experimental model role has been deprecated.
Note that the `repoMapFileSelection` experimental model role has been deprecated and is only available in `config.json`.
### Context Providers

View file

@ -91,6 +91,7 @@ class MessageTypes {
"config/listProfiles",
"config/openProfile",
"config/updateSharedConfig",
"config/updateSelectedModel",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",

View file

@ -447,7 +447,8 @@ class IdeProtocolClient(
val result = responseContent["result"] as Map<*, *>
val config = result["config"] as Map<String, Any>
val applyCodeBlockModel = getModelByRole(config, "applyCodeBlock")
val selectedModels = config["selectedModelByRole"] as Map<String, Any>
val applyCodeBlockModel = selectedModels["apply"] as Map<String, Any>
if (applyCodeBlockModel != null) {
continuation.resume(applyCodeBlockModel)
@ -588,19 +589,4 @@ class IdeProtocolClient(
fun deleteAtIndex(index: Int) {
continuePluginService.sendToWebview("deleteAtIndex", DeleteAtIndex(index), uuid())
}
private fun getModelByRole(
config: Any,
role: Any
): Any? {
val experimental = (config as? Map<*, *>)?.get("experimental") as? Map<*, *>
val roleTitle = (experimental?.get("modelRoles") as? Map<*, *>)?.get(role) as? String ?: return null
val models = (config as? Map<*, *>)?.get("models") as? List<*>
val matchingModel = models?.find { model ->
(model as? Map<*, *>)?.get("title") == roleTitle
}
return matchingModel
}
}

View file

@ -192,10 +192,12 @@ class VerticalDiffBlock(
private fun revertDiff() {
WriteCommandAction.runWriteCommandAction(project) {
// Delete the added lines
val startOffset = editor.document.getLineStartOffset(startLine)
val endOffset = editor.document.getLineEndOffset(startLine + addedLines.size - 1) + 1
editor.document.deleteString(startOffset, endOffset)
// Delete the added lines
if (addedLines.isNotEmpty()) {
val endOffset = editor.document.getLineEndOffset(startLine + addedLines.size - 1) + 1
editor.document.deleteString(startOffset, endOffset)
}
// Add the deleted lines back
if (deletedLines.isNotEmpty()) {

View file

@ -106,7 +106,7 @@
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "^1.0.31",
"@continuedev/config-yaml": "^1.0.35",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/openai-adapters": "^1.0.10",

View file

@ -504,21 +504,11 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
async function copyScripts() {
process.chdir(path.join(continueDir, "extensions", "vscode"));
console.log("[info] Copying scripts from core");
await new Promise((resolve, reject) => {
ncp(
path.join(__dirname, "../../../core/scripts"),
path.join(__dirname, "../out"),
{ dereference: true },
(error) => {
if (error) {
console.warn("[error] Error copying script files", error);
reject(error);
} else {
resolve();
}
},
);
});
fs.copyFileSync(
path.join(__dirname, "../../../core/util/start_ollama.sh"),
path.join(__dirname, "../out/start_ollama.sh"),
);
console.log("[info] Copied script files");
}
module.exports = {

View file

@ -21,7 +21,6 @@ import {
stopStatusBarLoading,
} from "./statusBar";
import type { TabAutocompleteModel } from "../util/loadAutocompleteModel";
import { startLocalOllama } from "core/util/ollamaHelper";
import type { IDE } from "core";
@ -41,7 +40,8 @@ interface VsCodeCompletionInput {
}
export class ContinueCompletionProvider
implements vscode.InlineCompletionItemProvider {
implements vscode.InlineCompletionItemProvider
{
private onError(e: any) {
let options = ["Documentation"];
if (e.message.includes("Ollama may not be installed")) {
@ -82,13 +82,19 @@ export class ContinueCompletionProvider
constructor(
private readonly configHandler: ConfigHandler,
private readonly ide: IDE,
private readonly tabAutocompleteModel: TabAutocompleteModel,
private readonly webviewProtocol: VsCodeWebviewProtocol,
) {
async function getAutocompleteModel() {
const { config } = await configHandler.loadConfig();
if (!config) {
return;
}
return config.selectedModelByRole.autocomplete ?? undefined;
}
this.completionProvider = new CompletionProvider(
this.configHandler,
this.ide,
this.tabAutocompleteModel.get.bind(this.tabAutocompleteModel),
getAutocompleteModel,
this.onError.bind(this),
getDefinitionsFromLsp,
);

View file

@ -4,7 +4,6 @@ import * as os from "node:os";
import { ContextMenuConfig, RangeInFileWithContents } from "core";
import { CompletionProvider } from "core/autocomplete/CompletionProvider";
import { ConfigHandler } from "core/config/ConfigHandler";
import { getModelByRole } from "core/config/util";
import { ContinueServerClient } from "core/continueServer/stubs/client";
import { EXTENSION_NAME } from "core/control-plane/env";
import { Core } from "core/core";
@ -30,11 +29,12 @@ import { VerticalDiffManager } from "./diff/vertical/manager";
import EditDecorationManager from "./quickEdit/EditDecorationManager";
import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick";
import { Battery } from "./util/battery";
import { VsCodeIde } from "./VsCodeIde";
import { getMetaKeyLabel } from "./util/util";
import { VsCodeIde } from "./VsCodeIde";
import type { VsCodeWebviewProtocol } from "./webviewProtocol";
import { LOCAL_DEV_DATA_VERSION } from "core/data/log";
import { startLocalOllama } from "core/util/ollamaHelper";
import type { VsCodeWebviewProtocol } from "./webviewProtocol";
let fullScreenPanel: vscode.WebviewPanel | undefined;
@ -348,7 +348,7 @@ const getCommandsMap: (
);
const modelTitle =
getModelByRole(config, "inlineEdit")?.title ?? defaultModelTitle;
config.selectedModelByRole.edit?.title ?? defaultModelTitle;
void sidebar.webviewProtocol.request("incrementFtc", undefined);
@ -872,16 +872,12 @@ const getCommandsMap: (
const config = vscode.workspace.getConfiguration(EXTENSION_NAME);
const quickPick = vscode.window.createQuickPick();
const autocompleteModels =
(await configHandler.loadConfig()).config?.tabAutocompleteModels ?? [];
let selected = new GlobalContext().get("selectedTabAutocompleteModel");
if (
!selected ||
!autocompleteModels.some((model) => model.title === selected)
) {
selected = autocompleteModels[0]?.title;
}
const { config: continueConfig } = await configHandler.loadConfig();
const autocompleteModels =
continueConfig?.modelsByRole.autocomplete ?? [];
const selected =
continueConfig?.selectedModelByRole?.autocomplete?.title ?? undefined;
// Toggle between Disabled, Paused, and Enabled
const pauseOnBattery =
@ -956,11 +952,14 @@ const getCommandsMap: (
} else if (
autocompleteModels.some((model) => model.title === selectedOption)
) {
new GlobalContext().update(
"selectedTabAutocompleteModel",
selectedOption,
);
configHandler.reloadConfig();
if (core.configHandler.currentProfile?.profileDescription.id) {
core.invoke("config/updateSelectedModel", {
profileId:
core.configHandler.currentProfile?.profileDescription.id,
role: "autocomplete",
title: selectedOption,
});
}
} else if (selectedOption === "$(feedback) Give feedback") {
vscode.commands.executeCommand("continue.giveAutocompleteFeedback");
} else if (selectedOption === "$(comment) Open chat (Cmd+L)") {
@ -986,7 +985,10 @@ const getCommandsMap: (
});
if (feedback) {
const client = await continueServerClientPromise;
const completionsPath = getDevDataFilePath("autocomplete");
const completionsPath = getDevDataFilePath(
"autocomplete",
LOCAL_DEV_DATA_VERSION,
);
const lastLines = await readLastLines.read(completionsPath, 2);
client.sendFeedback(feedback, lastLines);

View file

@ -34,7 +34,6 @@ import {
} from "../stubs/WorkOsAuthProvider";
import { Battery } from "../util/battery";
import { FileSearch } from "../util/FileSearch";
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
import { VsCodeIde } from "../VsCodeIde";
import { VsCodeMessenger } from "./VsCodeMessenger";
@ -47,7 +46,6 @@ export class VsCodeExtension {
private configHandler: ConfigHandler;
private extensionContext: vscode.ExtensionContext;
private ide: VsCodeIde;
private tabAutocompleteModel: TabAutocompleteModel;
private sidebar: ContinueGUIWebviewViewProvider;
private windowId: string;
private editDecorationManager: EditDecorationManager;
@ -143,7 +141,6 @@ export class VsCodeExtension {
this.editDecorationManager,
);
resolveVerticalDiffManager?.(this.verticalDiffManager);
this.tabAutocompleteModel = new TabAutocompleteModel(this.configHandler);
setupRemoteConfigSync(
this.configHandler.reloadConfig.bind(this.configHandler),
@ -168,8 +165,6 @@ export class VsCodeExtension {
} else if (newConfig) {
setupStatusBar(undefined, undefined, false);
this.tabAutocompleteModel.clearLlm();
registerAllCodeLensProviders(
context,
this.verticalDiffManager.fileUriToCodeLens,
@ -193,7 +188,6 @@ export class VsCodeExtension {
new ContinueCompletionProvider(
this.configHandler,
this.ide,
this.tabAutocompleteModel,
this.sidebar.webviewProtocol,
),
),
@ -347,7 +341,8 @@ export class VsCodeExtension {
// Register a content provider for the readonly virtual documents
const documentContentProvider = new (class
implements vscode.TextDocumentContentProvider {
implements vscode.TextDocumentContentProvider
{
// emitter and its event
onDidChangeEmitter = new vscode.EventEmitter<vscode.Uri>();
onDidChange = this.onDidChangeEmitter.event;

View file

@ -28,6 +28,7 @@ import { showTutorial } from "../util/tutorial";
import { getExtensionUri } from "../util/vscode";
import { VsCodeIde } from "../VsCodeIde";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
import { ILLM } from "core";
/**
* A shared messenger class between Core and Webview
@ -177,7 +178,7 @@ export class VsCodeMessenger {
return;
}
let llm = getModelByRole(config, "applyCodeBlock");
let llm: ILLM | null | undefined = config.selectedModelByRole.apply;
if (!llm) {
llm = config.models.find(
@ -286,13 +287,10 @@ export class VsCodeMessenger {
const prompt = msg.data.prompt;
const { start, end } = msg.data.range.range;
const verticalDiffManager = await verticalDiffManagerPromise;
const modelTitle = await this.webviewProtocol.request(
"getDefaultModelTitle",
undefined,
);
const fileAfterEdit = await verticalDiffManager.streamEdit(
stripImages(prompt),
modelTitle,
msg.data.selectedModelTitle,
"edit",
undefined,
undefined,
@ -307,30 +305,6 @@ export class VsCodeMessenger {
fileAfterEdit,
});
});
this.onWebview("edit/acceptReject", async (msg) => {
const { onlyFirst, accept, filepath } = msg.data;
if (accept && onlyFirst) {
// Accept first
vscode.commands.executeCommand(
"continue.acceptVerticalDiffBlock",
filepath,
0,
);
} else if (accept) {
vscode.commands.executeCommand("continue.acceptDiff", filepath);
// Accept all
} else if (onlyFirst) {
// Reject first
vscode.commands.executeCommand(
"continue.rejectVerticalDiffBlock",
filepath,
0,
);
} else {
// Reject all
vscode.commands.executeCommand("continue.rejectDiff", filepath);
}
});
this.onWebview("edit/exit", async (msg) => {
if (msg.data.shouldFocusEditor) {
const activeEditor = vscode.window.activeTextEditor;

View file

@ -41,8 +41,8 @@ export async function getContextProvidersString(
return provider.getContextItems("", {
config,
ide,
embeddingsProvider: config.embeddingsProvider,
reranker: config.reranker,
embeddingsProvider: config.selectedModelByRole.embed,
reranker: config.selectedModelByRole.rerank,
llm: config.models[0],
fullInput: "",
selectedCode: [],

View file

@ -1,8 +1,6 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { IDE } from "core";
import { ConfigHandler } from "core/config/ConfigHandler";
import { getModelByRole } from "core/config/util";
import { logDevData } from "core/util/devdata";
import { Telemetry } from "core/util/posthog";
import * as vscode from "vscode";
@ -10,6 +8,7 @@ import { VerticalDiffManager } from "../diff/vertical/manager";
import { FileSearch } from "../util/FileSearch";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
import { DataLogger } from "core/data/log";
import { getContextProviderQuickPickVal } from "./ContextProvidersQuickPick";
import { appendToHistory, getHistoryQuickPickVal } from "./HistoryQuickPick";
import { getModelQuickPickVal } from "./ModelSelectionQuickPick";
@ -226,13 +225,18 @@ export class QuickEdit {
break;
}
let model = await this.getCurModelTitle();
logDevData("quickEdit", {
prompt,
path,
label,
diffs: this.verticalDiffManager.logDiffs,
model,
void DataLogger.getInstance().logDevData({
name: "quickEdit",
data: {
prompt,
path,
label,
diffs: this.verticalDiffManager.logDiffs,
model,
},
});
quickPick.dispose();
});
}
@ -273,7 +277,7 @@ export class QuickEdit {
}
return (
getModelByRole(config, "inlineEdit")?.title ??
config.selectedModelByRole.edit?.title ??
(await this.webviewProtocol.request(
"getDefaultModelTitle",
undefined,

View file

@ -1,65 +0,0 @@
import { ConfigHandler } from "core/config/ConfigHandler";
import Ollama from "core/llm/llms/Ollama";
import { GlobalContext } from "core/util/GlobalContext";
import type { ILLM } from "core";
export class TabAutocompleteModel {
private _llm: ILLM | undefined;
private defaultTag = "qwen2.5-coder:1.5b";
private globalContext: GlobalContext = new GlobalContext();
constructor(private configHandler: ConfigHandler) {}
clearLlm() {
this._llm = undefined;
}
async getDefaultTabAutocompleteModel() {
const llm = new Ollama({
model: this.defaultTag,
});
try {
const models = await llm.listModels();
if (!models.includes(this.defaultTag)) {
return undefined;
}
} catch (e) {
return undefined;
}
return llm;
}
async get() {
if (!this._llm) {
const { config } = await this.configHandler.loadConfig();
if (!config) {
return undefined;
}
if (config.tabAutocompleteModels?.length) {
const selected = this.globalContext.get("selectedTabAutocompleteModel");
if (selected) {
this._llm =
config.tabAutocompleteModels?.find(
(model) => model.title === selected,
) ?? config.tabAutocompleteModels?.[0];
} else {
if (config.tabAutocompleteModels[0].title) {
this.globalContext.update(
"selectedTabAutocompleteModel",
config.tabAutocompleteModels[0].title,
);
}
this._llm = config.tabAutocompleteModels[0];
}
} else {
this._llm = await this.getDefaultTabAutocompleteModel();
}
}
return this._llm;
}
}

5018
gui/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -15,7 +15,7 @@
"test:watch": "vitest"
},
"dependencies": {
"@continuedev/config-yaml": "^1.0.31",
"@continuedev/config-yaml": "^1.0.38",
"@headlessui/react": "^1.7.17",
"@heroicons/react": "^2.0.18",
"@reduxjs/toolkit": "^2.3.0",

View file

@ -294,9 +294,7 @@ const Layout = () => {
onClick={() => navigate(ROUTES.CONFIG_ERROR)}
>
<strong className="font-bold">Error!</strong>{" "}
<span className="block sm:inline">
Could not load config.json
</span>
<span className="block sm:inline">Could not load config</span>
<div className="mt-2 underline">Learn More</div>
</div>
)}

View file

@ -22,8 +22,12 @@ export default function FeedbackButtons({ item }: FeedbackButtonsProps) {
if (item.promptLogs?.length) {
for (const promptLog of item.promptLogs) {
ideMessenger.post("devdata/log", {
tableName: "chat",
data: { ...promptLog, feedback, sessionId },
name: "chatFeedback",
data: {
...promptLog,
feedback,
sessionId,
},
});
}
}

View file

@ -110,7 +110,6 @@ function AddDocsDialog() {
type: "docs",
description: "Initializing",
id: startUrl,
embeddingsProviderId: "mock-embeddings-provider-id",
progress: 0,
status: "indexing",
title,
@ -164,7 +163,6 @@ function AddDocsDialog() {
type: "docs",
description: "Initializing",
id: docsResult.details.docsLink,
embeddingsProviderId: "mock-embeddings-provider-id",
progress: 0,
status: "indexing",
title: docsResult.details.title ?? docsResult.packageInfo.name,

View file

@ -13,10 +13,10 @@ const ToggleSwitch: React.FC<ToggleSwitchProps> = ({
}) => {
return (
<div className="flex cursor-pointer select-none items-center justify-between gap-3">
<span className="truncate-right text-right">{text}</span>
<span className="truncate-right">{text}</span>
<div>
<div
className={`border-vsc-input-border bg-vsc-input-background flex h-5 w-10 items-center rounded-full border border-solid p-0.5`}
className={`border-vsc-input-border bg-vsc-input-background flex h-4 w-8 items-center rounded-full border border-solid p-0.5`}
onClick={onToggle}
>
<div className="relative h-full w-full">

View file

@ -37,6 +37,7 @@ export const handleJetBrainsOSRMetaKeyIssues = (
if (e.key in handlers) {
e.stopPropagation();
debugger;
e.preventDefault();
handlers[e.key]();
}

View file

@ -21,7 +21,8 @@ export function AssistantSelectOptions({
onClose,
}: AssistantSelectOptionsProps) {
const ideMessenger = useContext(IdeMessengerContext);
const { profiles, selectedProfile, selectedOrganization } = useAuth();
const { profiles, selectedProfile, selectedOrganization, session, login } =
useAuth();
const dispatch = useAppDispatch();
const navigate = useNavigate();
@ -85,7 +86,10 @@ export function AssistantSelectOptions({
</div>
<div className="mt-auto w-full">
<OptionDiv key={profiles.length} onClick={onNewAssistant}>
<OptionDiv
key={"new-assistant"}
onClick={session ? onNewAssistant : () => login(true)}
>
<div
className="flex items-center py-0.5"
style={{ fontSize: getFontSize() - 2 }}

View file

@ -1,7 +1,6 @@
import { XCircleIcon } from "@heroicons/react/24/outline";
import { IndexingProgressUpdate } from "core";
import { useAppSelector } from "../../../redux/hooks";
import { isJetBrains } from "../../../util";
export interface IndexingProgressErrorTextProps {
update: IndexingProgressUpdate;
@ -9,20 +8,16 @@ export interface IndexingProgressErrorTextProps {
function IndexingProgressErrorText({ update }: IndexingProgressErrorTextProps) {
const embeddingsProvider = useAppSelector(
(state) => state.config.config.embeddingsProvider,
(state) => state.config.config.selectedModelByRole.embed,
);
const showJbError =
(isJetBrains() && embeddingsProvider === "all-MiniLM-L6-v2") || true;
if (showJbError) {
if (!embeddingsProvider) {
return (
<div className="flex items-center gap-2 italic">
<XCircleIcon className="h-4 w-4 min-w-[10%]" />
<span className="leading-relaxed">
The <code>transformers.js</code> embeddingsProvider is currently
unsupported in JetBrains. To enable codebase indexing, you can use any
of the other providers described in the docs:{" "}
Add an Embeddings model to enable codebase indexing. See the docs for
examples:
<a
href="https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers"
target="_blank"

View file

@ -0,0 +1,95 @@
import { Fragment } from "react";
import { Listbox, Transition } from "@headlessui/react";
import {
ChevronUpDownIcon,
InformationCircleIcon,
} from "@heroicons/react/24/outline";
import { type ModelDescription } from "core";
import { ToolTip } from "../../components/gui/Tooltip";
interface ModelRoleSelectorProps {
models: ModelDescription[];
selectedModel: ModelDescription | null;
onSelect: (model: ModelDescription | null) => void;
displayName: string;
description: string;
}
const ModelRoleSelector = ({
models,
selectedModel,
onSelect,
displayName,
description,
}: ModelRoleSelectorProps) => {
function handleSelect(title: string | null) {
onSelect(models.find((m) => m.title === title) ?? null);
}
return (
<>
<div className="mt-2 flex flex-row items-center gap-1 sm:mt-0">
<span className="text-sm">{displayName}</span>
<InformationCircleIcon
className="h-3 w-3"
data-tooltip-id={`${displayName}-description`}
/>
<ToolTip id={`${displayName}-description`} place={"bottom"}>
{description}
</ToolTip>
</div>
<Listbox value={selectedModel?.title ?? null} onChange={handleSelect}>
{({ open }) => (
<div className="relative">
<Listbox.Button
className={`border-vsc-input-border bg-vsc-background ${!!models.length ? "hover:bg-vsc-input-background cursor-pointer" : ""} text-vsc-foreground relative m-0 flex w-full items-center justify-between rounded-md border border-solid px-2 py-1 text-left`}
>
{models.length === 0 ? (
<span className="text-lightgray italic">{`No ${displayName} models${["Chat", "Apply", "Edit"].includes(displayName) ? ". Using chat model" : ""}`}</span>
) : (
<span className="lines lines-1">
{selectedModel?.title ?? `Select ${displayName} model`}
</span>
)}
{models.length ? (
<div className="pointer-events-none flex items-center">
<ChevronUpDownIcon
className="h-3.5 w-3.5"
aria-hidden="true"
/>
</div>
) : null}
</Listbox.Button>
<Transition
as={Fragment}
show={open}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<Listbox.Options className="bg-vsc-background max-h-80vh absolute z-[800] mt-0.5 w-full overflow-y-scroll rounded-sm p-0">
{models.map((option, idx) => (
<Listbox.Option
key={idx}
value={option.title}
className={`text-vsc-foreground hover:text-list-active-foreground flex cursor-pointer flex-row items-center gap-3 px-2 py-1 ${option?.title === selectedModel?.title ? "bg-list-active" : "bg-vsc-input-background"}`}
>
<span className="lines lines-1 relative flex h-5 items-center justify-between gap-3 pr-2 text-xs">
{option.title}
</span>
</Listbox.Option>
))}
</Listbox.Options>
</Transition>
</div>
)}
</Listbox>
</>
);
};
export default ModelRoleSelector;

View file

@ -1,322 +0,0 @@
import { useContext, useEffect, useState } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline";
import {
SharedConfigSchema,
modifyContinueConfigWithSharedConfig,
} from "core/config/sharedConfig";
import { Input } from "../../components";
import NumberInput from "../../components/gui/NumberInput";
import { Select } from "../../components/gui/Select";
import ToggleSwitch from "../../components/gui/Switch";
import { updateConfig } from "../../redux/slices/configSlice";
import { getFontSize } from "../../util";
function UserSettingsUI() {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const config = useAppSelector((state) => state.config.config);
function handleUpdate(sharedConfig: Partial<SharedConfigSchema>) {
dispatch(
updateConfig(modifyContinueConfigWithSharedConfig(config, sharedConfig)),
);
ideMessenger.post("config/updateSharedConfig", sharedConfig);
}
// TODO defaults are in multiple places, should be consolidated and probably not explicit here
const codeWrap = config.ui?.codeWrap ?? false;
const showChatScrollbar = config.ui?.showChatScrollbar ?? false;
const displayRawMarkdown = config.ui?.displayRawMarkdown ?? false;
const disableSessionTitles = config.disableSessionTitles ?? false;
const readResponseTTS = config.experimental?.readResponseTTS ?? false;
const allowAnonymousTelemetry = config.allowAnonymousTelemetry ?? true;
const disableIndexing = config.disableIndexing ?? false;
const useAutocompleteCache = config.tabAutocompleteOptions?.useCache ?? false;
const useChromiumForDocsCrawling =
config.experimental?.useChromiumForDocsCrawling ?? false;
const codeBlockToolbarPosition = config.ui?.codeBlockToolbarPosition ?? "top";
const useAutocompleteMultilineCompletions =
config.tabAutocompleteOptions?.multilineCompletions ?? "auto";
const fontSize = getFontSize();
// Disable autocomplete
const disableAutocompleteInFiles = (
config.tabAutocompleteOptions?.disableInFiles ?? []
).join(", ");
const [formDisableAutocomplete, setFormDisableAutocomplete] = useState(
disableAutocompleteInFiles,
);
const cancelChangeDisableAutocomplete = () => {
setFormDisableAutocomplete(disableAutocompleteInFiles);
};
const handleDisableAutocompleteSubmit = () => {
handleUpdate({
disableAutocompleteInFiles: formDisableAutocomplete
.split(",")
.map((val) => val.trim())
.filter((val) => !!val),
});
};
useEffect(() => {
// Necessary so that reformatted/trimmed values don't cause dirty state
setFormDisableAutocomplete(disableAutocompleteInFiles);
}, [disableAutocompleteInFiles]);
// Workspace prompts
const promptPath = config.experimental?.promptPath || "";
const [formPromptPath, setFormPromptPath] = useState(promptPath);
const cancelChangePromptPath = () => {
setFormPromptPath(promptPath);
};
const handleSubmitPromptPath = () => {
handleUpdate({
promptPath: formPromptPath || "",
});
};
useEffect(() => {
// Necessary so that reformatted/trimmed values don't cause dirty state
setFormPromptPath(promptPath);
}, [promptPath]);
return (
<div className="flex flex-col gap-4 py-6">
<div>
<h2 className="mb-2 mt-0">User settings</h2>
</div>
<div className="flex flex-col gap-4">
<ToggleSwitch
isToggled={codeWrap}
onToggle={() =>
handleUpdate({
codeWrap: !codeWrap,
})
}
text="Wrap Codeblocks"
/>
<ToggleSwitch
isToggled={displayRawMarkdown}
onToggle={() =>
handleUpdate({
displayRawMarkdown: !displayRawMarkdown,
})
}
text="Display Raw Markdown"
/>
<ToggleSwitch
isToggled={allowAnonymousTelemetry}
onToggle={() =>
handleUpdate({
allowAnonymousTelemetry: !allowAnonymousTelemetry,
})
}
text="Allow Anonymous Telemetry"
/>
<ToggleSwitch
isToggled={disableIndexing}
onToggle={() =>
handleUpdate({
disableIndexing: !disableIndexing,
})
}
text="Disable Indexing"
/>
<ToggleSwitch
isToggled={disableSessionTitles}
onToggle={() =>
handleUpdate({
disableSessionTitles: !disableSessionTitles,
})
}
text="Disable Session Titles"
/>
<ToggleSwitch
isToggled={readResponseTTS}
onToggle={() =>
handleUpdate({
readResponseTTS: !readResponseTTS,
})
}
text="Response Text to Speech"
/>
<ToggleSwitch
isToggled={showChatScrollbar}
onToggle={() =>
handleUpdate({
showChatScrollbar: !showChatScrollbar,
})
}
text="Show Chat Scrollbar"
/>
<ToggleSwitch
isToggled={useAutocompleteCache}
onToggle={() =>
handleUpdate({
useAutocompleteCache: !useAutocompleteCache,
})
}
text="Use Autocomplete Cache"
/>
<ToggleSwitch
isToggled={useChromiumForDocsCrawling}
onToggle={() =>
handleUpdate({
useChromiumForDocsCrawling: !useChromiumForDocsCrawling,
})
}
text="Use Chromium for Docs Crawling"
/>
<label className="flex items-center justify-between gap-3">
<span className="text-right">Codeblock Actions Position</span>
<Select
value={codeBlockToolbarPosition}
onChange={(e) =>
handleUpdate({
codeBlockToolbarPosition: e.target.value as "top" | "bottom",
})
}
>
<option value="top">Top</option>
<option value="bottom">Bottom</option>
</Select>
</label>
<label className="flex items-center justify-between gap-3">
<span className="text-right">Multiline Autocompletions</span>
<Select
value={useAutocompleteMultilineCompletions}
onChange={(e) =>
handleUpdate({
useAutocompleteMultilineCompletions: e.target.value as
| "auto"
| "always"
| "never",
})
}
>
<option value="auto">Auto</option>
<option value="always">Always</option>
<option value="never">Never</option>
</Select>
</label>
<label className="flex items-center justify-between gap-3">
<span className="text-right">Font Size</span>
<NumberInput
value={fontSize}
onChange={(val) =>
handleUpdate({
fontSize: val,
})
}
min={7}
max={50}
/>
</label>
<form
className="flex flex-col gap-1"
onSubmit={(e) => {
e.preventDefault();
handleSubmitPromptPath();
}}
>
<div className="flex items-center justify-between">
<span>Workspace prompts path</span>
<div className="flex items-center gap-2">
<Input
value={formPromptPath}
className="max-w-[100px]"
onChange={(e) => {
setFormPromptPath(e.target.value);
}}
/>
<div className="flex h-full flex-col">
{formPromptPath !== promptPath ? (
<>
<div
onClick={handleSubmitPromptPath}
className="cursor-pointer"
>
<CheckIcon className="h-4 w-4 text-green-500 hover:opacity-80" />
</div>
<div
onClick={cancelChangePromptPath}
className="cursor-pointer"
>
<XMarkIcon className="h-4 w-4 text-red-500 hover:opacity-80" />
</div>
</>
) : (
<div>
<CheckIcon className="text-vsc-foreground-muted h-4 w-4" />
</div>
)}
</div>
</div>
</div>
</form>
<form
className="flex flex-col gap-1"
onSubmit={(e) => {
e.preventDefault();
handleDisableAutocompleteSubmit();
}}
>
<div className="flex items-center justify-between">
<span>Disable autocomplete in files</span>
<div className="flex items-center gap-2">
<Input
value={formDisableAutocomplete}
className="max-w-[100px]"
onChange={(e) => {
setFormDisableAutocomplete(e.target.value);
}}
/>
<div className="flex h-full flex-col">
{formDisableAutocomplete !== disableAutocompleteInFiles ? (
<>
<div
onClick={handleDisableAutocompleteSubmit}
className="cursor-pointer"
>
<CheckIcon className="h-4 w-4 text-green-500 hover:opacity-80" />
</div>
<div
onClick={cancelChangeDisableAutocomplete}
className="cursor-pointer"
>
<XMarkIcon className="h-4 w-4 text-red-500 hover:opacity-80" />
</div>
</>
) : (
<div>
<CheckIcon className="text-vsc-foreground-muted h-4 w-4" />
</div>
)}
</div>
</div>
</div>
<span className="text-vsc-foreground-muted self-end text-xs">
Comma-separated list of path matchers
</span>
</form>
</div>
</div>
);
}
export default UserSettingsUI;

View file

@ -1,16 +1,32 @@
import { ModelRole } from "@continuedev/config-yaml";
import { Listbox, Transition } from "@headlessui/react";
import { ChevronUpDownIcon, PlusCircleIcon } from "@heroicons/react/24/outline";
import {
CheckIcon,
ChevronUpDownIcon,
PlusCircleIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { ModelDescription } from "core";
import {
SharedConfigSchema,
modifyAnyConfigWithSharedConfig,
} from "core/config/sharedConfig";
import { Fragment, useContext, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { SecondaryButton } from "../../components";
import { Input, SecondaryButton } from "../../components";
import NumberInput from "../../components/gui/NumberInput";
import { Select } from "../../components/gui/Select";
import ToggleSwitch from "../../components/gui/Switch";
import PageHeader from "../../components/PageHeader";
import { useAuth } from "../../context/Auth";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useNavigationListener } from "../../hooks/useNavigationListener";
import { useAppDispatch } from "../../redux/hooks";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { setDefaultModel, updateConfig } from "../../redux/slices/configSlice";
import { selectProfileThunk } from "../../redux/thunks/profileAndOrg";
import { getFontSize, isJetBrains } from "../../util";
import ModelRoleSelector from "./ModelRoleSelector";
import { ScopeSelect } from "./ScopeSelect";
import UserSettingsUI from "./UserSettings";
function ConfigPage() {
useNavigationListener();
@ -52,6 +68,113 @@ function ConfigPage() {
// NOTE Hub takes priority over Continue for Teams
// Since teams will be moving to hub, not vice versa
/////// User settings section //////
const config = useAppSelector((state) => state.config.config);
const selectedChatModel = useAppSelector(
(store) => store.config.defaultModelTitle,
);
function handleUpdate(sharedConfig: SharedConfigSchema) {
// Optimistic update
const updatedConfig = modifyAnyConfigWithSharedConfig(config, sharedConfig);
dispatch(updateConfig(updatedConfig));
// IMPORTANT no need for model role updates (separate logic for selected model roles)
// simply because this function won't be used to update model roles
// Actual update to core which propagates back with config update event
ideMessenger.post("config/updateSharedConfig", sharedConfig);
}
function handleRoleUpdate(role: ModelRole, model: ModelDescription | null) {
if (!selectedProfile) {
return;
}
// Optimistic update
dispatch(
updateConfig({
...config,
selectedModelByRole: {
...config.selectedModelByRole,
[role]: model,
},
}),
);
ideMessenger.post("config/updateSelectedModel", {
profileId: selectedProfile.id,
role,
title: model?.title ?? null,
});
}
// TODO use handleRoleUpdate for chat
function handleChatModelSelection(model: ModelDescription | null) {
if (!model) {
return;
}
dispatch(setDefaultModel({ title: model.title }));
}
// TODO defaults are in multiple places, should be consolidated and probably not explicit here
const codeWrap = config.ui?.codeWrap ?? false;
const showChatScrollbar = config.ui?.showChatScrollbar ?? false;
const displayRawMarkdown = config.ui?.displayRawMarkdown ?? false;
const disableSessionTitles = config.disableSessionTitles ?? false;
const readResponseTTS = config.experimental?.readResponseTTS ?? false;
const allowAnonymousTelemetry = config.allowAnonymousTelemetry ?? true;
const disableIndexing = config.disableIndexing ?? false;
const useAutocompleteCache = config.tabAutocompleteOptions?.useCache ?? false;
const useChromiumForDocsCrawling =
config.experimental?.useChromiumForDocsCrawling ?? false;
const codeBlockToolbarPosition = config.ui?.codeBlockToolbarPosition ?? "top";
const useAutocompleteMultilineCompletions =
config.tabAutocompleteOptions?.multilineCompletions ?? "auto";
const fontSize = getFontSize();
// Disable autocomplete
const disableAutocompleteInFiles = (
config.tabAutocompleteOptions?.disableInFiles ?? []
).join(", ");
const [formDisableAutocomplete, setFormDisableAutocomplete] = useState(
disableAutocompleteInFiles,
);
const cancelChangeDisableAutocomplete = () => {
setFormDisableAutocomplete(disableAutocompleteInFiles);
};
const handleDisableAutocompleteSubmit = () => {
handleUpdate({
disableAutocompleteInFiles: formDisableAutocomplete
.split(",")
.map((val) => val.trim())
.filter((val) => !!val),
});
};
useEffect(() => {
// Necessary so that reformatted/trimmed values don't cause dirty state
setFormDisableAutocomplete(disableAutocompleteInFiles);
}, [disableAutocompleteInFiles]);
// Workspace prompts
const promptPath = config.experimental?.promptPath || "";
const [formPromptPath, setFormPromptPath] = useState(promptPath);
const cancelChangePromptPath = () => {
setFormPromptPath(promptPath);
};
const handleSubmitPromptPath = () => {
handleUpdate({
promptPath: formPromptPath || "",
});
};
useEffect(() => {
// Necessary so that reformatted/trimmed values don't cause dirty state
setFormPromptPath(promptPath);
}, [promptPath]);
const jetbrains = isJetBrains();
return (
<div className="overflow-y-scroll">
<PageHeader onTitleClick={() => navigate("/")} title="Chat" />
@ -143,10 +266,14 @@ function ConfigPage() {
value={null}
className={`text-vsc-foreground hover:bg-list-active bg-vsc-input-background flex cursor-pointer flex-row items-center gap-2 px-3 py-2`}
onClick={() => {
ideMessenger.post("controlPlane/openUrl", {
path: "new",
orgSlug: selectedOrganization?.slug,
});
if (session) {
ideMessenger.post("controlPlane/openUrl", {
path: "new",
orgSlug: selectedOrganization?.slug,
});
} else {
login(true);
}
}}
>
<PlusCircleIcon className="h-4 w-4" />
@ -173,12 +300,301 @@ function ConfigPage() {
) : (
<div>Loading...</div>
)}
<div>
<h2 className="m-0 mb-3 p-0 text-center text-sm">
Active Models
</h2>
<div className="grid grid-cols-1 gap-x-3 gap-y-2 sm:grid-cols-[auto_1fr]">
<ModelRoleSelector
displayName="Chat"
description="Used in the chat interface"
models={config.modelsByRole.chat}
selectedModel={{
title: selectedChatModel,
provider: "mock",
model: "mock",
}}
onSelect={(model) => handleChatModelSelection(model)}
/>
<ModelRoleSelector
displayName="Autocomplete"
description="Used to generate code completion suggestions"
models={config.modelsByRole.autocomplete}
selectedModel={config.selectedModelByRole.autocomplete}
onSelect={(model) => handleRoleUpdate("autocomplete", model)}
/>
{/* Jetbrains has a model selector inline */}
{!jetbrains && (
<ModelRoleSelector
displayName="Edit"
description="Used for inline edits"
models={config.modelsByRole.edit}
selectedModel={config.selectedModelByRole.edit}
onSelect={(model) => handleRoleUpdate("edit", model)}
/>
)}
<ModelRoleSelector
displayName="Apply"
description="Used to apply generated codeblocks to files"
models={config.modelsByRole.apply}
selectedModel={config.selectedModelByRole.apply}
onSelect={(model) => handleRoleUpdate("apply", model)}
/>
<ModelRoleSelector
displayName="Embed"
description="Used to generate and query embeddings for the @codebase and @docs context providers"
models={config.modelsByRole.embed}
selectedModel={config.selectedModelByRole.embed}
onSelect={(model) => handleRoleUpdate("embed", model)}
/>
<ModelRoleSelector
displayName="Rerank"
description="Used for reranking results from the @codebase and @docs context providers"
models={config.modelsByRole.rerank}
selectedModel={config.selectedModelByRole.rerank}
onSelect={(model) => handleRoleUpdate("rerank", model)}
/>
</div>
</div>
</div>
</div>
{!controlServerBetaEnabled || hubEnabled ? (
<div className="flex flex-col">
<div className="flex max-w-[400px] flex-col">
<UserSettingsUI />
<div className="flex flex-col gap-4 py-6">
<div>
<h2 className="mb-2 mt-0">User settings</h2>
</div>
<div className="flex flex-col gap-4">
<ToggleSwitch
isToggled={codeWrap}
onToggle={() =>
handleUpdate({
codeWrap: !codeWrap,
})
}
text="Wrap Codeblocks"
/>
<ToggleSwitch
isToggled={displayRawMarkdown}
onToggle={() =>
handleUpdate({
displayRawMarkdown: !displayRawMarkdown,
})
}
text="Display Raw Markdown"
/>
<ToggleSwitch
isToggled={allowAnonymousTelemetry}
onToggle={() =>
handleUpdate({
allowAnonymousTelemetry: !allowAnonymousTelemetry,
})
}
text="Allow Anonymous Telemetry"
/>
<ToggleSwitch
isToggled={disableIndexing}
onToggle={() =>
handleUpdate({
disableIndexing: !disableIndexing,
})
}
text="Disable Indexing"
/>
<ToggleSwitch
isToggled={disableSessionTitles}
onToggle={() =>
handleUpdate({
disableSessionTitles: !disableSessionTitles,
})
}
text="Disable Session Titles"
/>
<ToggleSwitch
isToggled={readResponseTTS}
onToggle={() =>
handleUpdate({
readResponseTTS: !readResponseTTS,
})
}
text="Response Text to Speech"
/>
<ToggleSwitch
isToggled={showChatScrollbar}
onToggle={() =>
handleUpdate({
showChatScrollbar: !showChatScrollbar,
})
}
text="Show Chat Scrollbar"
/>
<ToggleSwitch
isToggled={useAutocompleteCache}
onToggle={() =>
handleUpdate({
useAutocompleteCache: !useAutocompleteCache,
})
}
text="Use Autocomplete Cache"
/>
<ToggleSwitch
isToggled={useChromiumForDocsCrawling}
onToggle={() =>
handleUpdate({
useChromiumForDocsCrawling: !useChromiumForDocsCrawling,
})
}
text="Use Chromium for Docs Crawling"
/>
<label className="flex items-center justify-between gap-3">
<span className="lines lines-1 text-left">
Codeblock Actions Position
</span>
<Select
value={codeBlockToolbarPosition}
onChange={(e) =>
handleUpdate({
codeBlockToolbarPosition: e.target.value as
| "top"
| "bottom",
})
}
>
<option value="top">Top</option>
<option value="bottom">Bottom</option>
</Select>
</label>
<label className="flex items-center justify-between gap-3">
<span className="lines lines-1 text-left">
Multiline Autocompletions
</span>
<Select
value={useAutocompleteMultilineCompletions}
onChange={(e) =>
handleUpdate({
useAutocompleteMultilineCompletions: e.target
.value as "auto" | "always" | "never",
})
}
>
<option value="auto">Auto</option>
<option value="always">Always</option>
<option value="never">Never</option>
</Select>
</label>
<label className="flex items-center justify-between gap-3">
<span className="text-left">Font Size</span>
<NumberInput
value={fontSize}
onChange={(val) =>
handleUpdate({
fontSize: val,
})
}
min={7}
max={50}
/>
</label>
<form
className="flex flex-col gap-1"
onSubmit={(e) => {
e.preventDefault();
handleSubmitPromptPath();
}}
>
<div className="flex items-center justify-between gap-1">
<span>Workspace prompts path</span>
<div className="flex items-center gap-2">
<Input
value={formPromptPath}
className="max-w-[100px]"
onChange={(e) => {
setFormPromptPath(e.target.value);
}}
/>
<div className="flex h-full flex-col">
{formPromptPath !== promptPath ? (
<>
<div
onClick={handleSubmitPromptPath}
className="cursor-pointer"
>
<CheckIcon className="h-4 w-4 text-green-500 hover:opacity-80" />
</div>
<div
onClick={cancelChangePromptPath}
className="cursor-pointer"
>
<XMarkIcon className="h-4 w-4 text-red-500 hover:opacity-80" />
</div>
</>
) : (
<div>
<CheckIcon className="text-vsc-foreground-muted h-4 w-4" />
</div>
)}
</div>
</div>
</div>
</form>
<form
className="flex flex-col gap-1"
onSubmit={(e) => {
e.preventDefault();
handleDisableAutocompleteSubmit();
}}
>
<div className="flex items-center justify-between">
<span>Disable autocomplete in files</span>
<div className="flex items-center gap-2">
<Input
value={formDisableAutocomplete}
className="max-w-[100px]"
onChange={(e) => {
setFormDisableAutocomplete(e.target.value);
}}
/>
<div className="flex h-full flex-col">
{formDisableAutocomplete !==
disableAutocompleteInFiles ? (
<>
<div
onClick={handleDisableAutocompleteSubmit}
className="cursor-pointer"
>
<CheckIcon className="h-4 w-4 text-green-500 hover:opacity-80" />
</div>
<div
onClick={cancelChangeDisableAutocomplete}
className="cursor-pointer"
>
<XMarkIcon className="h-4 w-4 text-red-500 hover:opacity-80" />
</div>
</>
) : (
<div>
<CheckIcon className="text-vsc-foreground-muted h-4 w-4" />
</div>
)}
</div>
</div>
</div>
<span className="text-vsc-foreground-muted text-lightgray self-end text-xs">
Comma-separated list of path matchers
</span>
</form>
</div>
</div>
</div>
</div>
) : null}

View file

@ -338,6 +338,7 @@ export function Chat() {
ideMessenger.post("edit/sendPrompt", {
prompt,
range: codeToEdit[0] as RangeInFileWithContents,
selectedModelTitle,
});
dispatch(submitEdit(prompt));

View file

@ -27,6 +27,24 @@ const initialState: ConfigState = {
models: [],
tools: [],
usePlatform: true,
modelsByRole: {
chat: [],
apply: [],
edit: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
apply: null,
edit: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
},
};

View file

@ -61,6 +61,34 @@ export const streamNormalInput = createAsyncThunk<
// Attach prompt log
if (next.done && next.value) {
dispatch(addPromptCompletionPair([next.value]));
try {
if (state.session.mode === "chat") {
extra.ideMessenger.post("devdata/log", {
name: "chatInteraction",
data: {
prompt: next.value.prompt,
completion: next.value.completion,
modelProvider: defaultModel.provider,
modelTitle: defaultModel.title,
sessionId: state.session.id,
},
});
}
// else if (state.session.mode === "edit") {
// extra.ideMessenger.post("devdata/log", {
// name: "editInteraction",
// data: {
// prompt: next.value.prompt,
// completion: next.value.completion,
// modelProvider: defaultModel.provider,
// modelTitle: defaultModel.title,
// },
// });
// }
} catch (e) {
console.error("Failed to send dev data interaction log", e);
}
}
// If it's a tool call that is automatically accepted, we should call it

View file

@ -43,7 +43,7 @@ export const streamResponseAfterToolCall = createAsyncThunk<
content: renderContextItems(toolOutput),
toolCallId,
};
debugger;
dispatch(streamUpdate([newMessage]));
dispatch(
addContextItemsAtIndex({

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/config-yaml",
"version": "1.0.35",
"version": "1.0.38",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
@ -12,12 +12,14 @@
"author": "Continue Dev, Inc.",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
"zod": "^3.23.8",
"@continuedev/config-types": "^1.0.14"
"zod": "^3.23.8"
},
"devDependencies": {
"@types/jest": "^29.5.14",
"cross-env": "^7.0.3",
"jest": "^29.7.0",
"ts-jest": "^29.2.3",
"ts-node": "^10.9.2"
}

View file

@ -7,6 +7,7 @@ export * from "./load/getBlockType.js";
export * from "./load/merge.js";
export * from "./load/proxySecretResolution.js";
export * from "./load/unroll.js";
export * from "./schemas/data/index.js";
export * from "./schemas/index.js";
export type { ModelConfig, ModelRole } from "./schemas/models.js";
export * from "./validation.js";

View file

@ -0,0 +1,42 @@
import { z } from "zod";
import { completionOptionsSchema } from "../../models.js";
import { baseDevDataAllSchema } from "../base.js";
export const autocompleteEventAllSchema = baseDevDataAllSchema.extend({
// Tab autocomplete options - TODO - old json version?
disable: z.boolean(),
useFileSuffix: z.boolean(),
maxPromptTokens: z.number(),
debounceDelay: z.number(),
maxSuffixPercentage: z.number(),
prefixPercentage: z.number(),
transform: z.boolean().optional(),
template: z.string().optional(),
multilineCompletions: z.enum(["always", "never", "auto"]),
slidingWindowPrefixPercentage: z.number(),
slidingWindowSize: z.number(),
useCache: z.boolean(),
onlyMyCode: z.boolean(),
useRecentlyEdited: z.boolean(),
useImports: z.boolean().optional(),
// Other
accepted: z.boolean().optional(),
time: z.number(),
prefix: z.string(),
suffix: z.string(),
prompt: z.string(),
completion: z.string(),
modelProvider: z.string(),
modelName: z.string(),
cacheHit: z.boolean(),
filepath: z.string(),
gitRepo: z.string().optional(),
completionId: z.string(),
uniqueId: z.string(),
timestamp: z.number(),
// DEPRECATED - no more nested objects after v0.1.0, all flat values
completionOptions: completionOptionsSchema.optional(),
disableInFiles: z.array(z.string()).optional(),
});

View file

@ -0,0 +1,43 @@
import { autocompleteEventAllSchema } from "./index.js";
export const autocompleteEventSchema_0_1_0 = autocompleteEventAllSchema.pick({
disable: true,
useFileSuffix: true,
maxPromptTokens: true,
debounceDelay: true,
maxSuffixPercentage: true,
prefixPercentage: true,
transform: true,
template: true,
multilineCompletions: true,
slidingWindowPrefixPercentage: true,
slidingWindowSize: true,
useCache: true,
onlyMyCode: true,
useRecentlyEdited: true,
disableInFiles: true,
useImports: true,
accepted: true,
time: true,
prefix: true,
suffix: true,
prompt: true,
completion: true,
modelProvider: true,
modelName: true,
completionOptions: true,
cacheHit: true,
filepath: true,
gitRepo: true,
completionId: true,
uniqueId: true,
timestamp: true,
});
export const autocompleteEventSchema_0_1_0_noCode =
autocompleteEventSchema_0_1_0.omit({
prefix: true,
suffix: true,
prompt: true,
completion: true,
});

View file

@ -0,0 +1,50 @@
import { autocompleteEventAllSchema } from "./index.js";
export const autocompleteEventSchema_0_2_0 = autocompleteEventAllSchema.pick({
// base
timestamp: true,
userId: true,
userAgent: true,
selectedProfileId: true,
eventName: true,
schema: true,
// autocomplete-specific
disable: true,
maxPromptTokens: true,
debounceDelay: true,
maxSuffixPercentage: true,
prefixPercentage: true,
transform: true,
template: true,
multilineCompletions: true,
slidingWindowPrefixPercentage: true,
slidingWindowSize: true,
useCache: true,
onlyMyCode: true,
useRecentlyEdited: true,
useImports: true,
accepted: true,
time: true,
prefix: true,
suffix: true,
prompt: true,
completion: true,
modelProvider: true,
modelName: true,
cacheHit: true,
filepath: true,
gitRepo: true,
completionId: true,
uniqueId: true,
// Note objects (completionOptions and disableInfiles) removed from 0.1.0 => 0.2.0
});
export const autocompleteEventSchema_0_2_0_noCode =
autocompleteEventSchema_0_2_0.omit({
prefix: true,
suffix: true,
prompt: true,
completion: true,
});

View file

@ -0,0 +1,11 @@
import { z } from "zod";
export const baseDevDataAllSchema = z.object({
eventName: z.string(),
schema: z.string(),
timestamp: z.string().datetime(),
userId: z.string(),
userAgent: z.string(),
selectedProfileId: z.string(),
// gitCommitHash: z.string(),
});

View file

@ -0,0 +1,11 @@
import { z } from "zod";
import { baseDevDataAllSchema } from "../base.js";
export const chatFeedbackEventAllSchema = baseDevDataAllSchema.extend({
modelTitle: z.string(),
completionOptions: z.object({}),
prompt: z.string(),
completion: z.string(),
feedback: z.boolean().optional(),
sessionId: z.string().uuid(),
});

View file

@ -0,0 +1,16 @@
import { chatFeedbackEventAllSchema } from "./index.js";
export const chatFeedbackEventSchema_0_1_0 = chatFeedbackEventAllSchema.pick({
modelTitle: true,
completionOptions: true,
prompt: true,
completion: true,
feedback: true,
sessionId: true,
});
export const chatFeedbackEventSchema_0_1_0_noCode =
chatFeedbackEventSchema_0_1_0.omit({
prompt: true,
completion: true,
});

View file

@ -0,0 +1,24 @@
import { chatFeedbackEventAllSchema } from "./index.js";
export const chatFeedbackEventSchema_0_2_0 = chatFeedbackEventAllSchema.pick({
// base
timestamp: true,
userId: true,
userAgent: true,
selectedProfileId: true,
eventName: true,
schema: true,
// other
prompt: true,
completion: true,
modelTitle: true,
feedback: true,
sessionId: true,
});
export const chatFeedbackEventSchema_0_2_0_noCode =
chatFeedbackEventSchema_0_2_0.omit({
prompt: true,
completion: true,
});

View file

@ -0,0 +1,10 @@
import { z } from "zod";
import { baseDevDataAllSchema } from "../base.js";
export const chatInteractionEventAllSchema = baseDevDataAllSchema.extend({
modelProvider: z.string(),
modelTitle: z.string(),
prompt: z.string(),
completion: z.string(),
sessionId: z.string(),
});

View file

@ -0,0 +1,25 @@
import { chatInteractionEventAllSchema } from "./index.js";
export const chatInteractionEventSchema_0_2_0 =
chatInteractionEventAllSchema.pick({
// base
timestamp: true,
userId: true,
userAgent: true,
selectedProfileId: true,
eventName: true,
schema: true,
// other
prompt: true,
completion: true,
modelTitle: true,
modelProvider: true,
sessionId: true,
});
export const chatInteractionEventSchema_0_2_0_noCode =
chatInteractionEventSchema_0_2_0.omit({
prompt: true,
completion: true,
});

View file

@ -0,0 +1,9 @@
import { z } from "zod";
import { baseDevDataAllSchema } from "../base.js";
export const editInteractionEventAllSchema = baseDevDataAllSchema.extend({
modelProvider: z.string(),
modelTitle: z.string(),
prompt: z.string(),
completion: z.string(),
});

View file

@ -0,0 +1,24 @@
import { editInteractionEventAllSchema } from "./index.js";
export const editInteractionEventSchema_0_2_0 =
editInteractionEventAllSchema.pick({
// base
timestamp: true,
userId: true,
userAgent: true,
selectedProfileId: true,
eventName: true,
schema: true,
// other
prompt: true,
completion: true,
modelTitle: true,
modelProvider: true,
});
export const editInteractionEventSchema_0_2_0_noCode =
editInteractionEventSchema_0_2_0.omit({
prompt: true,
completion: true,
});

View file

@ -0,0 +1,15 @@
import { z } from "zod";
import { baseDevDataAllSchema } from "../base.js";
export const editOutcomeEventAllSchema = baseDevDataAllSchema.extend({
modelProvider: z.string(),
modelTitle: z.string(),
prompt: z.string(),
completion: z.string(),
previousCode: z.string(),
newCode: z.string(),
previousCodeLines: z.number(),
newCodeLines: z.number(),
lineChange: z.number(),
accepted: z.boolean(),
});

View file

@ -0,0 +1,24 @@
import { editOutcomeEventAllSchema } from "./index.js";
export const editOutcomeEventSchema_0_2_0 = editOutcomeEventAllSchema.pick({
// base
timestamp: true,
userId: true,
userAgent: true,
selectedProfileId: true,
eventName: true,
schema: true,
// other
prompt: true,
completion: true,
modelTitle: true,
modelProvider: true,
accepted: true,
});
export const editOutcomeEventSchema_0_2_0_noCode =
editOutcomeEventSchema_0_2_0.omit({
prompt: true,
completion: true,
});

View file

@ -0,0 +1,128 @@
import { z } from "zod";
import { autocompleteEventAllSchema } from "./autocomplete/index.js";
import { requestOptionsSchema } from "../models.js";
import {
autocompleteEventSchema_0_1_0,
autocompleteEventSchema_0_1_0_noCode,
} from "./autocomplete/v0.1.0.js";
import {
quickEditEventSchema_0_1_0,
quickEditEventSchema_0_1_0_noCode,
} from "./quickEdit/v0.1.0.js";
import {
autocompleteEventSchema_0_2_0,
autocompleteEventSchema_0_2_0_noCode,
} from "./autocomplete/v0.2.0.js";
import { quickEditEventAllSchema } from "./quickEdit/index.js";
import { chatFeedbackEventAllSchema } from "./chatFeedback/index.js";
import { tokensGeneratedEventAllSchema } from "./tokensGenerated/index.js";
import {
chatFeedbackEventSchema_0_1_0,
chatFeedbackEventSchema_0_1_0_noCode,
} from "./chatFeedback/v0.1.0.js";
import {
tokensGeneratedEventSchema_0_1_0,
tokensGeneratedEventSchema_0_1_0_noCode,
} from "./tokensGenerated/v0.1.0.js";
import {
chatFeedbackEventSchema_0_2_0,
chatFeedbackEventSchema_0_2_0_noCode,
} from "./chatFeedback/v0.2.0.js";
import {
tokensGeneratedEventSchema_0_2_0,
tokensGeneratedEventSchema_0_2_0_noCode,
} from "./tokensGenerated/v0.2.0.js";
import { chatInteractionEventAllSchema } from "./chatInteraction/index.js";
import {
chatInteractionEventSchema_0_2_0,
chatInteractionEventSchema_0_2_0_noCode,
} from "./chatInteraction/v0.2.0.js";
import { editInteractionEventAllSchema } from "./editInteraction/index.js";
const semverRegex =
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
const dataLevel = z.union([z.literal("all"), z.literal("noCode")]);
export const dataSchema = z.object({
name: z.string(),
destination: z.string().url(),
schema: z.string().regex(semverRegex, {
message: "Version must follow semver format, e.g. 0.2.0",
}),
level: dataLevel.optional(),
events: z.array(z.string()).optional(), // Could do literals e.g. "autocomplete", "chat" but want to allow some flexibility later
requestOptions: requestOptionsSchema.optional(),
apiKey: z.string().optional(),
});
export type DataDestination = z.infer<typeof dataSchema>;
export type DataLogLevel = z.infer<typeof dataLevel>;
// Schemas for data that the log function should have
// In order to build event bodies for ALL versions of an event
const devEventAllVersionDataSchemas = z.object({
autocomplete: autocompleteEventAllSchema,
quickEdit: quickEditEventAllSchema,
chatFeedback: chatFeedbackEventAllSchema,
tokensGenerated: tokensGeneratedEventAllSchema,
chatInteraction: chatInteractionEventAllSchema,
// editInteraction: editInteractionEventAllSchema,
});
// Version and level specific schemas are organized here
export const devDataVersionedSchemas = {
["0.1.0" as string]: {
all: {
autocomplete: autocompleteEventSchema_0_1_0,
quickEdit: quickEditEventSchema_0_1_0,
chatFeedback: chatFeedbackEventSchema_0_1_0,
tokensGenerated: tokensGeneratedEventSchema_0_1_0,
},
noCode: {
autocomplete: autocompleteEventSchema_0_1_0_noCode,
quickEdit: quickEditEventSchema_0_1_0_noCode,
chatFeedback: chatFeedbackEventSchema_0_1_0_noCode,
tokensGenerated: tokensGeneratedEventSchema_0_1_0_noCode,
},
},
["0.2.0" as string]: {
all: {
autocomplete: autocompleteEventSchema_0_2_0,
chatFeedback: chatFeedbackEventSchema_0_2_0,
tokensGenerated: tokensGeneratedEventSchema_0_2_0,
chatInteraction: chatInteractionEventSchema_0_2_0,
// editInteraction: editInteractionEventSchema_0_2_0,
},
noCode: {
autocomplete: autocompleteEventSchema_0_2_0_noCode,
chatFeedback: chatFeedbackEventSchema_0_2_0_noCode,
tokensGenerated: tokensGeneratedEventSchema_0_2_0_noCode,
chatInteraction: chatInteractionEventSchema_0_2_0_noCode,
// editInteraction: editInteractionEventSchema_0_2_0_noCode,
},
},
};
type DevEventDataSchemas = z.infer<typeof devEventAllVersionDataSchemas>;
export type DevEventName = keyof DevEventDataSchemas;
type DevEventAllVersionsSchema<T extends DevEventName> = DevEventDataSchemas[T];
export type DevDataLogEvent = {
[K in DevEventName]: {
name: K;
data: Omit<
DevEventAllVersionsSchema<K>,
| "eventName"
| "schema"
| "timestamp"
| "userId"
| "userAgent"
| "selectedProfileId"
>;
};
}[DevEventName];
export const allDevEventNames = Object.keys(
devEventAllVersionDataSchemas.shape,
) as DevEventName[];

View file

@ -0,0 +1,16 @@
import { z } from "zod";
export const quickEditEventAllSchema = z.object({
prompt: z.string(),
path: z.string().optional(),
label: z.string(),
diffs: z
.array(
z.object({
type: z.enum(["new", "old", "same"]),
line: z.string(),
}),
)
.optional(),
model: z.string().optional(),
});

View file

@ -0,0 +1,16 @@
import { quickEditEventAllSchema } from "./index.js";
export const quickEditEventSchema_0_1_0 = quickEditEventAllSchema.pick({
prompt: true,
path: true,
label: true,
diffs: true,
model: true,
});
export const quickEditEventSchema_0_1_0_noCode =
quickEditEventSchema_0_1_0.omit({
prompt: true,
path: true,
diffs: true,
});

View file

@ -0,0 +1,9 @@
import { z } from "zod";
import { baseDevDataAllSchema } from "../base.js";
export const tokensGeneratedEventAllSchema = baseDevDataAllSchema.extend({
model: z.string(),
provider: z.string(),
promptTokens: z.number(),
generatedTokens: z.number(),
});

View file

@ -0,0 +1,12 @@
import { tokensGeneratedEventAllSchema } from "./index.js";
export const tokensGeneratedEventSchema_0_1_0 =
tokensGeneratedEventAllSchema.pick({
model: true,
provider: true,
promptTokens: true,
generatedTokens: true,
});
export const tokensGeneratedEventSchema_0_1_0_noCode =
tokensGeneratedEventSchema_0_1_0;

View file

@ -0,0 +1,21 @@
import { tokensGeneratedEventAllSchema } from "./index.js";
export const tokensGeneratedEventSchema_0_2_0 =
tokensGeneratedEventAllSchema.pick({
// base
timestamp: true,
userId: true,
userAgent: true,
selectedProfileId: true,
eventName: true,
schema: true,
// tokens generated specific
model: true,
provider: true,
promptTokens: true,
generatedTokens: true,
});
export const tokensGeneratedEventSchema_0_2_0_noCode =
tokensGeneratedEventSchema_0_2_0;

View file

@ -1,10 +1,6 @@
import * as z from "zod";
import { modelSchema, partialModelSchema } from "./models.js";
export const dataSchema = z.object({
destination: z.string(),
levels: z.string().optional(),
});
import { dataSchema } from "./data/index.js";
export const contextSchema = z.object({
provider: z.string(),

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