diff --git a/core/commands/slash/draftIssue.ts b/core/commands/slash/draftIssue.ts index a640dbd25..637013476 100644 --- a/core/commands/slash/draftIssue.ts +++ b/core/commands/slash/draftIssue.ts @@ -32,7 +32,7 @@ const DraftIssueCommand: SlashCommand = { let title = await llm.complete( `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, new AbortController().signal, - { maxTokens: 20 }, + { maxTokens: 30 }, ); title = `${removeQuotesAndEscapes(title.trim())}\n\n`; @@ -40,7 +40,7 @@ const DraftIssueCommand: SlashCommand = { let body = ""; const messages: ChatMessage[] = [ - ...history, + ...history.filter((msg) => msg.role !== "system"), { role: "user", content: PROMPT(input, title) }, ]; diff --git a/core/commands/slash/mcp.ts b/core/commands/slash/mcp.ts index 91c9dcd16..84df38989 100644 --- a/core/commands/slash/mcp.ts +++ b/core/commands/slash/mcp.ts @@ -1,5 +1,6 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { PromptMessage } from "@modelcontextprotocol/sdk/types.js"; import { ChatMessage, SlashCommand } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; export function constructMcpSlashCommand( @@ -22,8 +23,8 @@ export function constructMcpSlashCommand( } const result = await client.getPrompt({ name, arguments: argsObject }); - - const messages: ChatMessage[] = result.messages.map((msg) => { + const mcpMessages: PromptMessage[] = result.messages; + const messages: ChatMessage[] = mcpMessages.map((msg) => { if (msg.content.type !== "text") { throw new Error( "Continue currently only supports text prompts through MCP", @@ -40,12 +41,22 @@ export function constructMcpSlashCommand( return; } - const reversedMessages = [...messages].reverse(); - const messageToAppendInput = - reversedMessages.find((m) => m.role === "user") ?? - reversedMessages.find((m) => m.role === "assistant") ?? - reversedMessages[0]; - messageToAppendInput.content += ` ${userInput}`; + if (userInput) { + const lastMessage = messages.at(-1); + if (!lastMessage || lastMessage.role !== "user") { + messages.push({ + role: "user", + content: userInput, + }); + } else { + let newContent = renderChatMessage(lastMessage); + if (newContent) { + newContent += "\n\n"; + } + newContent += userInput; + lastMessage.content = newContent; + } + } for await (const chunk of context.llm.streamChat( messages, diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index fd628eb06..96e676ce6 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -4,7 +4,7 @@ import { ControlPlaneClient, ControlPlaneSessionInfo, } from "../control-plane/client.js"; -import { getControlPlaneEnv, useHub } from "../control-plane/env.js"; +import { getControlPlaneEnv } from "../control-plane/env.js"; import { BrowserSerializedContinueConfig, ContinueConfig, @@ -16,7 +16,6 @@ import { import { GlobalContext } from "../util/GlobalContext.js"; import { getAllAssistantFiles } from "./loadLocalAssistants.js"; -import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js"; import LocalProfileLoader from "./profile/LocalProfileLoader.js"; import PlatformProfileLoader from "./profile/PlatformProfileLoader.js"; import { @@ -135,16 +134,11 @@ export class ConfigHandler { const userId = await this.controlPlaneClient.userId; if (userId) { const orgDescs = await this.controlPlaneClient.listOrganizations(); - if (await useHub(this.ideSettingsPromise)) { - const personalHubOrg = await this.getPersonalHubOrg(); - const hubOrgs = await Promise.all( - orgDescs.map((org) => this.getNonPersonalHubOrg(org)), - ); - return [...hubOrgs, personalHubOrg]; - } else { - // Should only ever be one teams org. Will be removed soon anyways - return await Promise.all(orgDescs.map((org) => this.getTeamsOrg(org))); - } + const personalHubOrg = await this.getPersonalHubOrg(); + const hubOrgs = await Promise.all( + orgDescs.map((org) => this.getNonPersonalHubOrg(org)), + ); + return [...hubOrgs, personalHubOrg]; } else { return [await this.getLocalOrg()]; } @@ -213,25 +207,6 @@ export class ConfigHandler { return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, allLocalProfiles); } - async getTeamsOrg(org: OrganizationDescription): Promise { - const workspaces = await this.controlPlaneClient.listWorkspaces(); - const profiles = await this.getAllLocalProfiles(); - workspaces.forEach((workspace) => { - const profileLoader = new ControlPlaneProfileLoader( - workspace.id, - workspace.name, - this.controlPlaneClient, - this.ide, - this.ideSettingsPromise, - this.llmLogger, - this.reloadConfig.bind(this), - ); - - profiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); - }); - return this.rectifyProfilesForOrg(org, profiles); - } - private async rectifyProfilesForOrg( org: OrganizationDescription, profiles: ProfileLifecycleManager[], diff --git a/core/config/getSystemPromptDotFile.ts b/core/config/getSystemPromptDotFile.ts deleted file mode 100644 index 550144cd8..000000000 --- a/core/config/getSystemPromptDotFile.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { IDE } from ".."; -import { joinPathsToUri } from "../util/uri"; -export const SYSTEM_PROMPT_DOT_FILE = ".continuerules"; - -export async function getSystemPromptDotFile(ide: IDE): Promise { - const dirs = await ide.getWorkspaceDirs(); - - let prompts: string[] = []; - for (const dir of dirs) { - const dotFile = joinPathsToUri(dir, SYSTEM_PROMPT_DOT_FILE); - if (await ide.fileExists(dotFile)) { - try { - const content = await ide.readFile(dotFile); - prompts.push(content); - } catch (e) { - // ignore if file doesn't exist - } - } - } - - if (!prompts.length) { - return null; - } - - return prompts.join("\n\n"); -} diff --git a/core/config/getWorkspaceContinueRuleDotFiles.ts b/core/config/getWorkspaceContinueRuleDotFiles.ts new file mode 100644 index 000000000..8a14d2405 --- /dev/null +++ b/core/config/getWorkspaceContinueRuleDotFiles.ts @@ -0,0 +1,32 @@ +import { ConfigValidationError } from "@continuedev/config-yaml"; +import { IDE, RuleWithSource } from ".."; +import { joinPathsToUri } from "../util/uri"; +export const SYSTEM_PROMPT_DOT_FILE = ".continuerules"; + +export async function getWorkspaceContinueRuleDotFiles(ide: IDE) { + const dirs = await ide.getWorkspaceDirs(); + + const errors: ConfigValidationError[] = []; + const rules: RuleWithSource[] = []; + for (const dir of dirs) { + try { + const dotFile = joinPathsToUri(dir, SYSTEM_PROMPT_DOT_FILE); + const exists = await ide.fileExists(dotFile); + if (exists) { + const content = await ide.readFile(dotFile); + rules.push({ + rule: content, + ruleFile: dotFile, + source: ".continuerules", + }); + } + } catch (e) { + errors.push({ + fatal: false, + message: `Failed to load system prompt dot file from workspace ${dir}: ${e instanceof Error ? e.message : e}`, + }); + } + } + + return { rules, errors }; +} diff --git a/core/config/load.ts b/core/config/load.ts index 6473d3a51..4c89651ad 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -18,7 +18,6 @@ import { ContinueConfig, ContinueRcJson, CustomContextProvider, - CustomLLM, EmbeddingsProviderDescription, IContextProvider, IDE, @@ -68,7 +67,6 @@ import { } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; -import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; import { modifyAnyConfigWithSharedConfig } from "./sharedConfig"; import { getModelByRole, @@ -205,12 +203,6 @@ async function serializedToIntermediateConfig( return config; } -function isModelDescription( - llm: ModelDescription | CustomLLM, -): llm is ModelDescription { - return (llm as ModelDescription).title !== undefined; -} - export function isContextProviderWithParams( contextProvider: CustomContextProvider | ContextProviderWithParams, ): contextProvider is ContextProviderWithParams { @@ -243,81 +235,81 @@ async function intermediateToFinalConfig({ // Auto-detect models let models: BaseLLM[] = []; - for (const desc of config.models) { - if (isModelDescription(desc)) { - const llm = await llmFromDescription( - desc, - ide.readFile.bind(ide), - uniqueId, - ideSettings, - llmLogger, - config.completionOptions, - config.systemMessage, - ); - if (!llm) { - continue; - } - - if (llm.model === "AUTODETECT") { - try { - const modelNames = await llm.listModels(); - const detectedModels = await Promise.all( - modelNames.map(async (modelName) => { - return await llmFromDescription( - { - ...desc, - model: modelName, - title: modelName, - }, - ide.readFile.bind(ide), - uniqueId, - ideSettings, - llmLogger, - copyOf(config.completionOptions), - config.systemMessage, - ); - }), - ); - models.push( - ...(detectedModels.filter( - (x) => typeof x !== "undefined", - ) as BaseLLM[]), - ); - } catch (e) { - console.warn("Error listing models: ", e); + await Promise.all( + config.models.map(async (desc) => { + if ("title" in desc) { + const llm = await llmFromDescription( + desc, + ide.readFile.bind(ide), + uniqueId, + ideSettings, + llmLogger, + config.completionOptions, + ); + if (!llm) { + return; } - } else { - models.push(llm); - } - } else { - const llm = new CustomLLMClass({ - ...desc, - options: { ...desc.options, logger: llmLogger } as any, - }); - if (llm.model === "AUTODETECT") { - try { - const modelNames = await llm.listModels(); - const models = modelNames.map( - (modelName) => - new CustomLLMClass({ - ...desc, - options: { - ...desc.options, - model: modelName, - logger: llmLogger, - }, + + if (llm.model === "AUTODETECT") { + try { + const modelNames = await llm.listModels(); + const detectedModels = await Promise.all( + modelNames.map(async (modelName) => { + return await llmFromDescription( + { + ...desc, + model: modelName, + title: modelName, + }, + ide.readFile.bind(ide), + uniqueId, + ideSettings, + llmLogger, + copyOf(config.completionOptions), + ); }), - ); - - models.push(...models); - } catch (e) { - console.warn("Error listing models: ", e); + ); + models.push( + ...(detectedModels.filter( + (x) => typeof x !== "undefined", + ) as BaseLLM[]), + ); + } catch (e) { + console.warn("Error listing models: ", e); + } + } else { + models.push(llm); } } else { - models.push(llm); + const llm = new CustomLLMClass({ + ...desc, + options: { ...desc.options, logger: llmLogger } as any, + }); + if (llm.model === "AUTODETECT") { + try { + const modelNames = await llm.listModels(); + const models = modelNames.map( + (modelName) => + new CustomLLMClass({ + ...desc, + options: { + ...desc.options, + model: modelName, + logger: llmLogger, + }, + }), + ); + + models.push(...models); + } catch (e) { + console.warn("Error listing models: ", e); + } + } else { + models.push(llm); + } } - } - } + }), + ); // Prepare models for (const model of models) { @@ -353,7 +345,7 @@ async function intermediateToFinalConfig({ ? config.tabAutocompleteModel : [config.tabAutocompleteModel] ).map(async (desc) => { - if (isModelDescription(desc)) { + if ("title" in desc) { const llm = await llmFromDescription( desc, ide.readFile.bind(ide), @@ -361,7 +353,6 @@ async function intermediateToFinalConfig({ ideSettings, llmLogger, config.completionOptions, - config.systemMessage, ); if (llm?.providerName === "free-trial") { @@ -534,8 +525,16 @@ async function intermediateToFinalConfig({ rerank: newReranker ?? null, summarize: null, // Not implemented }, + rules: [], }; + if (config.systemMessage) { + continueConfig.rules.unshift({ + rule: config.systemMessage, + source: "json-systemMessage", + }); + } + // Trigger MCP server refreshes (Config is reloaded again once connected!) const mcpManager = MCPManagerSingleton.getInstance(); mcpManager.setConnections( @@ -610,7 +609,6 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription { contextLength: llm.contextLength, template: llm.template, completionOptions: llm.completionOptions, - systemMessage: llm.systemMessage, baseChatSystemMessage: llm.baseChatSystemMessage, requestOptions: llm.requestOptions, promptTemplates: serializePromptTemplates(llm.promptTemplates), @@ -626,7 +624,6 @@ async function finalToBrowserConfig( ): Promise { return { allowAnonymousTelemetry: final.allowAnonymousTelemetry, - systemMessage: final.systemMessage, completionOptions: final.completionOptions, slashCommands: final.slashCommands?.map( ({ run, ...slashCommandDescription }) => slashCommandDescription, @@ -866,11 +863,6 @@ async function loadContinueConfigFromJson( return { errors, config: undefined, configLoadInterrupted: true }; } - const systemPromptDotFile = await getSystemPromptDotFile(ide); - if (systemPromptDotFile) { - serialized.systemMessage = systemPromptDotFile; - } - // Apply shared config // TODO: override several of these values with user/org shared config const sharedConfig = new GlobalContext().getSharedConfig(); diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts deleted file mode 100644 index bf705fd95..000000000 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { ConfigJson } from "@continuedev/config-types"; -import { ConfigResult } from "@continuedev/config-yaml"; - -import { ControlPlaneClient } from "../../control-plane/client.js"; -import { PRODUCTION_ENV } from "../../control-plane/env.js"; -import { - ContinueConfig, - IDE, - IdeSettings, - ILLMLogger, - SerializedContinueConfig, -} from "../../index.js"; -import { ProfileDescription } from "../ProfileLifecycleManager.js"; - -import doLoadConfig from "./doLoadConfig.js"; -import { IProfileLoader } from "./IProfileLoader.js"; - -export default class ControlPlaneProfileLoader implements IProfileLoader { - private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes - - description: ProfileDescription; - - workspaceSettings: ConfigJson | undefined; - - constructor( - private readonly workspaceId: string, - private workspaceTitle: string, - private readonly controlPlaneClient: ControlPlaneClient, - private readonly ide: IDE, - private ideSettingsPromise: Promise, - private llmLogger: ILLMLogger, - private readonly onReload: () => void, - ) { - this.description = { - id: workspaceId, - profileType: "control-plane", - iconUrl: "", - fullSlug: { - ownerSlug: "", - packageSlug: "", - versionSlug: "", - }, - title: workspaceTitle, - errors: undefined, - uri: `${PRODUCTION_ENV.APP_URL}workspaces/${workspaceId}`, - }; - - setInterval(async () => { - this.workspaceSettings = - await this.controlPlaneClient.getSettingsForWorkspace( - this.description.id, - ); - this.onReload(); - }, ControlPlaneProfileLoader.RELOAD_INTERVAL); - } - - async doLoadConfig(): Promise> { - const settings = - this.workspaceSettings ?? - ((await this.controlPlaneClient.getSettingsForWorkspace( - this.description.id, - )) as any); - const serializedConfig: SerializedContinueConfig = settings; - - return await doLoadConfig({ - ide: this.ide, - ideSettingsPromise: this.ideSettingsPromise, - controlPlaneClient: this.controlPlaneClient, - llmLogger: this.llmLogger, - overrideConfigJson: serializedConfig, - overrideConfigYaml: undefined, - platformConfigMetadata: undefined, - profileId: this.workspaceId, - overrideConfigYamlByPath: undefined, - orgScopeId: null, - }); - } - - setIsActive(isActive: boolean): void {} -} diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index c7678f216..99845ddbf 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -34,6 +34,7 @@ import { migrateJsonSharedConfig } from "../migrateSharedConfig"; import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; +import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles"; import { PlatformConfigMetadata } from "./PlatformProfileLoader"; export default async function doLoadConfig({ @@ -120,6 +121,12 @@ export default async function doLoadConfig({ // Remove ability have undefined errors, just have an array errors = [...(errors ?? [])]; + // Add rules from .continuerules files + const { rules, errors: continueRulesErrors } = + await getWorkspaceContinueRuleDotFiles(ide); + newConfig.rules.unshift(...rules); + errors.push(...continueRulesErrors); + // Rectify model selections for each role newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId); diff --git a/core/config/types.ts b/core/config/types.ts index 3cf978540..241b37874 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -958,7 +958,7 @@ declare global { cacheBehavior?: CacheBehavior; } - export interface EmbedOptions { + export interface JSONEmbedOptions { apiBase?: string; apiKey?: string; model?: string; diff --git a/core/config/util.ts b/core/config/util.ts index 4c70acb38..9460986bb 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -1,14 +1,16 @@ import fs from "fs"; import os from "os"; +import { ModelConfig } from "@continuedev/config-yaml"; import { ContinueConfig, ExperimentalModelRoles, IDE, ILLM, - ModelDescription, + JSONModelDescription, PromptTemplate, } from "../"; +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages"; import { GlobalContext } from "../util/GlobalContext"; import { editConfigFile } from "../util/paths"; @@ -23,16 +25,21 @@ function stringify(obj: any, indentation?: number): string { } export function addModel( - model: ModelDescription, + model: JSONModelDescription, role?: keyof ExperimentalModelRoles, ) { editConfigFile( (config) => { - if (config.models?.some((m: any) => stringify(m) === stringify(model))) { + if (config.models?.some((m) => stringify(m) === stringify(model))) { return config; } - if (config.models?.some((m: any) => m?.title === model.title)) { - model.title = `${model.title} (1)`; + + const numMatches = config.models?.reduce( + (prev, curr) => (curr.title.startsWith(model.title) ? prev + 1 : prev), + 0, + ); + if (numMatches !== 0) { + model.title = `${model.title} (${numMatches})`; } config.models.push(model); @@ -51,22 +58,34 @@ export function addModel( return config; }, (config) => { - if (config.models?.some((m: any) => m?.title === model.title)) { - model.title = `${model.title} (1)`; + const numMatches = config.models?.reduce( + (prev, curr) => + "name" in curr && curr.name.startsWith(model.title) ? prev + 1 : prev, + 0, + ); + if (numMatches !== 0) { + model.title = `${model.title} (${numMatches})`; } if (!config.models) { config.models = []; } - config.models.push({ + const desc: ModelConfig = { name: model.title, provider: model.provider, model: model.model, apiKey: model.apiKey, apiBase: model.apiBase, defaultCompletionOptions: model.completionOptions, - }); + }; + if (model.systemMessage) { + desc.chatOptions = { + baseSystemMessage: + DEFAULT_CHAT_SYSTEM_MESSAGE + "\n\n" + model.systemMessage, + }; + } + config.models.push(desc); return config; }, ); diff --git a/core/config/workspace/workspaceBlocks.ts b/core/config/workspace/workspaceBlocks.ts new file mode 100644 index 000000000..009e3cdff --- /dev/null +++ b/core/config/workspace/workspaceBlocks.ts @@ -0,0 +1,97 @@ +import { BlockType, ConfigYaml } from "@continuedev/config-yaml"; +import * as YAML from "yaml"; +import { IDE } from "../.."; +import { joinPathsToUri } from "../../util/uri"; + +function getContentsForNewBlock(blockType: BlockType): ConfigYaml { + const configYaml: ConfigYaml = { + name: `New ${blockType.slice(0, -1)}`, + version: "0.0.1", + schema: "v1", + }; + switch (blockType) { + case "context": + configYaml.context = [ + { + provider: "file", + }, + ]; + break; + case "models": + configYaml.models = [ + { + provider: "anthropic", + model: "claude-3-7-sonnet-latest", + apiKey: "${{ secrets.ANTHROPIC_API_KEY }}", + name: "Claude 3.7 Sonnet", + roles: ["chat", "edit"], + }, + ]; + break; + case "rules": + configYaml.rules = ["Always give concise responses"]; + break; + case "docs": + configYaml.docs = [ + { + name: "New docs", + startUrl: "https://docs.continue.dev", + }, + ]; + break; + case "prompts": + configYaml.prompts = [ + { + name: "New prompt", + description: "New prompt", + prompt: + "Please write a thorough suite of unit tests for this code, making sure to cover all relevant edge cases", + }, + ]; + break; + case "mcpServers": + configYaml.mcpServers = [ + { + name: "New MCP server", + command: "npx", + args: ["-y", ""], + env: {}, + }, + ]; + break; + } + + return configYaml; +} + +export async function createNewWorkspaceBlockFile( + ide: IDE, + blockType: BlockType, +): Promise { + const workspaceDirs = await ide.getWorkspaceDirs(); + if (workspaceDirs.length === 0) { + throw new Error( + "No workspace directories found. Make sure you've opened a folder in your IDE.", + ); + } + + const baseDirUri = joinPathsToUri(workspaceDirs[0], `.continue/${blockType}`); + + // Find the first available filename + let counter = 0; + let fileUri: string; + do { + const suffix = counter === 0 ? "" : `-${counter}`; + fileUri = joinPathsToUri( + baseDirUri, + `new-${blockType.slice(0, -1)}${suffix}.yaml`, + ); + counter++; + } while (await ide.fileExists(fileUri)); + + await ide.writeFile( + fileUri, + YAML.stringify(getContentsForNewBlock(blockType)), + ); + await ide.openFile(fileUri); +} diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 7939a7e83..771f04501 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -6,9 +6,11 @@ import { ConfigValidationError, FQSN, isAssistantUnrolledNonNullable, + MCPServer, ModelRole, PlatformClient, RegistryClient, + Rule, SecretResult, unrollAssistantFromContent, validateConfigYaml, @@ -16,11 +18,13 @@ import { import { ContinueConfig, + ExperimentalMCPOptions, IContextProvider, IDE, IdeInfo, IdeSettings, ILLMLogger, + RuleWithSource, } from "../.."; import { slashFromCustomCommand } from "../../commands"; import { MCPManagerSingleton } from "../../context/mcp"; @@ -36,7 +40,6 @@ import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles"; import { allTools } from "../../tools"; import { GlobalContext } from "../../util/GlobalContext"; import { getConfigYamlPath } from "../../util/paths"; -import { getSystemPromptDotFile } from "../getSystemPromptDotFile"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; @@ -59,6 +62,35 @@ export class LocalPlatformClient implements PlatformClient { } } +function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource { + if (typeof rule === "string") { + return { + rule: rule, + source: "rules-block", + }; + } else { + return { + source: "rules-block", + rule: rule.rule, + if: rule.if, + name: rule.name, + }; + } +} + +function convertYamlMcpToContinueMcp( + server: MCPServer, +): ExperimentalMCPOptions { + return { + transport: { + type: "stdio", + command: server.command, + args: server.args ?? [], + env: server.env, + }, + }; +} + async function loadConfigYaml( rawYaml: string, overrideConfigYaml: AssistantUnrolled | undefined, @@ -80,7 +112,6 @@ async function loadConfigYaml( await controlPlaneClient.getAccessToken(), getControlPlaneEnvSync( ideSettings.continueTestEnvironment, - ideSettings.enableControlServerBeta, ).CONTROL_PLANE_URL, ), { @@ -142,7 +173,6 @@ async function configYamlToContinueConfig({ slashCommands: [], tools: [...allTools], mcpServerStatuses: [], - systemMessage: config.rules?.join("\n"), contextProviders: [], modelsByRole: { chat: [], @@ -162,6 +192,7 @@ async function configYamlToContinueConfig({ rerank: null, summarize: null, }, + rules: [], }; // Right now, if there are any missing packages in the config, then we will just throw an error @@ -177,8 +208,11 @@ async function configYamlToContinueConfig({ }; } + for (const rule of config.rules ?? []) { + continueConfig.rules.push(convertYamlRuleToContinueRule(rule)); + } + continueConfig.data = config.data; - continueConfig.rules = config.rules; continueConfig.docs = config.docs?.map((doc) => ({ title: doc.name, startUrl: doc.startUrl, @@ -186,21 +220,16 @@ async function configYamlToContinueConfig({ faviconUrl: doc.faviconUrl, })); continueConfig.experimental = { - modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({ - transport: { - type: "stdio", - command: mcpServer.command, - args: mcpServer.args ?? [], - env: mcpServer.env, - }, - })), + modelContextProtocolServers: config.mcpServers?.map( + convertYamlMcpToContinueMcp, + ), }; // Prompt files - try { const promptFiles = await getAllPromptFiles(ide, undefined, true); - for (const file of promptFiles) { + promptFiles.forEach((file) => { try { const slashCommand = slashCommandFromPromptFileV1( file.path, @@ -215,7 +244,7 @@ async function configYamlToContinueConfig({ message: `Failed to convert prompt file ${file.path} to slash command: ${e instanceof Error ? e.message : e}`, }); } - } + }); } catch (e) { localErrors.push({ fatal: false, @@ -236,9 +265,9 @@ async function configYamlToContinueConfig({ }); // Models - const modelsArrayRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"]; + const defaultModelRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"]; for (const model of config.models ?? []) { - model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified + model.roles = model.roles ?? defaultModelRoles; // Default to all 4 chat-esque roles if not specified try { const llms = await llmsFromModelConfig({ model, @@ -405,7 +434,6 @@ export async function loadContinueConfigFromYaml({ ideInfo, uniqueId, llmLogger, - // workOsAccessToken, overrideConfigYaml, platformConfigMetadata, controlPlaneClient, @@ -417,7 +445,6 @@ export async function loadContinueConfigFromYaml({ ideInfo: IdeInfo; uniqueId: string; llmLogger: ILLMLogger; - // workOsAccessToken: string | undefined; overrideConfigYaml: AssistantUnrolled | undefined; platformConfigMetadata: PlatformConfigMetadata | undefined; controlPlaneClient: ControlPlaneClient; @@ -460,22 +487,6 @@ export async function loadContinueConfigFromYaml({ allowFreeTrial: true, }); - try { - const systemPromptDotFile = await getSystemPromptDotFile(ide); - if (systemPromptDotFile) { - if (continueConfig.systemMessage) { - continueConfig.systemMessage += "\n\n" + systemPromptDotFile; - } else { - continueConfig.systemMessage = systemPromptDotFile; - } - } - } catch (e) { - localErrors.push({ - fatal: false, - message: `Failed to load system prompt dot file: ${e instanceof Error ? e.message : e}`, - }); - } - // Apply shared config // TODO: override several of these values with user/org shared config // Don't try catch this - has security implications and failure should be fatal diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index 572d7eb70..7b5994317 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -63,8 +63,6 @@ async function modelConfigToBaseLLM({ logger: llmLogger, uniqueId, title: model.name, - systemMessage: config.systemMessage, - rules: config.rules, promptTemplates: model.promptTemplates, baseChatSystemMessage: model.chatOptions?.baseSystemMessage, capabilities: { diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts index 7d3ae9eb0..acbc20b59 100644 --- a/core/control-plane/env.ts +++ b/core/control-plane/env.ts @@ -21,16 +21,6 @@ const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; const WORKOS_ENV_ID_PRODUCTION = "continue"; const WORKOS_ENV_ID_STAGING = "continue-staging"; -export const PRODUCTION_ENV: ControlPlaneEnv = { - DEFAULT_CONTROL_PLANE_PROXY_URL: - "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/", - CONTROL_PLANE_URL: - "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/", - AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION, - WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION, - APP_URL: "https://app.continue.dev/", -}; - const PRODUCTION_HUB_ENV: ControlPlaneEnv = { DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue.dev/", CONTROL_PLANE_URL: "https://api.continue.dev/", @@ -71,15 +61,11 @@ export async function getControlPlaneEnv( ideSettingsPromise: Promise, ): Promise { const ideSettings = await ideSettingsPromise; - return getControlPlaneEnvSync( - ideSettings.continueTestEnvironment, - ideSettings.enableControlServerBeta, - ); + return getControlPlaneEnvSync(ideSettings.continueTestEnvironment); } export function getControlPlaneEnvSync( ideTestEnvironment: IdeSettings["continueTestEnvironment"], - enableControlServerBeta: IdeSettings["enableControlServerBeta"], ): ControlPlaneEnv { // Note .local overrides .staging if (fs.existsSync(getLocalEnvironmentDotFilePath())) { @@ -90,10 +76,6 @@ export function getControlPlaneEnvSync( return STAGING_ENV; } - if (enableControlServerBeta === true) { - return PRODUCTION_ENV; - } - const env = ideTestEnvironment === "production" ? "hub" @@ -109,17 +91,12 @@ export function getControlPlaneEnvSync( ? STAGING_ENV : env === "test" ? TEST_ENV - : env === "hub" - ? PRODUCTION_HUB_ENV - : PRODUCTION_ENV; + : PRODUCTION_HUB_ENV; } export async function useHub( ideSettingsPromise: Promise, ): Promise { const ideSettings = await ideSettingsPromise; - if (ideSettings.enableControlServerBeta) { - return false; - } return ideSettings.continueTestEnvironment !== "none"; } diff --git a/core/core.ts b/core/core.ts index 68aa605ac..a5e54404b 100644 --- a/core/core.ts +++ b/core/core.ts @@ -4,7 +4,7 @@ import { v4 as uuidv4 } from "uuid"; import { CompletionProvider } from "./autocomplete/CompletionProvider"; import { ConfigHandler } from "./config/ConfigHandler"; -import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile"; +import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles"; import { addModel, deleteModel } from "./config/util"; import CodebaseContextProvider from "./context/providers/CodebaseContextProvider"; import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider"; @@ -30,6 +30,7 @@ import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; import { + ContextItemWithId, DiffLine, IdeSettings, ModelDescription, @@ -46,6 +47,7 @@ import { setupLocalConfig, setupQuickstartConfig, } from "./config/onboarding"; +import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks"; import { MCPManagerSingleton } from "./context/mcp"; import { streamDiffLines } from "./edit/streamDiffLines"; import { shouldIgnore } from "./indexing/shouldIgnore"; @@ -61,23 +63,29 @@ async function* streamDiffLinesGenerator( msg: Message, ): AsyncGenerator { const data = msg.data; - const llm = (await configHandler.loadConfig()).config?.selectedModelByRole - .chat; + + const { config } = await configHandler.loadConfig(); + if (!config) { + throw new Error("Failed to load config"); + } + + const llm = config.selectedModelByRole.chat; if (!llm) { throw new Error("No chat model selected"); } - for await (const diffLine of streamDiffLines( - data.prefix, - data.highlighted, - data.suffix, + for await (const diffLine of streamDiffLines({ + highlighted: data.highlighted, + prefix: data.prefix, + suffix: data.suffix, llm, - data.input, - data.language, - false, - undefined, - )) { + rules: config.rules, + input: data.input, + language: data.language, + onlyOneInsertion: false, + overridePrompt: undefined, + })) { if (abortedMessageIds.has(msg.messageId)) { abortedMessageIds.delete(msg.messageId); break; @@ -164,8 +172,6 @@ export class Core { this.configHandler.currentProfile?.profileDescription.id || null, organizations: this.configHandler.getSerializedOrgs(), selectedOrgId: this.configHandler.currentOrg.id, - usingContinueForTeams: (await ideSettingsPromise) - .enableControlServerBeta, }); // update additional submenu context providers registered via VSCode API @@ -257,9 +263,7 @@ export class Core { stack: err.stack, }); - // Again, specifically for jetbrains to prevent duplicate error messages - // The same logic can currently be found in the webview protocol - // bc streaming errors are handled in the GUI + // just to prevent duplicate error messages in jetbrains (same logic in webview protocol) if ( ["llm/streamChat", "chatDescriber/describe"].includes( message.messageType, @@ -323,6 +327,11 @@ export class Core { await this.configHandler.reloadConfig(); }); + on("config/addLocalWorkspaceBlock", async (msg) => { + await createNewWorkspaceBlockFile(this.ide, msg.data.blockType); + await this.configHandler.reloadConfig(); + }); + on("config/openProfile", async (msg) => { await this.configHandler.openConfigProfile(msg.data.profileId); }); @@ -337,7 +346,13 @@ export class Core { }); on("config/refreshProfiles", async (msg) => { + const { selectOrgId, selectProfileId } = msg.data ?? {}; await this.configHandler.refreshAll(); + if (selectOrgId) { + await this.configHandler.setSelectedOrgId(selectOrgId, selectProfileId); + } else if (selectProfileId) { + await this.configHandler.setSelectedProfileId(selectProfileId); + } }); on("config/updateSharedConfig", async (msg) => { @@ -412,8 +427,6 @@ export class Core { this.configHandler.currentProfile?.profileDescription.id ?? null, organizations: this.configHandler.getSerializedOrgs(), selectedOrgId: this.configHandler.currentOrg.id, - usingContinueForTeams: (await ideSettingsPromise) - .enableControlServerBeta, }; }); @@ -492,9 +505,9 @@ export class Core { streamDiffLinesGenerator(this.configHandler, this.abortedMessageIds, msg), ); - on("completeOnboarding", this.handleCompleteOnboarding); + on("completeOnboarding", this.handleCompleteOnboarding.bind(this)); - on("addAutocompleteModel", this.handleAddAutocompleteModel); + on("addAutocompleteModel", this.handleAddAutocompleteModel.bind(this)); on("stats/getTokensPerDay", async (msg) => { const rows = await DevDataSqliteDb.getTokensPerDay(); @@ -534,10 +547,8 @@ export class Core { } }); - // File changes - // TODO - remove remaining logic for these from IDEs where possible - on("files/changed", this.handleFilesChanged); - + // File changes - TODO - remove remaining logic for these from IDEs where possible + on("files/changed", this.handleFilesChanged.bind(this)); const refreshIfNotIgnored = async (uris: string[]) => { const toRefresh: string[] = []; for (const uri of uris) { @@ -613,7 +624,6 @@ export class Core { on("docs/getDetails", async (msg) => { return await this.docsService.getDetails(msg.data.startUrl); }); - // on("didChangeSelectedProfile", async (msg) => { await this.configHandler.setSelectedProfileId(msg.data.id); @@ -667,10 +677,7 @@ export class Core { throw new Error(`Tool ${toolCall.function.name} not found`); } - const llm = (await this.configHandler.loadConfig()).config - ?.selectedModelByRole.chat; - - if (!llm) { + if (!config.selectedModelByRole.chat) { throw new Error("No chat model selected"); } @@ -679,7 +686,7 @@ export class Core { JSON.parse(toolCall.function.arguments || "{}"), { ide: this.ide, - llm, + llm: config.selectedModelByRole.chat, fetch: (url, init) => fetchwithRequestOptions(url, init, config.requestOptions), tool, @@ -696,29 +703,33 @@ export class Core { }); on("isItemTooBig", async ({ data: { item, selectedModelTitle } }) => { - const { config } = await this.configHandler.loadConfig(); - - if (!config) { - return false; - } - - const llm = (await this.configHandler.loadConfig()).config - ?.selectedModelByRole.chat; - - if (!llm) { - throw new Error("No chat model selected"); - } - - const tokens = countTokens(item.content); - - if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) { - return true; - } - - return false; + return this.isItemTooBig(item); }); } + private async isItemTooBig(item: ContextItemWithId) { + const { config } = await this.configHandler.loadConfig(); + + if (!config) { + return false; + } + + const llm = (await this.configHandler.loadConfig()).config + ?.selectedModelByRole.chat; + + if (!llm) { + throw new Error("No chat model selected"); + } + + const tokens = countTokens(item.content); + + if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) { + return true; + } + + return false; + } + private handleAddAutocompleteModel( msg: Message<{ model: ModelDescription; diff --git a/core/edit/lazy/applyCodeBlock.ts b/core/edit/lazy/applyCodeBlock.ts index d2323aca3..8ca9a8154 100644 --- a/core/edit/lazy/applyCodeBlock.ts +++ b/core/edit/lazy/applyCodeBlock.ts @@ -2,7 +2,7 @@ import { DiffLine, ILLM } from "../.."; import { generateLines } from "../../diff/util"; import { supportedLanguages } from "../../util/treeSitter"; import { getUriFileExtension } from "../../util/uri"; - +import { deterministicApplyLazyEdit } from "./deterministic"; import { streamLazyApply } from "./streamLazyApply"; import { applyUnifiedDiff, isUnifiedDiffFormat } from "./unifiedDiffApply"; @@ -13,35 +13,44 @@ function canUseInstantApply(filename: string) { export async function applyCodeBlock( oldFile: string, - newFile: string, + newLazyFile: string, filename: string, llm: ILLM, -): Promise<[boolean, AsyncGenerator]> { - // This was buggy, removed for now, maybe forever - // if (canUseInstantApply(filename)) { - // const diffLines = await deterministicApplyLazyEdit( - // oldFile, - // newFile, - // filename, - // ); +): Promise<{ + isInstantApply: boolean; + diffLinesGenerator: AsyncGenerator; +}> { + if (canUseInstantApply(filename)) { + const diffLines = await deterministicApplyLazyEdit({ + oldFile, + newLazyFile, + filename, + onlyFullFileRewrite: true, + }); - // // Fall back to LLM method if we couldn't apply deterministically - // if (diffLines !== undefined) { - // const diffGenerator = generateLines(diffLines!); - // return [true, diffGenerator]; - // } - // } + if (diffLines !== undefined) { + return { + isInstantApply: true, + diffLinesGenerator: generateLines(diffLines!), + }; + } + } // If the code block is a diff - if (isUnifiedDiffFormat(newFile)) { + if (isUnifiedDiffFormat(newLazyFile)) { try { - const diffLines = applyUnifiedDiff(oldFile, newFile); - const diffGenerator = generateLines(diffLines!); - return [true, diffGenerator]; + const diffLines = applyUnifiedDiff(oldFile, newLazyFile); + return { + isInstantApply: true, + diffLinesGenerator: generateLines(diffLines!), + }; } catch (e) { console.error("Failed to apply unified diff", e); } } - return [false, streamLazyApply(oldFile, filename, newFile, llm)]; + return { + isInstantApply: false, + diffLinesGenerator: streamLazyApply(oldFile, filename, newLazyFile, llm), + }; } diff --git a/core/edit/lazy/deterministic.test.ts b/core/edit/lazy/deterministic.test.ts index 7590e5025..adfaafa5e 100644 --- a/core/edit/lazy/deterministic.test.ts +++ b/core/edit/lazy/deterministic.test.ts @@ -21,11 +21,11 @@ async function collectDiffs( ): Promise<{ ourDiffs: DiffLine[]; myersDiffs: any }> { const ourDiffs: DiffLine[] = []; - for (const diffLine of (await deterministicApplyLazyEdit( + for (const diffLine of (await deterministicApplyLazyEdit({ oldFile, - newFile, + newLazyFile: newFile, filename, - )) ?? []) { + })) ?? []) { ourDiffs.push(diffLine); } diff --git a/core/edit/lazy/deterministic.ts b/core/edit/lazy/deterministic.ts index 1e3a0ec4e..947f628e4 100644 --- a/core/edit/lazy/deterministic.ts +++ b/core/edit/lazy/deterministic.ts @@ -15,6 +15,11 @@ type AstReplacements = Array<{ replacementNodes: Parser.SyntaxNode[]; }>; +const LAZY_COMMENT_REGEX = /\.{3}\s*(.+?)\s*\.{3}/; +export function isLazyText(text: string): boolean { + return LAZY_COMMENT_REGEX.test(text); +} + function reconstructNewFile( oldFile: string, newFile: string, @@ -121,11 +126,23 @@ function nodeSurroundedInLazyBlocks( } // TODO: If we don't have high confidence, return undefined to fall back to slower methods -export async function deterministicApplyLazyEdit( - oldFile: string, - newLazyFile: string, - filename: string, -): Promise { +export async function deterministicApplyLazyEdit({ + oldFile, + newLazyFile, + filename, + /** + * Using this as a flag to slowly reintroduce lazy applies. + * With this set, we will only attempt to deterministically apply + * when there are no lazy blocks and then just replace the whole file, + * and otherwise never use instant apply + */ + onlyFullFileRewrite = false, +}: { + oldFile: string; + newLazyFile: string; + filename: string; + onlyFullFileRewrite?: boolean; +}): Promise { const parser = await getParserForFile(filename); if (!parser) { return undefined; @@ -135,6 +152,14 @@ export async function deterministicApplyLazyEdit( let newTree = parser.parse(newLazyFile); let reconstructedNewFile: string | undefined = undefined; + if (onlyFullFileRewrite) { + if (!isLazyText(newTree.rootNode.text)) { + return myersDiff(oldFile, newLazyFile); + } else { + return undefined; + } + } + // If there is no lazy block anywhere, we add our own to the outsides // so that large chunks of the file don't get removed if (!findInAst(newTree.rootNode, isLazyBlock)) { @@ -198,11 +223,6 @@ export async function deterministicApplyLazyEdit( return diff; } -const LAZY_COMMENT_REGEX = /\.{3}\s*(.+?)\s*\.{3}/; -export function isLazyLine(text: string): boolean { - return LAZY_COMMENT_REGEX.test(text); -} - function isLazyBlock(node: Parser.SyntaxNode): boolean { // Special case for "{/* ... existing code ... */}" if ( @@ -213,7 +233,7 @@ function isLazyBlock(node: Parser.SyntaxNode): boolean { return true; } - return node.type.includes("comment") && isLazyLine(node.text); + return node.type.includes("comment") && isLazyText(node.text); } function stringsWithinLevDistThreshold( diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index 4f530cd60..1f5c8ffc0 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -1,4 +1,11 @@ -import { ChatMessage, DiffLine, ILLM, Prediction } from "../"; +import { + ChatMessage, + DiffLine, + ILLM, + Prediction, + RuleWithSource, + UserChatMessage, +} from "../"; import { filterCodeBlockLines, filterEnglishLinesAtEnd, @@ -10,7 +17,9 @@ import { } from "../autocomplete/filtering/streamTransforms/lineStream"; import { streamDiff } from "../diff/streamDiff"; import { streamLines } from "../diff/util"; +import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules"; import { gptEditPrompt } from "../llm/templates/edit"; +import { findLast } from "../util/findLast"; import { Telemetry } from "../util/posthog"; function constructPrompt( @@ -47,16 +56,27 @@ function modelIsInept(model: string): boolean { return !(model.includes("gpt") || model.includes("claude")); } -export async function* streamDiffLines( - prefix: string, - highlighted: string, - suffix: string, - llm: ILLM, - input: string, - language: string | undefined, - onlyOneInsertion: boolean, - overridePrompt: ChatMessage[] | undefined, -): AsyncGenerator { +export async function* streamDiffLines({ + prefix, + highlighted, + suffix, + llm, + input, + language, + onlyOneInsertion, + overridePrompt, + rules, +}: { + prefix: string; + highlighted: string; + suffix: string; + llm: ILLM; + input: string; + language: string | undefined; + onlyOneInsertion: boolean; + overridePrompt: ChatMessage[] | undefined; + rules: RuleWithSource[]; +}): AsyncGenerator { void Telemetry.capture( "inlineEdit", { @@ -78,9 +98,54 @@ export async function* streamDiffLines( oldLines = []; } - const prompt = + let prompt = overridePrompt ?? constructPrompt(prefix, highlighted, suffix, llm, input, language); + + // Rules will be included with edit prompt + // If any rules are present this will result in using chat instead of legacy completion + const lastUserMessage: UserChatMessage | undefined = + typeof prompt === "string" + ? { + role: "user", + content: prompt, + } + : (findLast(prompt, (msg) => msg.role === "user") as + | UserChatMessage + | undefined); + + const systemMessage = getSystemMessageWithRules({ + currentModel: llm.model, + rules, + userMessage: lastUserMessage, + baseSystemMessage: undefined, + }); + + if (systemMessage) { + if (typeof prompt === "string") { + prompt = [ + { + role: "system", + content: systemMessage, + }, + { + role: "user", + content: prompt, + }, + ]; + } else { + const curSysMsg = prompt.find((msg) => msg.role === "system"); + if (curSysMsg) { + curSysMsg.content = systemMessage + "\n\n" + curSysMsg.content; + } else { + prompt.unshift({ + role: "system", + content: systemMessage, + }); + } + } + } + const inept = modelIsInept(llm.model); const prediction: Prediction = { diff --git a/core/index.d.ts b/core/index.d.ts index 30a977717..5711f9d9e 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,4 +1,4 @@ -import { DataDestination, ModelRole, Rule } from "@continuedev/config-yaml"; +import { DataDestination, ModelRole } from "@continuedev/config-yaml"; import Parser from "web-tree-sitter"; import { LLMConfigurationStatuses } from "./llm/constants"; import { GetGhTokenArgs } from "./protocol/ide"; @@ -559,7 +559,6 @@ export interface LLMOptions { title?: string; uniqueId?: string; - systemMessage?: string; baseChatSystemMessage?: string; contextLength?: number; maxStopWords?: number; @@ -570,7 +569,6 @@ export interface LLMOptions { templateMessages?: (messages: ChatMessage[]) => string; logger?: ILLMLogger; llmRequestHook?: (model: string, prompt: string) => any; - rules?: Rule[]; apiKey?: string; // continueProperties @@ -701,7 +699,6 @@ export interface IdeSettings { remoteConfigServerUrl: string | undefined; remoteConfigSyncPeriod: number; userToken: string; - enableControlServerBeta: boolean; continueTestEnvironment: "none" | "production" | "staging" | "local"; pauseCodebaseIndexOnStart: boolean; } @@ -1028,9 +1025,8 @@ export interface ModelDescription { model: string; apiKey?: string; - // continueProperties - apiKeyLocation?: string; apiBase?: string; + apiKeyLocation?: string; orgScopeId?: string | null; onPremProxyUrl?: string | null; @@ -1039,7 +1035,6 @@ export interface ModelDescription { maxStopWords?: number; template?: TemplateType; completionOptions?: BaseCompletionOptions; - systemMessage?: string; baseChatSystemMessage?: string; requestOptions?: RequestOptions; promptTemplates?: { [key: string]: string }; @@ -1049,7 +1044,7 @@ export interface ModelDescription { configurationStatus?: LLMConfigurationStatuses; } -export interface EmbedOptions { +export interface JSONEmbedOptions { apiBase?: string; apiKey?: string; model?: string; @@ -1070,7 +1065,7 @@ export interface EmbedOptions { projectId?: string; } -export interface EmbeddingsProviderDescription extends EmbedOptions { +export interface EmbeddingsProviderDescription extends JSONEmbedOptions { provider: string; } @@ -1294,11 +1289,39 @@ export interface AnalyticsConfig { clientKey?: string; } +export interface JSONModelDescription { + title: string; + provider: string; + model: string; + apiKey?: string; + apiBase?: string; + + contextLength?: number; + maxStopWords?: number; + template?: TemplateType; + completionOptions?: BaseCompletionOptions; + systemMessage?: string; + requestOptions?: RequestOptions; + cacheBehavior?: CacheBehavior; + + region?: string; + profile?: string; + modelArn?: string; + apiType?: "openai" | "azure"; + apiVersion?: string; + deployment?: string; + projectId?: string; + accountId?: string; + aiGatewaySlug?: string; + useLegacyCompletionsEndpoint?: boolean; + deploymentId?: string; +} + // config.json export interface SerializedContinueConfig { env?: string[]; allowAnonymousTelemetry?: boolean; - models: ModelDescription[]; + models: JSONModelDescription[]; systemMessage?: string; completionOptions?: BaseCompletionOptions; requestOptions?: RequestOptions; @@ -1309,7 +1332,7 @@ export interface SerializedContinueConfig { disableSessionTitles?: boolean; userToken?: string; embeddingsProvider?: EmbeddingsProviderDescription; - tabAutocompleteModel?: ModelDescription | ModelDescription[]; + tabAutocompleteModel?: JSONModelDescription | JSONModelDescription[]; tabAutocompleteOptions?: Partial; ui?: ContinueUIConfig; reranker?: RerankerDescription; @@ -1329,11 +1352,11 @@ export type ContinueRcJson = Partial & { export interface Config { /** If set to true, Continue will collect anonymous usage data to improve the product. If set to false, we will collect nothing. Read here to learn more: https://docs.continue.dev/telemetry */ allowAnonymousTelemetry?: boolean; - /** Each entry in this array will originally be a ModelDescription, the same object from your config.json, but you may add CustomLLMs. + /** Each entry in this array will originally be a JSONModelDescription, the same object from your config.json, but you may add CustomLLMs. * A CustomLLM requires you only to define an AsyncGenerator that calls the LLM and yields string updates. You can choose to define either `streamCompletion` or `streamChat` (or both). * Continue will do the rest of the work to construct prompt templates, handle context items, prune context, etc. */ - models: (CustomLLM | ModelDescription)[]; + models: (CustomLLM | JSONModelDescription)[]; /** A system message to be followed by all of your models */ systemMessage?: string; /** The default completion options for all models */ @@ -1357,8 +1380,8 @@ export interface Config { /** The model that Continue will use for tab autocompletions. */ tabAutocompleteModel?: | CustomLLM - | ModelDescription - | (CustomLLM | ModelDescription)[]; + | JSONModelDescription + | (CustomLLM | JSONModelDescription)[]; /** Options for tab autocomplete */ tabAutocompleteOptions?: Partial; /** UI styles customization */ @@ -1375,7 +1398,7 @@ export interface Config { // in the actual Continue source code export interface ContinueConfig { allowAnonymousTelemetry?: boolean; - systemMessage?: string; + // systemMessage?: string; completionOptions?: BaseCompletionOptions; requestOptions?: RequestOptions; slashCommands: SlashCommand[]; @@ -1390,7 +1413,7 @@ export interface ContinueConfig { docs?: SiteIndexingConfig[]; tools: Tool[]; mcpServerStatuses: MCPServerStatus[]; - rules?: Rule[]; + rules: RuleWithSource[]; modelsByRole: Record; selectedModelByRole: Record; data?: DataDestination[]; @@ -1398,7 +1421,7 @@ export interface ContinueConfig { export interface BrowserSerializedContinueConfig { allowAnonymousTelemetry?: boolean; - systemMessage?: string; + // systemMessage?: string; completionOptions?: BaseCompletionOptions; requestOptions?: RequestOptions; slashCommands: SlashCommandDescription[]; @@ -1412,7 +1435,7 @@ export interface BrowserSerializedContinueConfig { docs?: SiteIndexingConfig[]; tools: Tool[]; mcpServerStatuses: MCPServerStatus[]; - rules?: Rule[]; + rules: RuleWithSource[]; usePlatform: boolean; tabAutocompleteOptions?: Partial; modelsByRole: Record; @@ -1460,3 +1483,18 @@ export interface TerminalOptions { reuseTerminal?: boolean; terminalName?: string; } + +export interface RuleWithSource { + name?: string; + slug?: string; + source: + | "default" + | "model-chat-options" + | "rules-block" + | "json-systemMessage" + | ".continuerules"; + if?: string; + rule: string; + description?: string; + ruleFile?: string; +} diff --git a/core/indexing/LanceDbIndex.test.ts b/core/indexing/LanceDbIndex.test.skip.ts similarity index 100% rename from core/indexing/LanceDbIndex.test.ts rename to core/indexing/LanceDbIndex.test.skip.ts diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index f3e6b4d07..b58a18c9f 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,7 +1,19 @@ -import { ChatHistoryItem, ChatMessage, MessagePart } from "../"; +import { + ChatHistoryItem, + ChatMessage, + RuleWithSource, + TextMessagePart, + UserChatMessage, +} from "../"; +import { findLast } from "../util/findLast"; import { normalizeToMessageParts } from "../util/messageContent"; +import { messageIsEmpty } from "./messages"; +import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; -const DEFAULT_SYSTEM_MESSAGE = `\ +export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = + "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L8"; + +export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ Always include the language and file name in the info string when you write code blocks. If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py' @@ -35,17 +47,14 @@ const CANCELED_TOOL_CALL_MESSAGE = export function constructMessages( history: ChatHistoryItem[], baseChatSystemMessage: string | undefined, + rules: RuleWithSource[], + modelName: string, ): ChatMessage[] { const filteredHistory = history.filter( (item) => item.message.role !== "system", ); const msgs: ChatMessage[] = []; - msgs.push({ - role: "system", - content: baseChatSystemMessage ?? DEFAULT_SYSTEM_MESSAGE, - }); - for (let i = 0; i < filteredHistory.length; i++) { const historyItem = filteredHistory[i]; @@ -53,9 +62,14 @@ export function constructMessages( // Gather context items for user messages let content = normalizeToMessageParts(historyItem.message); - const ctxItems = historyItem.contextItems.map((ctxItem) => { - return { type: "text", text: `${ctxItem.content}\n` } as MessagePart; - }); + const ctxItems = historyItem.contextItems + .map((ctxItem) => { + return { + type: "text", + text: `${ctxItem.content}\n`, + } as TextMessagePart; + }) + .filter((part) => !!part.text.trim()); content = [...ctxItems, ...content]; msgs.push({ @@ -73,6 +87,32 @@ export function constructMessages( } } + const userMessage = findLast(msgs, (msg) => msg.role === "user") as + | UserChatMessage + | undefined; + const systemMessage = getSystemMessageWithRules({ + baseSystemMessage: baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE, + rules, + userMessage, + currentModel: modelName, + }); + if (systemMessage.trim()) { + msgs.unshift({ + role: "system", + content: systemMessage, + }); + } + + // We dispatch an empty assistant chat message to the history on submission. Don't send it + const lastMessage = msgs.at(-1); + if ( + lastMessage && + lastMessage.role === "assistant" && + messageIsEmpty(lastMessage) + ) { + msgs.pop(); + } + // Remove the "id" from all of the messages return msgs.map((msg) => { const { id, ...rest } = msg as any; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 2fc01f9b8..fbe532208 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -1,13 +1,7 @@ import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; -import { - ChatMessage, - MessageContent, - MessagePart, - UserChatMessage, -} from "../index.js"; +import { ChatMessage, MessageContent, MessagePart } from "../index.js"; -import { Rule } from "@continuedev/config-yaml"; import { renderChatMessage } from "../util/messageContent.js"; import { AsyncEncoder, @@ -17,8 +11,12 @@ import { import { autodetectTemplateType } from "./autodetect.js"; import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js"; import llamaTokenizer from "./llamaTokenizer.js"; -import { isRuleActive } from "./rules/isRuleActive.js"; -import { extractPathsFromCodeBlocks } from "./utils/extractPathsFromCodeBlocks.js"; +import { + addSpaceToAnyEmptyMessages, + chatMessageIsEmpty, + flattenMessages, + messageHasToolCalls, +} from "./messages.js"; interface Encoding { encode: Tiktoken["encode"]; decode: Tiktoken["decode"]; @@ -126,31 +124,6 @@ function countTokens( } } -function messageHasToolCalls(msg: ChatMessage): boolean { - return msg.role === "assistant" && !!msg.toolCalls; -} - -export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { - const flattened: ChatMessage[] = []; - - for (let i = 0; i < msgs.length; i++) { - const msg = msgs[i]; - - if ( - flattened.length > 0 && - flattened[flattened.length - 1].role === msg.role && - !messageHasToolCalls(msg) && - !messageHasToolCalls(flattened[flattened.length - 1]) - ) { - flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`; - } else { - flattened.push(msg); - } - } - - return flattened; -} - function countChatMessageTokens( modelName: string, chatMessage: ChatMessage, @@ -248,10 +221,19 @@ function summarize(message: ChatMessage): string { function pruneChatHistory( modelName: string, - chatHistory: ChatMessage[], + msgs: ChatMessage[], contextLength: number, tokensForCompletion: number, ): ChatMessage[] { + // Move system message to 2nd to last to give it priority + const systemMessage = msgs.find((msg) => msg.role === "system"); + const chatHistory: ChatMessage[] = msgs.filter( + (msg) => msg.role !== "system", + ); + if (systemMessage) { + chatHistory.splice(-1, 0, systemMessage); + } + let totalTokens = tokensForCompletion + chatHistory.reduce((acc, message) => { @@ -364,147 +346,17 @@ function pruneChatHistory( ); totalTokens = contextLength; } - return chatHistory; -} -function messageIsEmpty(message: ChatMessage): boolean { - if (typeof message.content === "string") { - return message.content.trim() === ""; - } - if (Array.isArray(message.content)) { - return message.content.every( - (item) => item.type === "text" && item.text?.trim() === "", - ); - } - return false; -} - -function addSpaceToAnyEmptyMessages(messages: ChatMessage[]): ChatMessage[] { - return messages.map((message) => { - if (messageIsEmpty(message)) { - message.content = " "; - } - return message; - }); -} - -function chatMessageIsEmpty(message: ChatMessage): boolean { - switch (message.role) { - case "system": - case "user": - return ( - typeof message.content === "string" && message.content.trim() === "" - ); - case "assistant": - return ( - typeof message.content === "string" && - message.content.trim() === "" && - !message.toolCalls - ); - case "thinking": - case "tool": - return false; - } -} - -function addSystemMessage({ - messages, - systemMessage, - originalMessages, -}: { - messages: ChatMessage[]; - systemMessage: string | undefined; - originalMessages: ChatMessage[] | undefined; -}): ChatMessage[] { + // put system message back if applicable if ( - !(systemMessage && systemMessage.trim() !== "") && - originalMessages?.[0]?.role !== "system" + chatHistory.length > 1 && + chatHistory[chatHistory.length - 2].role === "system" ) { - return messages; + const movedSystemMessage = chatHistory.splice(-2, 1)[0]; + chatHistory.unshift(movedSystemMessage); } - let content = ""; - if (originalMessages?.[0]?.role === "system") { - content = renderChatMessage(originalMessages[0]); - } - if (systemMessage && systemMessage.trim() !== "") { - const shouldAddNewLines = content !== ""; - if (shouldAddNewLines) { - content += "\n\n"; - } - content += systemMessage; - } - - const systemChatMsg: ChatMessage = { - role: "system", - content, - }; - // Insert as second to last - messages.splice(-1, 0, systemChatMsg); - return messages; -} - -function getMessageStringContent(message?: UserChatMessage): string { - if (!message) { - return ""; - } - - if (typeof message.content === "string") { - return message.content; - } - - // Handle MessagePart array - return message.content - .map((part) => { - if (part.type === "text") { - return part.text; - } - - return ""; - }) - .join("\n"); -} - -const getSystemMessage = ({ - userMessage, - rules, - currentModel, -}: { - userMessage?: UserChatMessage; - rules: Rule[]; - currentModel: string; -}) => { - const messageStringContent = getMessageStringContent(userMessage); - const filePathsFromMessage = extractPathsFromCodeBlocks(messageStringContent); - - return rules - .filter((rule) => { - return isRuleActive({ - rule, - activePaths: filePathsFromMessage, - currentModel, - }); - }) - .map((rule) => { - if (typeof rule === "string") { - return rule; - } - return rule.rule; - }) - .join("\n"); -}; - -function getLastUserMessage( - messages: ChatMessage[], -): UserChatMessage | undefined { - // Iterate backwards through messages to find the last user message - for (let i = messages.length - 1; i >= 0; i--) { - if (messages[i].role === "user") { - return messages[i] as UserChatMessage; - } - } - - return undefined; + return chatHistory; } function compileChatMessages({ @@ -513,64 +365,19 @@ function compileChatMessages({ contextLength, maxTokens, supportsImages, - prompt, - functions, - systemMessage, - rules, }: { modelName: string; - msgs: ChatMessage[] | undefined; + msgs: ChatMessage[]; contextLength: number; maxTokens: number; supportsImages: boolean; - prompt: string | undefined; - functions: any[] | undefined; - systemMessage: string | undefined; - rules: Rule[]; }): ChatMessage[] { - let msgsCopy = msgs - ? msgs - .map((msg) => ({ ...msg })) - .filter((msg) => !chatMessageIsEmpty(msg) && msg.role !== "system") - : []; + let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m })); + + msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg)); msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); - if (prompt) { - const promptMsg: ChatMessage = { - role: "user", - content: prompt, - }; - msgsCopy.push(promptMsg); - } - - const lastUserMessage = getLastUserMessage(msgsCopy); - - msgsCopy = addSystemMessage({ - messages: msgsCopy, - systemMessage: - systemMessage ?? - getSystemMessage({ - userMessage: lastUserMessage, - rules, - currentModel: modelName, - }), - originalMessages: msgs, - }); - - let functionTokens = 0; - if (functions) { - for (const func of functions) { - functionTokens += countTokens(JSON.stringify(func), modelName); - } - } - - if (maxTokens + functionTokens + TOKEN_BUFFER_FOR_SAFETY >= contextLength) { - throw new Error( - `maxTokens (${maxTokens}) is too close to contextLength (${contextLength}), which doesn't leave room for response. Try increasing the contextLength parameter of the model in your config.json.`, - ); - } - // If images not supported, convert MessagePart[] to string if (!supportsImages) { for (const msg of msgsCopy) { @@ -585,14 +392,9 @@ function compileChatMessages({ modelName, msgsCopy, contextLength, - functionTokens + maxTokens + TOKEN_BUFFER_FOR_SAFETY, + maxTokens + TOKEN_BUFFER_FOR_SAFETY, ); - if (history.length >= 2 && history[history.length - 2].role === "system") { - const movedSystemMessage = history.splice(-2, 1)[0]; - history.unshift(movedSystemMessage); - } - const flattenedHistory = flattenMessages(history); return flattenedHistory; @@ -602,6 +404,7 @@ export { compileChatMessages, countTokens, countTokensAsync, + flattenMessages, pruneLinesFromBottom, pruneLinesFromTop, pruneRawPromptFromTop, diff --git a/core/llm/index.test.ts b/core/llm/index.test.ts index 7f535d1fd..7584e2122 100644 --- a/core/llm/index.test.ts +++ b/core/llm/index.test.ts @@ -35,7 +35,6 @@ describe("BaseLLM", () => { const options: LLMOptions = { model: "gpt-3.5-turbo", uniqueId: "testId", - systemMessage: "Test System Message", contextLength: 1024, completionOptions: { model: "some-model", @@ -62,7 +61,6 @@ describe("BaseLLM", () => { expect(instance.title).toBeDefined(); expect(instance.uniqueId).toBe("testId"); expect(instance.model).toBe("gpt-3.5-turbo"); - expect(instance.systemMessage).toBe("Test System Message"); expect(instance.contextLength).toBe(1024); expect(instance.completionOptions.maxTokens).toBe(150); expect(instance.requestOptions).toEqual({}); diff --git a/core/llm/index.ts b/core/llm/index.ts index a380bd5de..e3d8004bb 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -1,4 +1,4 @@ -import { ModelRole, Rule } from "@continuedev/config-yaml"; +import { ModelRole } from "@continuedev/config-yaml"; import { fetchwithRequestOptions } from "@continuedev/fetch"; import { findLlmInfo } from "@continuedev/llm-info"; import { @@ -126,7 +126,6 @@ export abstract class BaseLLM implements ILLM { model: string; title?: string; - systemMessage?: string; baseChatSystemMessage?: string; contextLength: number; maxStopWords?: number | undefined; @@ -149,7 +148,6 @@ export abstract class BaseLLM implements ILLM { cacheBehavior?: CacheBehavior; capabilities?: ModelCapability; roles?: ModelRole[]; - rules?: Rule[]; deployment?: string; apiVersion?: string; @@ -195,7 +193,6 @@ export abstract class BaseLLM implements ILLM { this.title = options.title; this.uniqueId = options.uniqueId ?? "None"; - this.systemMessage = options.systemMessage; this.baseChatSystemMessage = options.baseChatSystemMessage; this.contextLength = options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH; @@ -250,7 +247,6 @@ export abstract class BaseLLM implements ILLM { this.accountId = options.accountId; this.capabilities = options.capabilities; this.roles = options.roles; - this.rules = options.rules; this.deployment = options.deployment; this.apiVersion = options.apiVersion; @@ -288,7 +284,6 @@ export abstract class BaseLLM implements ILLM { private _compileChatMessages( options: CompletionOptions, messages: ChatMessage[], - functions?: any[], ) { let contextLength = this.contextLength; if ( @@ -305,10 +300,6 @@ export abstract class BaseLLM implements ILLM { contextLength, maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, supportsImages: this.supportsImages(), - prompt: undefined, - functions, - systemMessage: this.systemMessage, - rules: this.rules ?? [], }); } @@ -317,45 +308,13 @@ export abstract class BaseLLM implements ILLM { return prompt; } + // NOTE system message no longer supported here + const msgs: ChatMessage[] = [{ role: "user", content: prompt }]; - const systemMessage = this.systemMessage; - if (systemMessage) { - msgs.unshift({ role: "system", content: systemMessage }); - } - return this.templateMessages(msgs); } - private _compilePromptForLog( - prompt: string, - completionOptions: CompletionOptions, - ): string { - const completionOptionsLog = JSON.stringify( - { - contextLength: this.contextLength, - ...completionOptions, - }, - null, - 2, - ); - - let requestOptionsLog = ""; - if (this.requestOptions) { - requestOptionsLog = JSON.stringify(this.requestOptions, null, 2); - } - - return ( - "##### Completion options #####\n" + - completionOptionsLog + - (requestOptionsLog - ? "\n\n##### Request options #####\n" + requestOptionsLog - : "") + - "\n\n##### Prompt #####\n" + - prompt - ); - } - private _logEnd( model: string, prompt: string, diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index cd48ef41b..5bec42d49 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -30,15 +30,17 @@ class Anthropic extends BaseLLM { description: tool.function.description, input_schema: tool.function.parameters, })), - thinking: options.reasoning ? { - type: "enabled", - budget_tokens: options.reasoningBudgetTokens, - } : undefined, + thinking: options.reasoning + ? { + type: "enabled", + budget_tokens: options.reasoningBudgetTokens, + } + : undefined, tool_choice: options.toolChoice ? { - type: "tool", - name: options.toolChoice.function.name, - } + type: "tool", + name: options.toolChoice.function.name, + } : undefined, }; @@ -70,19 +72,23 @@ class Anthropic extends BaseLLM { } else if (message.role === "thinking" && !message.redactedThinking) { return { role: "assistant", - content: [{ - type: "thinking", - thinking: message.content, - signature: message.signature - }] + content: [ + { + type: "thinking", + thinking: message.content, + signature: message.signature, + }, + ], }; } else if (message.role === "thinking" && message.redactedThinking) { return { role: "assistant", - content: [{ - type: "redacted_thinking", - data: message.redactedThinking - }] + content: [ + { + type: "redacted_thinking", + data: message.redactedThinking, + }, + ], }; } @@ -172,11 +178,12 @@ class Anthropic extends BaseLLM { ); } - const shouldCacheSystemMessage = - !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; - const systemMessage: string = stripImages( + const systemMessage = stripImages( messages.filter((m) => m.role === "system")[0]?.content ?? "", ); + const shouldCacheSystemMessage = !!( + this.cacheBehavior?.cacheSystemMessage && systemMessage + ); const msgs = this.convertMessages(messages); const response = await this.fetch(new URL("messages", this.apiBase), { @@ -195,12 +202,12 @@ class Anthropic extends BaseLLM { messages: msgs, system: shouldCacheSystemMessage ? [ - { - type: "text", - text: this.systemMessage, - cache_control: { type: "ephemeral" }, - }, - ] + { + type: "text", + text: systemMessage, + cache_control: { type: "ephemeral" }, + }, + ] : systemMessage, }), signal, @@ -240,7 +247,11 @@ class Anthropic extends BaseLLM { // handle redacted thinking if (value.content_block.type === "redacted_thinking") { console.log("redacted thinking", value.content_block.data); - yield { role: "thinking", content: "", redactedThinking: value.content_block.data }; + yield { + role: "thinking", + content: "", + redactedThinking: value.content_block.data, + }; } break; case "content_block_delta": @@ -253,7 +264,11 @@ class Anthropic extends BaseLLM { yield { role: "thinking", content: value.delta.thinking }; break; case "signature_delta": - yield { role: "thinking", content: "", signature: value.delta.signature }; + yield { + role: "thinking", + content: "", + signature: value.delta.signature, + }; break; case "input_json_delta": if (!lastToolUseId || !lastToolUseName) { diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index b9517bb59..430e4a93b 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -14,10 +14,10 @@ import { CompletionOptions, LLMOptions, } from "../../index.js"; -import { getSecureID } from "../utils/getSecureID.js"; -import { renderChatMessage } from "../../util/messageContent.js"; +import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js"; +import { getSecureID } from "../utils/getSecureID.js"; interface ModelConfig { formatPayload: (text: string) => any; @@ -285,10 +285,13 @@ class Bedrock extends BaseLLM { messages: ChatMessage[], options: CompletionOptions, ): any { + const systemMessage = stripImages( + messages.find((m) => m.role === "system")?.content ?? "", + ); const convertedMessages = this._convertMessages(messages); const shouldCacheSystemMessage = - !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; + !!systemMessage && this.cacheBehavior?.cacheSystemMessage; const enablePromptCaching = shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation; @@ -305,10 +308,10 @@ class Bedrock extends BaseLLM { return { modelId: options.model, messages: convertedMessages, - system: this.systemMessage + system: systemMessage ? shouldCacheSystemMessage - ? [{ text: this.systemMessage }, { cachePoint: { type: "default" } }] - : [{ text: this.systemMessage }] + ? [{ text: systemMessage }, { cachePoint: { type: "default" } }] + : [{ text: systemMessage }] : undefined, toolConfig: supportsTools && options.tools diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index 86834cb74..ecc9c5208 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -4,7 +4,7 @@ import { CompletionOptions, LLMOptions, } from "../../index.js"; -import { renderChatMessage } from "../../util/messageContent.js"; +import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamJSON } from "../stream.js"; @@ -67,6 +67,11 @@ class Cohere extends BaseLLM { ...this.requestOptions?.headers, }; + let preamble: string | undefined = undefined; + const systemMessage = messages.find((m) => m.role === "system")?.content; + if (systemMessage) { + preamble = stripImages(systemMessage); + } const resp = await this.fetch(new URL("chat", this.apiBase), { method: "POST", headers, @@ -74,7 +79,7 @@ class Cohere extends BaseLLM { ...this._convertArgs(options), message: messages.pop()?.content, chat_history: this._convertMessages(messages), - preamble: this.systemMessage, + preamble, }), signal, }); diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index b912564dc..1e3c35449 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -8,16 +8,17 @@ import { TextMessagePart, ToolCallDelta, } from "../../index.js"; -import { renderChatMessage } from "../../util/messageContent.js"; +import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; import { - convertContinueToolToGeminiFunction, + GeminiChatContent, GeminiChatContentPart, GeminiChatRequestBody, GeminiChatResponse, GeminiGenerationConfig, GeminiToolFunctionDeclaration, + convertContinueToolToGeminiFunction, } from "./gemini-types"; class Gemini extends BaseLLM { @@ -156,14 +157,8 @@ class Gemini extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - // Ensure this.apiBase is used if available, otherwise use default - const apiBase = - this.apiBase || - Gemini.defaultOptions?.apiBase || - "https://generativelanguage.googleapis.com/v1beta/"; // Determine if it's a v1 API call based on apiBase - const isV1API = apiBase.includes("/v1/"); + const isV1API = this.apiBase?.includes("/v1/"); - // Conditionally apply removeSystemMessage const convertedMsgs = isV1API ? this.removeSystemMessage(messages) : messages; @@ -215,6 +210,9 @@ class Gemini extends BaseLLM { }); } }); + const systemMessage = messages.find( + (msg) => msg.role === "system", + )?.content; const body: GeminiChatRequestBody = { contents: messages @@ -242,28 +240,35 @@ class Gemini extends BaseLLM { ], }; } - const assistantMsg = { - role: - msg.role === "assistant" ? ("model" as const) : ("user" as const), + if (msg.role === "assistant") { + const assistantMsg: GeminiChatContent = { + role: "model", + parts: + typeof msg.content === "string" + ? [{ text: msg.content }] + : msg.content.map(this.continuePartToGeminiPart), + }; + if (msg.toolCalls) { + msg.toolCalls.forEach((toolCall) => { + if (toolCall.function?.name && toolCall.function?.arguments) { + assistantMsg.parts.push({ + functionCall: { + name: toolCall.function.name, + args: JSON.parse(toolCall.function.arguments), + }, + }); + } + }); + } + return assistantMsg; + } + return { + role: "user", parts: typeof msg.content === "string" ? [{ text: msg.content }] : msg.content.map(this.continuePartToGeminiPart), }; - if (msg.role === "assistant" && msg.toolCalls) { - msg.toolCalls.forEach((toolCall) => { - if (toolCall.function?.name && toolCall.function?.arguments) { - assistantMsg.parts.push({ - functionCall: { - name: toolCall.function.name, - args: JSON.parse(toolCall.function.arguments), - }, - }); - } - }); - } - - return assistantMsg; }), }; if (options) { @@ -272,8 +277,10 @@ class Gemini extends BaseLLM { // https://ai.google.dev/gemini-api/docs/api-versions if (!isV1API) { - if (this.systemMessage) { - body.systemInstruction = { parts: [{ text: this.systemMessage }] }; + if (systemMessage) { + body.systemInstruction = { + parts: [{ text: stripImages(systemMessage) }], + }; } // Convert and add tools if present if (options.tools?.length) { @@ -394,10 +401,8 @@ class Gemini extends BaseLLM { `models/${options.model}:streamGenerateContent?key=${this.apiKey}`, this.apiBase, ); - // This feels hacky to repeat code from above function but was the quickest - // way to ensure system message re-formatting isn't done if user has specified v1 - const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase - const isV1API = apiBase.includes("/v1/"); + + const isV1API = !!this.apiBase?.includes("/v1/"); // Convert chat messages to contents const body = this.prepareBody(messages, options, isV1API); diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 139d033ab..6ac50795a 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -288,7 +288,10 @@ class OpenAI extends BaseLLM { // To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs // In practice, setting this to true and asking for multiple tool calls // leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}' - body.parallel_tool_calls = false; + // o3 does not support this + if (!body.model.startsWith("o3")) { + body.parallel_tool_calls = false; + } } return body; diff --git a/core/llm/llms/Replicate.ts b/core/llm/llms/Replicate.ts index c394ed29f..44a15c61d 100644 --- a/core/llm/llms/Replicate.ts +++ b/core/llm/llms/Replicate.ts @@ -80,16 +80,6 @@ class Replicate extends BaseLLM { } } } - - // protected async *_streamChat( - // messages: ChatMessage[], - // options: CompletionOptions - // ): AsyncGenerator { - // const resp = await this.complete( - // stripImages(messages[0]?.content || ""), - // options - // ); - // } } export default Replicate; diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 1b75cb690..84f471c6f 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -1,7 +1,7 @@ import { GoogleAuth } from "google-auth-library"; import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; -import { renderChatMessage } from "../../util/messageContent.js"; +import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse, streamSse } from "../stream.js"; @@ -11,7 +11,7 @@ import Gemini from "./Gemini.js"; class VertexAI extends BaseLLM { static providerName = "vertexai"; declare apiBase: string; - declare vertexProvider: string; + declare vertexProvider: "mistral" | "anthropic" | "gemini" | "unknown"; declare anthropicInstance: Anthropic; declare geminiInstance: Gemini; @@ -92,13 +92,13 @@ class VertexAI extends BaseLLM { messages: ChatMessage[], options: CompletionOptions, ): AsyncGenerator { - const shouldCacheSystemMessage = - !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; - const filteredSystemMessages : ChatMessage[] = messages.filter((m) => m.role === "system"); - let systemMessage: string = ""; - if(filteredSystemMessages.length > 0) { - systemMessage = renderChatMessage(filteredSystemMessages[0]); - } + const systemMessage = stripImages( + messages.filter((m) => m.role === "system")[0]?.content ?? "", + ); + const shouldCacheSystemMessage = !!( + this.cacheBehavior?.cacheSystemMessage && systemMessage + ); + const apiURL = new URL( `publishers/anthropic/models/${options.model}:streamRawPredict`, this.apiBase, @@ -118,7 +118,7 @@ class VertexAI extends BaseLLM { ? [ { type: "text", - text: this.systemMessage, + text: systemMessage, cache_control: { type: "ephemeral" }, }, ] @@ -142,8 +142,7 @@ class VertexAI extends BaseLLM { } } - //Gemini - + // Gemini private async *streamChatGemini( messages: ChatMessage[], options: CompletionOptions, @@ -306,7 +305,7 @@ class VertexAI extends BaseLLM { yield (await resp.json()).predictions[0].content; } - //Manager functions + // Manager functions protected async *_streamChat( messages: ChatMessage[], @@ -328,6 +327,8 @@ class VertexAI extends BaseLLM { } else { if (options.model.includes("bison")) { yield* this.streamChatBison(convertedMsgs, options); + } else { + throw new Error(`Unsupported model: ${options.model}`); } } } diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 7f1fe2e0c..ac91d3fa9 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -1,4 +1,9 @@ -import { ChatMessage, Chunk, CompletionOptions, LLMOptions } from "../../index.js"; +import { + ChatMessage, + Chunk, + CompletionOptions, + LLMOptions, +} from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; @@ -139,24 +144,24 @@ class WatsonX extends BaseLLM { } protected async updateWatsonxToken() { - var now = new Date().getTime() / 1000; - if ( - watsonxToken === undefined || - now > watsonxToken.expiration || - watsonxToken.token === undefined - ) { - watsonxToken = await this.getBearerToken(); - } else { - console.log( - `Reusing token (expires in ${ - (watsonxToken.expiration - now) / 60 - } mins)`, - ); - } - if (watsonxToken.token === undefined) { - throw new Error("Something went wrong. Check your credentials, please."); - } + var now = new Date().getTime() / 1000; + if ( + watsonxToken === undefined || + now > watsonxToken.expiration || + watsonxToken.token === undefined + ) { + watsonxToken = await this.getBearerToken(); + } else { + console.log( + `Reusing token (expires in ${ + (watsonxToken.expiration - now) / 60 + } mins)`, + ); } + if (watsonxToken.token === undefined) { + throw new Error("Something went wrong. Check your credentials, please."); + } + } protected async _complete( prompt: string, @@ -312,64 +317,60 @@ class WatsonX extends BaseLLM { return embeddings.map((e: any) => e.embedding); } - async rerank(query: string, chunks: Chunk[]): Promise { - if (!query || !chunks.length) { - throw new Error("Query and chunks must not be empty"); - } - try { - await this.updateWatsonxToken(); - - const headers = { - "Content-Type": "application/json", - Authorization: `${ - watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" - } ${watsonxToken.token}`, - }; - - const payload: any = { - inputs: chunks.map((chunk) => ({ text: chunk.content })), - query: query, - parameters: { - truncate_input_tokens: 500, - return_options: { - top_n: chunks.length - }, + if (!query || !chunks.length) { + throw new Error("Query and chunks must not be empty"); + } + try { + await this.updateWatsonxToken(); + + const headers = { + "Content-Type": "application/json", + Authorization: `${ + watsonxToken.expiration === -1 ? "ZenApiKey" : "Bearer" + } ${watsonxToken.token}`, + }; + + const payload: any = { + inputs: chunks.map((chunk) => ({ text: chunk.content })), + query: query, + parameters: { + truncate_input_tokens: 500, + return_options: { + top_n: chunks.length, }, - model_id: this.model, - project_id: this.projectId, - }; + }, + model_id: this.model, + project_id: this.projectId, + }; - const resp = await this.fetch( - new URL( - `${this.apiBase}/ml/v1/text/rerank?version=${this.apiVersion}`, - ), - { - method: "POST", - headers: headers, - body: JSON.stringify(payload), - }, - ); + const resp = await this.fetch( + new URL(`${this.apiBase}/ml/v1/text/rerank?version=${this.apiVersion}`), + { + method: "POST", + headers: headers, + body: JSON.stringify(payload), + }, + ); - if (!resp.ok) { - throw new Error(`Failed to rerank chunks: ${await resp.text()}`); - } - const data = await resp.json(); - const ranking = data.results; - - if (!ranking) { - throw new Error("Empty response received from Watsonx"); - } - - // Sort results by index to maintain original order - return ranking - .sort((a: any, b: any) => a.index - b.index) - .map((result: any) => result.score); - - } catch (error) { - console.error("Error in WatsonxReranker.rerank:", error); - throw error; + if (!resp.ok) { + throw new Error(`Failed to rerank chunks: ${await resp.text()}`); } + const data = await resp.json(); + const ranking = data.results; + + if (!ranking) { + throw new Error("Empty response received from Watsonx"); + } + + // Sort results by index to maintain original order + return ranking + .sort((a: any, b: any) => a.index - b.index) + .map((result: any) => result.score); + } catch (error) { + console.error("Error in WatsonxReranker.rerank:", error); + throw error; + } } } diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index cef09098c..c932b5db4 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -3,10 +3,11 @@ import { IdeSettings, ILLM, ILLMLogger, + JSONModelDescription, LLMOptions, - ModelDescription, } from "../.."; import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString"; +import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages"; import { BaseLLM } from "../index"; import Anthropic from "./Anthropic"; @@ -27,6 +28,7 @@ import FunctionNetwork from "./FunctionNetwork"; import Gemini from "./Gemini"; import Groq from "./Groq"; import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI"; +import HuggingFaceTEIEmbeddingsProvider from "./HuggingFaceTEI"; import HuggingFaceTGI from "./HuggingFaceTGI"; import Inception from "./Inception"; import Kindo from "./Kindo"; @@ -56,6 +58,7 @@ import TextGenWebUI from "./TextGenWebUI"; import Together from "./Together"; import VertexAI from "./VertexAI"; import Vllm from "./Vllm"; +import Voyage from "./Voyage"; import WatsonX from "./WatsonX"; import xAI from "./xAI"; @@ -73,6 +76,7 @@ export const LLMClasses = [ Together, Novita, HuggingFaceTGI, + HuggingFaceTEIEmbeddingsProvider, HuggingFaceInferenceAPI, Kindo, LlamaCpp, @@ -109,16 +113,16 @@ export const LLMClasses = [ Scaleway, Relace, Inception, + Voyage, ]; export async function llmFromDescription( - desc: ModelDescription, + desc: JSONModelDescription, readFile: (filepath: string) => Promise, uniqueId: string, ideSettings: IdeSettings, llmLogger: ILLMLogger, completionOptions?: BaseCompletionOptions, - systemMessage?: string, ): Promise { const cls = LLMClasses.find((llm) => llm.providerName === desc.provider); @@ -131,9 +135,15 @@ export async function llmFromDescription( ...desc.completionOptions, }; - systemMessage = desc.systemMessage ?? systemMessage; - if (systemMessage !== undefined) { - systemMessage = await renderTemplatedString(systemMessage, readFile, {}); + let baseChatSystemMessage: string | undefined = undefined; + if (desc.systemMessage !== undefined) { + baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE; + baseChatSystemMessage += "\n\n"; + baseChatSystemMessage += await renderTemplatedString( + desc.systemMessage, + readFile, + {}, + ); } let options: LLMOptions = { @@ -145,7 +155,7 @@ export async function llmFromDescription( finalCompletionOptions.maxTokens ?? cls.defaultOptions?.completionOptions?.maxTokens, }, - systemMessage, + baseChatSystemMessage, logger: llmLogger, uniqueId, }; diff --git a/core/llm/flattenMessages.test.ts b/core/llm/messages.test.ts similarity index 100% rename from core/llm/flattenMessages.test.ts rename to core/llm/messages.test.ts diff --git a/core/llm/messages.ts b/core/llm/messages.ts new file mode 100644 index 000000000..d3f7ab477 --- /dev/null +++ b/core/llm/messages.ts @@ -0,0 +1,69 @@ +import { ChatMessage } from ".."; + +export function messageHasToolCalls(msg: ChatMessage): boolean { + return msg.role === "assistant" && !!msg.toolCalls; +} + +export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { + const flattened: ChatMessage[] = []; + + for (let i = 0; i < msgs.length; i++) { + const msg = msgs[i]; + + if ( + flattened.length > 0 && + flattened[flattened.length - 1].role === msg.role && + !messageHasToolCalls(msg) && + !messageHasToolCalls(flattened[flattened.length - 1]) + ) { + flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`; + } else { + flattened.push(msg); + } + } + + return flattened; +} + +export function messageIsEmpty(message: ChatMessage): boolean { + if (typeof message.content === "string") { + return message.content.trim() === ""; + } + if (Array.isArray(message.content)) { + return message.content.every( + (item) => item.type === "text" && item.text?.trim() === "", + ); + } + return false; +} + +// some providers don't support empty messages +export function addSpaceToAnyEmptyMessages( + messages: ChatMessage[], +): ChatMessage[] { + return messages.map((message) => { + if (messageIsEmpty(message)) { + message.content = " "; + } + return message; + }); +} + +export function chatMessageIsEmpty(message: ChatMessage): boolean { + switch (message.role) { + case "system": + case "user": + return ( + typeof message.content === "string" && message.content.trim() === "" + ); + case "assistant": + return ( + typeof message.content === "string" && + message.content.trim() === "" && + !message.toolCalls + ); + case "thinking": + case "tool": + return false; + } +} diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts new file mode 100644 index 000000000..2387145d4 --- /dev/null +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -0,0 +1,35 @@ +import { RuleWithSource, UserChatMessage } from "../.."; +import { renderChatMessage } from "../../util/messageContent"; +import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks"; +import { isRuleActive } from "./isRuleActive"; + +export const getSystemMessageWithRules = ({ + baseSystemMessage, + userMessage, + rules, + currentModel, +}: { + baseSystemMessage?: string; + userMessage: UserChatMessage | undefined; + rules: RuleWithSource[]; + currentModel: string; +}) => { + const filePathsFromMessage = userMessage + ? extractPathsFromCodeBlocks(renderChatMessage(userMessage)) + : []; + + let systemMessage = baseSystemMessage ?? ""; + for (const rule of rules) { + if ( + isRuleActive({ + rule, + activePaths: filePathsFromMessage, + currentModel, + }) + ) { + systemMessage += `\n\n${rule.rule}`; + } + } + + return systemMessage; +}; diff --git a/core/llm/rules/isRuleActive.test.ts b/core/llm/rules/isRuleActive.test.ts index f50b9972a..89e06e148 100644 --- a/core/llm/rules/isRuleActive.test.ts +++ b/core/llm/rules/isRuleActive.test.ts @@ -1,10 +1,12 @@ +import { RuleWithSource } from "../.."; import { isRuleActive } from "./isRuleActive"; describe("isRuleActive", () => { - const rule = { + const rule: RuleWithSource = { name: "My Rule", rule: "Do no harm", if: '${{ contains(current.model.model, "claude-3-7-sonnet") and glob("*.tsx") }}', + source: "rules-block", }; it("should return false when activePaths is empty", () => { diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts index 47125c644..9c80f67ec 100644 --- a/core/llm/rules/isRuleActive.ts +++ b/core/llm/rules/isRuleActive.ts @@ -1,6 +1,6 @@ -import { Rule } from "@continuedev/config-yaml"; import { compileExpression } from "filtrex"; import { minimatch } from "minimatch"; +import { RuleWithSource } from "../.."; const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/; @@ -52,14 +52,10 @@ export const isRuleActive = ({ activePaths, currentModel, }: { - rule: Rule; + rule: RuleWithSource; activePaths: string[]; currentModel: string; }): boolean => { - if (typeof rule === "string") { - return true; - } - if (rule.if) { return evaluateIf({ condition: rule.if, activePaths, currentModel }); } diff --git a/core/package-lock.json b/core/package-lock.json index 494992220..34ac539aa 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -108,9 +108,9 @@ "node": ">=20.11.0" } }, - "../packages/config-yaml": { - "name": "@continuedev/config-yaml", + "../../../../../documents/code/continuedev/continue/packages/config-yaml": { "version": "1.0.78", + "extraneous": true, "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -129,6 +129,30 @@ "ts-node": "^10.9.2" } }, + "../../../../dallin/documents/code/continuedev/continue/packages/config-yaml": { + "extraneous": true + }, + "../packages/config-yaml": { + "version": "1.0.78", + "license": "Apache-2.0", + "dependencies": { + "@continuedev/config-types": "^1.0.14", + "yaml": "^2.6.1", + "zod": "^3.24.2" + }, + "bin": { + "config-yaml": "dist/cli.js" + }, + "devDependencies": { + "@types/jest": "^29.5.14", + "@types/node": "^20.0.0", + "cross-env": "^7.0.3", + "jest": "^29.7.0", + "ts-jest": "^29.2.3", + "ts-node": "^10.9.2", + "zod-to-json-schema": "^3.24.5" + } + }, "node_modules/@75lb/deep-merge": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.2.tgz", @@ -2877,118 +2901,6 @@ "node": ">=14.21.3" } }, - "node_modules/@biomejs/cli-darwin-x64": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-1.6.4.tgz", - "integrity": "sha512-uo1zgM7jvzcoDpF6dbGizejDLCqNpUIRkCj/oEK0PB0NUw8re/cn1EnxuOLZqDpn+8G75COLQTOx8UQIBBN/Kg==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-linux-arm64": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-1.6.4.tgz", - "integrity": "sha512-wAOieaMNIpLrxGc2/xNvM//CIZg7ueWy3V5A4T7gDZ3OL/Go27EKE59a+vMKsBCYmTt7jFl4yHz0TUkUbodA/w==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-linux-arm64-musl": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-1.6.4.tgz", - "integrity": "sha512-Hp8Jwt6rjj0wCcYAEN6/cfwrrPLLlGOXZ56Lei4Pt4jy39+UuPeAVFPeclrrCfxyL1wQ2xPrhd/saTHSL6DoJg==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-linux-x64": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-1.6.4.tgz", - "integrity": "sha512-qTWhuIw+/ePvOkjE9Zxf5OqSCYxtAvcTJtVmZT8YQnmY2I62JKNV2m7tf6O5ViKZUOP0mOQ6NgqHKcHH1eT8jw==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-linux-x64-musl": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-1.6.4.tgz", - "integrity": "sha512-wqi0hr8KAx5kBO0B+m5u8QqiYFFBJOSJVSuRqTeGWW+GYLVUtXNidykNqf1JsW6jJDpbkSp2xHKE/bTlVaG2Kg==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-win32-arm64": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-1.6.4.tgz", - "integrity": "sha512-Wp3FiEeF6v6C5qMfLkHwf4YsoNHr/n0efvoC8jCKO/kX05OXaVExj+1uVQ1eGT7Pvx0XVm/TLprRO0vq/V6UzA==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-win32-x64": { - "version": "1.6.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-1.6.4.tgz", - "integrity": "sha512-mz183Di5hTSGP7KjNWEhivcP1wnHLGmOxEROvoFsIxMYtDhzJDad4k5gI/1JbmA0xe4n52vsgqo09tBhrMT/Zg==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=14.21.3" - } - }, "node_modules/@continuedev/config-types": { "version": "1.0.14", "resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.14.tgz", @@ -3033,52 +2945,17 @@ "zod": "^3.24.2" } }, - "node_modules/@esbuild/android-arm": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.19.tgz", - "integrity": "sha512-rIKddzqhmav7MSmoFCmDIb6e2W57geRsM94gV2l38fzhXMwq7hZoClug9USI2pFRGL06f4IOPHHpFNOkWieR8A==", - "cpu": [ - "arm" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.17.19.tgz", - "integrity": "sha512-KBMWvEZooR7+kzY0BtbTQn0OAYY7CsiydT63pVEaPtVYF0hXbUaOyZog37DKxK7NF3XacBJOpYT4adIJh+avxA==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.17.19.tgz", - "integrity": "sha512-uUTTc4xGNDT7YSArp/zbtmbhO0uEEK9/ETW29Wk1thYUJBz3IVnvgEiEwEa9IeLyvnpKrWK64Utw2bgUmDveww==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=12" + "node_modules/@continuedev/openai-adapters/node_modules/@continuedev/config-yaml": { + "version": "1.0.86", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.86.tgz", + "integrity": "sha512-X0H1iPunFcqxgTcoS87EvbqNHjfkfidWt8rQ2CU5A8iBzPSDI/jdkok0Bm0MjgzgZuXbR6GxvwMcZcOTiFw1nA==", + "dependencies": { + "@continuedev/config-types": "^1.0.14", + "yaml": "^2.6.1", + "zod": "^3.24.2" + }, + "bin": { + "config-yaml": "dist/cli.js" } }, "node_modules/@esbuild/darwin-arm64": { @@ -3097,294 +2974,6 @@ "node": ">=12" } }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.19.tgz", - "integrity": "sha512-IJM4JJsLhRYr9xdtLytPLSH9k/oxR3boaUIYiHkAawtwNOXKE8KoU8tMvryogdcT8AU+Bflmh81Xn6Q0vTZbQw==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.17.19.tgz", - "integrity": "sha512-pBwbc7DufluUeGdjSU5Si+P3SoMF5DQ/F/UmTSb8HXO80ZEAJmrykPyzo1IfNbAoaqw48YRpv8shwd1NoI0jcQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.17.19.tgz", - "integrity": "sha512-4lu+n8Wk0XlajEhbEffdy2xy53dpR06SlzvhGByyg36qJw6Kpfk7cp45DR/62aPH9mtJRmIyrXAS5UWBrJT6TQ==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.17.19.tgz", - "integrity": "sha512-cdmT3KxjlOQ/gZ2cjfrQOtmhG4HJs6hhvm3mWSRDPtZ/lP5oe8FWceS10JaSJC13GBd4eH/haHnqf7hhGNLerA==", - "cpu": [ - "arm" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.19.tgz", - "integrity": "sha512-ct1Tg3WGwd3P+oZYqic+YZF4snNl2bsnMKRkb3ozHmnM0dGWuxcPTTntAF6bOP0Sp4x0PjSF+4uHQ1xvxfRKqg==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.17.19.tgz", - "integrity": "sha512-w4IRhSy1VbsNxHRQpeGCHEmibqdTUx61Vc38APcsRbuVgK0OPEnQ0YD39Brymn96mOx48Y2laBQGqgZ0j9w6SQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.17.19.tgz", - "integrity": "sha512-2iAngUbBPMq439a+z//gE+9WBldoMp1s5GWsUSgqHLzLJ9WoZLZhpwWuym0u0u/4XmZ3gpHmzV84PonE+9IIdQ==", - "cpu": [ - "loong64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.17.19.tgz", - "integrity": "sha512-LKJltc4LVdMKHsrFe4MGNPp0hqDFA1Wpt3jE1gEyM3nKUvOiO//9PheZZHfYRfYl6AwdTH4aTcXSqBerX0ml4A==", - "cpu": [ - "mips64el" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.17.19.tgz", - "integrity": "sha512-/c/DGybs95WXNS8y3Ti/ytqETiW7EU44MEKuCAcpPto3YjQbyK3IQVKfF6nbghD7EcLUGl0NbiL5Rt5DMhn5tg==", - "cpu": [ - "ppc64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.17.19.tgz", - "integrity": "sha512-FC3nUAWhvFoutlhAkgHf8f5HwFWUL6bYdvLc/TTuxKlvLi3+pPzdZiFKSWz/PF30TB1K19SuCxDTI5KcqASJqA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.17.19.tgz", - "integrity": "sha512-IbFsFbxMWLuKEbH+7sTkKzL6NJmG2vRyy6K7JJo55w+8xDk7RElYn6xvXtDW8HCfoKBFK69f3pgBJSUSQPr+4Q==", - "cpu": [ - "s390x" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.19.tgz", - "integrity": "sha512-68ngA9lg2H6zkZcyp22tsVt38mlhWde8l3eJLWkyLrp4HwMUr3c1s/M2t7+kHIhvMjglIBrFpncX1SzMckomGw==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.19.tgz", - "integrity": "sha512-CwFq42rXCR8TYIjIfpXCbRX0rp1jo6cPIUPSaWwzbVI4aOfX96OXY8M6KNmtPcg7QjYeDmN+DD0Wp3LaBOLf4Q==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.19.tgz", - "integrity": "sha512-cnq5brJYrSZ2CF6c35eCmviIN3k3RczmHz8eYaVlNasVqsNY+JKohZU5MKmaOI+KkllCdzOKKdPs762VCPC20g==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.17.19.tgz", - "integrity": "sha512-vCRT7yP3zX+bKWFeP/zdS6SqdWB8OIpaRq/mbXQxTGHnIxspRtigpkUcDMlSCOejlHowLqII7K2JKevwyRP2rg==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.19.tgz", - "integrity": "sha512-yYx+8jwowUstVdorcMdNlzklLYhPxjniHWFKgRqH7IFlUEa0Umu3KuYplf1HUZZ422e3NU9F4LGb+4O0Kdcaag==", - "cpu": [ - "arm64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.17.19.tgz", - "integrity": "sha512-eggDKanJszUtCdlVs0RB+h35wNlb5v4TWEkq4vZcmVt5u/HiDZrTXe2bWFQUez3RgNHwx/x4sk5++4NSSicKkw==", - "cpu": [ - "ia32" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.17.19", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.19.tgz", - "integrity": "sha512-lAhycmKnVOuRYNtRtatQR1LPQf2oYCkRGkSFnseDAKPl8lu5SOsK/e1sXe5a0Pc5kHIHe6P2I/ilntNv2xf3cA==", - "cpu": [ - "x64" - ], - "dev": true, - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=12" - } - }, "node_modules/@eslint-community/eslint-utils": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.4.1.tgz", @@ -4125,54 +3714,6 @@ "darwin" ] }, - "node_modules/@lancedb/vectordb-darwin-x64": { - "version": "0.4.20", - "resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-x64/-/vectordb-darwin-x64-0.4.20.tgz", - "integrity": "sha512-GSYsXE20RIehDu30FjREhJdEzhnwOTV7ZsrSXagStzLY1gr7pyd7sfqxmmUtdD09di7LnQoiM71AOpPTa01YwQ==", - "cpu": [ - "x64" - ], - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@lancedb/vectordb-linux-arm64-gnu": { - "version": "0.4.20", - "resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-arm64-gnu/-/vectordb-linux-arm64-gnu-0.4.20.tgz", - "integrity": "sha512-FpNOjOsz3nJVm6EBGyNgbOW2aFhsWZ/igeY45Z8hbZaaK2YBwrg/DASoNlUzgv6IR8cUaGJ2irNVJfsKR2cG6g==", - "cpu": [ - "arm64" - ], - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@lancedb/vectordb-linux-x64-gnu": { - "version": "0.4.20", - "resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-x64-gnu/-/vectordb-linux-x64-gnu-0.4.20.tgz", - "integrity": "sha512-pOqWjrRZQSrLTlQPkjidRii7NZDw8Xu9pN6ouVu2JAK8n81FXaPtFCyAI+Y3v9GpnYDN0rvD4eQ36aHAVPsa2g==", - "cpu": [ - "x64" - ], - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@lancedb/vectordb-win32-x64-msvc": { - "version": "0.4.20", - "resolved": "https://registry.npmjs.org/@lancedb/vectordb-win32-x64-msvc/-/vectordb-win32-x64-msvc-0.4.20.tgz", - "integrity": "sha512-5J5SsYSJ7jRCmU/sgwVHdrGz43B/7R2T9OEoFTKyVAtqTZdu75rkytXyn9SyEayXVhlUOaw76N0ASm0hAoDS/A==", - "cpu": [ - "x64" - ], - "optional": true, - "os": [ - "win32" - ] - }, "node_modules/@modelcontextprotocol/sdk": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.5.0.tgz", @@ -15977,27 +15518,6 @@ "node": ">=4" } }, - "node_modules/win-export-certificate-and-key": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/win-export-certificate-and-key/-/win-export-certificate-and-key-1.1.2.tgz", - "integrity": "sha512-3Su7Xdt9UR8pZicWQDcGSWNL6We/NzAGxe7AeQ1Z/zAeGHWlTKAh3HemGvIvxLRPsk4NW9D/QL3cL6SIvFcTvQ==", - "hasInstallScript": true, - "optional": true, - "os": [ - "win32" - ], - "dependencies": { - "bindings": "^1.5.0", - "node-addon-api": "^3.1.0", - "node-forge": "^1.2.1" - } - }, - "node_modules/win-export-certificate-and-key/node_modules/node-addon-api": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-3.2.1.tgz", - "integrity": "sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A==", - "optional": true - }, "node_modules/wink-distance": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/wink-distance/-/wink-distance-2.0.2.tgz", diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index fd0b48b2c..a934b2586 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -64,9 +64,6 @@ export function slashCommandFromPromptFileV1( description, prompt, run: async function* (context) { - const originalSystemMessage = context.llm.systemMessage; - context.llm.systemMessage = systemMessage; - const userInput = extractUserInput(context.input, name); const [_, renderedPrompt] = await renderPromptFileV2(prompt, { config: context.config, @@ -86,6 +83,18 @@ export function slashCommandFromPromptFileV1( systemMessage, ); + if (systemMessage) { + const currentSystemMsg = messages.find((msg) => msg.role === "system"); + if (currentSystemMsg) { + currentSystemMsg.content = systemMessage; + } else { + messages.unshift({ + role: "system", + content: systemMessage, + }); + } + } + for await (const chunk of context.llm.streamChat( messages, new AbortController().signal, @@ -93,8 +102,6 @@ export function slashCommandFromPromptFileV1( )) { yield renderChatMessage(chunk); } - - context.llm.systemMessage = originalSystemMessage; }, }; } diff --git a/core/promptFiles/v1/updateChatHistory.ts b/core/promptFiles/v1/updateChatHistory.ts index 04cbcd91b..70b3ce1bd 100644 --- a/core/promptFiles/v1/updateChatHistory.ts +++ b/core/promptFiles/v1/updateChatHistory.ts @@ -1,9 +1,11 @@ +import { ChatMessage } from "../.."; + export function replaceSlashCommandWithPromptInChatHistory( - history: any[], + history: ChatMessage[], commandName: string, renderedPrompt: string, - systemMessage?: string, -) { + systemMessageOverride?: string, +): ChatMessage[] { const messages = [...history]; for (let i = messages.length - 1; i >= 0; i--) { @@ -13,7 +15,12 @@ export function replaceSlashCommandWithPromptInChatHistory( } if (Array.isArray(content)) { - if (content.some((part) => part.text?.startsWith(`/${commandName}`))) { + if ( + content.some( + (part) => + part.type === "text" && part.text?.startsWith(`/${commandName}`), + ) + ) { messages[i] = updateArrayContent( messages[i], commandName, @@ -30,10 +37,12 @@ export function replaceSlashCommandWithPromptInChatHistory( } } - if (systemMessage) { - messages[0]?.role === "system" - ? (messages[0].content = systemMessage) - : messages.unshift({ role: "system", content: systemMessage }); + if (systemMessageOverride) { + if (messages[0]?.role === "system") { + messages[0].content = systemMessageOverride; + } else { + messages.unshift({ role: "system", content: systemMessageOverride }); + } } return messages; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 7f29c2e25..e36e71d0c 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -1,4 +1,5 @@ import { + BlockType, ConfigResult, DevDataLogEvent, ModelRole, @@ -58,6 +59,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, void, ]; + "config/addLocalWorkspaceBlock": [{ blockType: BlockType }, void]; "config/newPromptFile": [undefined, void]; "config/ideSettingsUpdate": [IdeSettings, void]; "config/getSerializedProfileInfo": [ @@ -67,12 +69,20 @@ export type ToCoreFromIdeOrWebviewProtocol = { profileId: string | null; organizations: SerializedOrgWithProfiles[]; selectedOrgId: string; - usingContinueForTeams: boolean; }, ]; "config/deleteModel": [{ title: string }, void]; "config/reload": [undefined, ConfigResult]; - "config/refreshProfiles": [undefined, void]; + "config/refreshProfiles": [ + ( + | undefined + | { + selectOrgId?: string; + selectProfileId?: string; + } + ), + void, + ]; "config/openProfile": [{ profileId: string | undefined }, void]; "config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema]; "config/updateSelectedModel": [ diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 1d854f948..f4a467cb8 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -18,6 +18,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/addModel", "config/newPromptFile", "config/ideSettingsUpdate", + "config/addLocalWorkspaceBlock", "config/getSerializedProfileInfo", "config/deleteModel", "config/refreshProfiles", diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 6b59fa338..74ce31559 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -15,7 +15,6 @@ export type ToWebviewFromIdeOrCoreProtocol = { profileId: string | null; organizations: SerializedOrgWithProfiles[]; selectedOrgId: string | null; - usingContinueForTeams: boolean; }, void, ]; diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index c59eb3320..ff7906e91 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -52,7 +52,6 @@ class FileSystemIde implements IDE { remoteConfigServerUrl: undefined, remoteConfigSyncPeriod: 60, userToken: "", - enableControlServerBeta: false, continueTestEnvironment: "none", pauseCodebaseIndexOnStart: false, }; diff --git a/docs/docs/customize/deep-dives/rules.md b/docs/docs/customize/deep-dives/rules.md index 59f816c15..3143b12cf 100644 --- a/docs/docs/customize/deep-dives/rules.md +++ b/docs/docs/customize/deep-dives/rules.md @@ -5,15 +5,49 @@ keywords: [rules, .continuerules, system, prompt, message] # Rules -Rules are used to provide instructions to **chat** models. They are inserted into the system message for all chat requests. Rules are _only_ used during Chat, they are not used for autocomplete or other roles. +Rules are used to provide instructions to the model for [Chat](../../chat/how-to-use-it.md), [Edit](../../edit/how-to-use-it.md), and [Agent](../../agent/how-to-use-it.md) requests. -## Hub `rules` blocks +Rules are **_NOT_** included in most other requests, such as [autocomplete](./autocomplete.mdx) or [apply](../model-roles/apply.mdx). + +You can view the current rules by clicking the pen icon above the main toolbar: + +![rules input toolbar section](/img/notch-rules.png) + +To form the system message, rules are joined with new lines, in the order they appear in the toolbar. This includes the base chat system message ([see below](#chat-system-message)). + +## `rules` blocks Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. +These blocks are defined using the [`config.yaml` syntax](../../reference.md#rules) and can also be created locally. Rules blocks can be simple text, or have the following properties: + +- `name` (**required**): A display name/title for the rule +- `rule` (**required**): The text content of the rule + +Examples: + +```yaml title="config.yaml" +rules: + - uses: myprofile/my-mood-setter + with: + TONE: consise + - Always annotate Python functions with their parameter and return types + - Always write Google style docstrings for functions and classes + - name: Server-side components + rule: When writing Next.js React components, use server-side components where possible instead of client components. +``` + +## Chat System Message + +Continue includes a simple default system message for [Chat](../../chat/how-to-use-it.md) and [Agent](../../agent/how-to-use-it.md) requests, to help the model provide reliable codeblock formats in its output. + +This can be viewed in the rules section of the toolbar (see above), or visit the source code [here](https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L4) + +Advanced users can override this system message for a specific model if needed by using `chatOptions.baseSystemMessage`. See the [`config.yaml` reference](../../reference.md#models). + ## `.continuerules` -You can create a project-specific system message by adding a `.continuerules` file to the root of your project. This file is raw text and its full contents will be used as rules. +You can create project-specific rules by adding a `.continuerules` file to the root of your project. This file is raw text and its full contents will be used as rules. ### Simple Examples diff --git a/docs/docs/customize/model-roles/apply.mdx b/docs/docs/customize/model-roles/apply.mdx index 78574b096..040cdaa2e 100644 --- a/docs/docs/customize/model-roles/apply.mdx +++ b/docs/docs/customize/model-roles/apply.mdx @@ -10,9 +10,15 @@ import Tabs from "@theme/Tabs"; When editing code, Chat and Edit model output often doesn't clearly align with existing code. A model with the `apply` role is used to generate a more precise diff to apply changes to a file. -Generally speaking, models proficient in chat and edit can also be used for applying code. +## Recommended Apply models -Explore apply models in [the hub](https://hub.continue.dev/explore/models?roles=apply). +We recommend [Relace's Instant Apply model](https://hub.continue.dev/relace/instant-apply) for the fastest Apply experience. You can get an API key [here](https://app.relace.ai/settings/api-keys). + +However, most Chat models can also be used for applying code changes. We recommend smaller/cheaper models for the task, such as Claude 3.5 Haiku. + +:::info +Explore all apply models in [the Hub](https://hub.continue.dev/explore/models?roles=apply) +::: ## Prompt templating diff --git a/docs/docs/hub/source-control.md b/docs/docs/hub/source-control.md new file mode 100644 index 000000000..9230c487b --- /dev/null +++ b/docs/docs/hub/source-control.md @@ -0,0 +1,50 @@ +--- +title: Source Control +description: Source Control +keywords: [source, control, github, workflow, action, version, yaml] +sidebar_label: Source Control +--- + +# Source Control + +When managing your custom assistants within an organization, you might want to take advantage of your usual source control workflows. Continue makes this easy with a [GitHub Action](https://github.com/continuedev/continue-publish-action) that automatically syncs your YAML files with hub.continue.dev. We are also planning on adding automations for GitLab, BitBucket, Gitee, and others. If you are interested, please reach out to us on [Discord](https://discord.gg/vapESyrFmJ). + +## Quickstart + +This quickstart uses a template repository, but you can also follow these steps 2-4 from an existing repository. + +### 1. Create a new repository from the template + +As shown in the image below, start by creating a new repository from [the template](https://github.com/continuedev/continue-hub-template). Click "Use Template" and then "Create a new repository". + +![Use the template repository](/img/hub/template-repo.png) + +### 2. Obtain a deploy key + +Deploy keys allow the GitHub Action to authenticate with hub.continue.dev. [Obtain your deploy key here](https://hub.continue.dev/settings/api-keys) and then [create a secret](https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions#creating-secrets-for-a-repository) named `CONTINUE_API_KEY` in your GitHub repository. + +### 3. Configure the GitHub Action + +:::tip +This step assumes you have already created an organization on hub.continue.dev. If not, learn more [here](./governance/creating-an-org.md). +::: + +In the repository you created, navigate to `.github/workflows/main.yaml` and update the lines below to match your organization: + +```yaml +env: + OWNER_SLUG: my-org-slug # <-- TODO +``` + +This is the only configuration necessary, but you can view the full list of options [here](https://github.com/continuedev/continue-publish-action/blob/main/README.md). + +### 4. Commit and push + +Add the [YAML for your assistants and blocks](../reference.md) to the appropriate directories: + +- `assistants/public` for public assistants +- `assistants/private` for private (visible only within your organization) assistants +- `blocks/public` for public blocks +- `blocks/private` for private blocks + +Then, commit and push your changes. Once the GitHub Action has completed running, you should be able to view the assistants within your organization on hub.continue.dev. diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 6269a1bb7..22bc742ab 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -49,6 +49,28 @@ models: provider: ollama ``` +### Local Blocks + +It is also possible to define blocks locally in a `.continue` folder. This folder can be located at either the root of your workspace (these will automatically be applied to all assistants when you are in that workspace) or in your home directory at `~/.continue` (these will automatically be applied globally). + +Place your YAML files in the following folders: + +Assistants: + +- `.continue/assistants` - for assistants + +Blocks: + +- `.continue/rules` - for rules +- `.continue/models` - for models +- `.continue/prompts` - for prompts +- `.continue/context` - for context providers +- `.continue/docs` - for docs +- `.continue/data` - for data +- `.continue/mcpServers` - for MCP Servers + +You can find many examples of each of these block types on the [Continue Explore Page](https://hub.continue.dev/explore/models) + ### Inputs Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use mustache templating as follows: @@ -237,7 +259,13 @@ context: ### `rules` -List of rules that the LLM should follow. These are inserted into the system message for all chat requests. +List of rules that the LLM should follow. These are concatenated into the system message for all [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md), and [Agent](./agent/how-to-use-it.md) requests. See the [rules deep dive](./customize/deep-dives/rules.md) for details. + +Explicit rules can either be simple text or an object with the following properties: + +- `name` (**required**): A display name/title for the rule +- `rule` (**required**): The text content of the rule + Example @@ -245,9 +273,11 @@ Example rules: - uses: myprofile/my-mood-setter with: - MOOD: happy + TONE: concise - Always annotate Python functions with their parameter and return types - Always write Google style docstrings for functions and classes + - name: Server-side components + rule: When writing Next.js React components, use server-side components where possible instead of client components. ``` --- diff --git a/docs/sidebars.js b/docs/sidebars.js index 20a47be93..1a634d163 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -171,6 +171,7 @@ const sidebars = { "hub/governance/pricing", ], }, + "hub/source-control", { type: "link", label: "Customize", diff --git a/docs/static/img/hub/template-repo.png b/docs/static/img/hub/template-repo.png new file mode 100644 index 000000000..36dbf4aa8 Binary files /dev/null and b/docs/static/img/hub/template-repo.png differ diff --git a/docs/static/img/notch-rules.png b/docs/static/img/notch-rules.png new file mode 100644 index 000000000..02a175817 Binary files /dev/null and b/docs/static/img/notch-rules.png differ diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 7c00cb65c..ec6ce435b 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginName=continue-intellij-extension pluginRepositoryUrl=https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion=1.0.12 +pluginVersion=1.0.13 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild=223 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 100ee2aad..82c6be732 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -83,6 +83,7 @@ class MessageTypes { "config/addModel", "config/newPromptFile", "config/ideSettingsUpdate", + "config/addLocalWorkspaceBlock", "config/getSerializedProfileInfo", "config/deleteModel", "config/refreshProfiles", diff --git a/extensions/vscode/.gitignore b/extensions/vscode/.gitignore index aa99f752c..e4f2af902 100644 --- a/extensions/vscode/.gitignore +++ b/extensions/vscode/.gitignore @@ -25,4 +25,6 @@ e2e/vsix e2e/test-continue/* !e2e/test-continue/config.json e2e/test-continue-yaml/* -!e2e/test-continue-yaml/config.yaml \ No newline at end of file +!e2e/test-continue-yaml/config.yaml + +config-yaml-schema.json \ No newline at end of file diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 801bba5ea..48f6e2aaa 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -2655,7 +2655,7 @@ }, "systemMessage": { "title": "System Message", - "description": "A system message that will always be followed by the LLM", + "description": "A system message that will always be followed by the LLM for Chat and Edit requests", "type": "string" }, "completionOptions": { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index fdcad544a..4917b02cc 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.23", + "version": "1.1.24", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.23", + "version": "1.1.24", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 088ac0001..ade2b79fa 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.23", + "version": "1.1.24", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -92,11 +92,6 @@ "default": true, "markdownDescription": "Continue collects anonymous usage data, cleaned of PII, to help us improve the product for our users. Read more at [continue.dev › Telemetry](https://docs.continue.dev/telemetry)." }, - "continue.enableContinueForTeams": { - "type": "boolean", - "default": false, - "markdownDescription": "Enable Continue for teams beta features. To sign in, click the gear icon to go to the settings page, and click Sign In." - }, "continue.showInlineTip": { "type": "boolean", "default": true, @@ -588,6 +583,10 @@ { "fileMatch": ".continuerc.json", "url": "./continue_rc_schema.json" + }, + { + "fileMatch": "**/config.yaml", + "url": "./config-yaml-schema.json" } ] }, diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index fbec94f6c..c16e627c3 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -10,7 +10,11 @@ const { autodetectPlatformAndArch, } = require("../../../scripts/util/index"); -const { copyConfigSchema, writeBuildTimestamp } = require("./utils"); +const { + copyConfigSchema, + writeBuildTimestamp, + generateConfigYamlSchema, +} = require("./utils"); // Clear folders that will be packaged to ensure clean slate rimrafSync(path.join(__dirname, "..", "bin")); @@ -63,6 +67,9 @@ const isMacTarget = target?.startsWith("darwin"); (async () => { console.log("[info] Packaging extension for target ", target); + // Generate and copy over config-yaml-schema.json + generateConfigYamlSchema(); + // Copy config schemas to intellij copyConfigSchema(); diff --git a/extensions/vscode/scripts/utils.js b/extensions/vscode/scripts/utils.js index 8a144731f..7023b6372 100644 --- a/extensions/vscode/scripts/utils.js +++ b/extensions/vscode/scripts/utils.js @@ -10,7 +10,20 @@ const { const continueDir = path.join(__dirname, "..", "..", ".."); +function generateConfigYamlSchema() { + process.chdir(path.join(continueDir, "packages", "config-yaml")); + execCmdSync("npm install"); + execCmdSync("npm run build"); + execCmdSync("npm run generate-schema"); + fs.copyFileSync( + path.join("schema", "config-yaml-schema.json"), + path.join(continueDir, "extensions", "vscode", "config-yaml-schema.json"), + ); + console.log("[info] Generated config.yaml schema"); +} + function copyConfigSchema() { + process.chdir(path.join(continueDir, "extensions", "vscode")); // Modify and copy for .continuerc.json const schema = JSON.parse(fs.readFileSync("config_schema.json", "utf8")); schema.$defs.SerializedContinueConfig.properties.mergeBehavior = { @@ -526,6 +539,7 @@ function writeBuildTimestamp() { } module.exports = { + generateConfigYamlSchema, copyConfigSchema, installNodeModules, buildGui, diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index 3c8b66dcd..5725c716a 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -759,10 +759,6 @@ class VsCodeIde implements IDE { 60, ), userToken: settings.get("userToken", ""), - enableControlServerBeta: settings.get( - "enableContinueForTeams", - false, - ), continueTestEnvironment: "production", pauseCodebaseIndexOnStart: settings.get( "pauseCodebaseIndexOnStart", diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 1bd22c7f4..bfc344b06 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -2,6 +2,7 @@ import { getContinueRcPath, getTsConfigPath } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; +import * as path from "path"; import { VsCodeExtension } from "../extension/VsCodeExtension"; import registerQuickFixProvider from "../lang-server/codeActions"; import { getExtensionVersion } from "../util/util"; @@ -32,6 +33,22 @@ export async function activateExtension(context: vscode.ExtensionContext) { ); } + // Only set the YAML schema configuration if it hasn't been set before + if (!context.globalState.get("yamlSchemaConfigured")) { + vscode.workspace.getConfiguration("yaml").update( + "schemas", + { + [path.join( + context.extension.extensionUri.fsPath, + "config-yaml-schema.json", + )]: [".continue/**/*.yaml"], + }, + vscode.ConfigurationTarget.Global, + ); + // Mark that we've configured the YAML schema + context.globalState.update("yamlSchemaConfigured", true); + } + const api = new VsCodeContinueApi(vscodeExtension); const continuePublicApi = { registerCustomContextProvider: api.registerCustomContextProvider.bind(api), diff --git a/extensions/vscode/src/apply/ApplyManager.ts b/extensions/vscode/src/apply/ApplyManager.ts index 4942cb0c1..3af716fc2 100644 --- a/extensions/vscode/src/apply/ApplyManager.ts +++ b/extensions/vscode/src/apply/ApplyManager.ts @@ -116,17 +116,17 @@ export class ApplyManager { return; } - const [instant, diffLines] = await applyCodeBlock( + const { isInstantApply, diffLinesGenerator } = await applyCodeBlock( editor.document.getText(), text, getUriPathBasename(editor.document.uri.toString()), llm, ); - if (instant) { + if (isInstantApply) { await this.verticalDiffManager.streamDiffLines( - diffLines, - instant, + diffLinesGenerator, + isInstantApply, streamId, toolCallId, ); @@ -157,6 +157,12 @@ export class ApplyManager { verticalDiffManager: VerticalDiffManager, toolCallId?: string, ) { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + vscode.window.showErrorMessage("Config not loaded"); + return; + } + const prompt = this.getApplyPrompt(text); const fullEditorRange = new vscode.Range( 0, @@ -168,15 +174,14 @@ export class ApplyManager { ? fullEditorRange : editor.selection; - await verticalDiffManager.streamEdit( - prompt, + await verticalDiffManager.streamEdit({ + input: prompt, llm, streamId, - undefined, - undefined, - rangeToApplyTo, - text, + range: rangeToApplyTo, + newCode: text, toolCallId, - ); + rules: config.rules, + }); } } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 719c1a5d1..f44e5fed7 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -372,14 +372,14 @@ const getCommandsMap: ( void sidebar.webviewProtocol.request("incrementFtc", undefined); - await verticalDiffManager.streamEdit( - config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, + await verticalDiffManager.streamEdit({ + input: + config.experimental?.contextMenuPrompts?.[promptName] ?? fallbackPrompt, llm, - undefined, onlyOneInsertion, - undefined, range, - ); + rules: config.rules, + }); } return { "continue.acceptDiff": async (newFileUri?: string, streamId?: string) => diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index f5496fe2f..6c94ab343 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -1,4 +1,4 @@ -import { ChatMessage, DiffLine, ILLM } from "core"; +import { ChatMessage, DiffLine, ILLM, RuleWithSource } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; import { streamDiffLines } from "core/edit/streamDiffLines"; import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; @@ -271,16 +271,27 @@ export class VerticalDiffManager { } } - async streamEdit( - input: string, - llm: ILLM, - streamId?: string, - onlyOneInsertion?: boolean, - quickEdit?: string, - range?: vscode.Range, - newCode?: string, - toolCallId?: string, - ): Promise { + async streamEdit({ + input, + llm, + streamId, + onlyOneInsertion, + quickEdit, + range, + newCode, + toolCallId, + rules, + }: { + input: string; + llm: ILLM; + streamId?: string; + onlyOneInsertion?: boolean; + quickEdit?: string; + range?: vscode.Range; + newCode?: string; + toolCallId?: string; + rules: RuleWithSource[]; + }): Promise { vscode.commands.executeCommand("setContext", "continue.diffVisible", true); let editor = vscode.window.activeTextEditor; @@ -427,16 +438,17 @@ export class VerticalDiffManager { const streamedLines: string[] = []; async function* recordedStream() { - const stream = streamDiffLines( + const stream = streamDiffLines({ + highlighted: rangeContent, prefix, - rangeContent, suffix, llm, + rules, input, - getMarkdownLanguageTagForFile(fileUri), - !!onlyOneInsertion, + language: getMarkdownLanguageTagForFile(fileUri), + onlyOneInsertion: !!onlyOneInsertion, overridePrompt, - ); + }); for await (const line of stream) { if (line.type === "new" || line.type === "same") { diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index c955f8d51..bcdb88edd 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -193,24 +193,11 @@ export class VsCodeExtension { let profileId = queryParams.get("profile_id"); let orgId = queryParams.get("org_id"); - if (orgId && orgId !== "null") { - // In case org id is passed with profile id - // Make sure org is updated before profile is set - if (profileId && profileId !== "null") { - this.core.invoke("didChangeSelectedOrg", { - id: orgId, - profileId, - }); - } else { - this.core.invoke("didChangeSelectedOrg", { - id: orgId, - }); - } - } else if (profileId && profileId !== "null") { - this.core.invoke("didChangeSelectedProfile", { - id: profileId, - }); - } + this.core.invoke("config/refreshProfiles", { + selectOrgId: orgId === "null" ? undefined : (orgId ?? undefined), + selectProfileId: + profileId === "null" ? undefined : (profileId ?? undefined), + }); }); // Battery diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 3112572d9..d0ada4fc4 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -195,6 +195,10 @@ export class VsCodeMessenger { const configHandler = await configHandlerPromise; const { config } = await configHandler.loadConfig(); + if (!config) { + throw new Error("Edit: Failed to load config"); + } + const model = config?.selectedModelByRole.edit ?? config?.selectedModelByRole.chat; @@ -202,17 +206,16 @@ export class VsCodeMessenger { throw new Error("No Edit or Chat model selected"); } - const fileAfterEdit = await verticalDiffManager.streamEdit( - stripImages(prompt), - model, - "edit", - undefined, - undefined, - new vscode.Range( + const fileAfterEdit = await verticalDiffManager.streamEdit({ + input: stripImages(prompt), + llm: model, + streamId: "edit", + range: new vscode.Range( new vscode.Position(start.line, start.character), new vscode.Position(end.line, end.character), ), - ); + rules: config.rules, + }); void this.webviewProtocol.request("setEditStatus", { status: "accepting", diff --git a/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts new file mode 100644 index 000000000..dd46ad401 --- /dev/null +++ b/extensions/vscode/src/lang-server/codeLens/providers/DownloadYamlExtensionCodeLensProvider.ts @@ -0,0 +1,34 @@ +import * as vscode from "vscode"; + +export class DownloadYamlExtensionCodeLensProvider + implements vscode.CodeLensProvider +{ + private yamlExtensionDownloaded(): boolean { + const yamlExtension = vscode.extensions.getExtension("redhat.vscode-yaml"); + return yamlExtension !== undefined; + } + + public provideCodeLenses( + document: vscode.TextDocument, + _: vscode.CancellationToken, + ): vscode.CodeLens[] | Thenable { + if (!document.uri.fsPath.includes(".continue")) { + return []; + } + if (this.yamlExtensionDownloaded()) { + return []; + } + + const codeLens: vscode.CodeLens = { + range: new vscode.Range(0, 0, 0, 0), + command: { + title: "Download YAML extension for Intellisense", + command: "workbench.extensions.installExtension", + arguments: ["redhat.vscode-yaml"], + }, + isResolved: true, + }; + + return [codeLens]; + } +} diff --git a/extensions/vscode/src/lang-server/codeLens/providers/index.ts b/extensions/vscode/src/lang-server/codeLens/providers/index.ts index 00a309e62..03d89aa44 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/index.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/index.ts @@ -1,3 +1,4 @@ +export { DownloadYamlExtensionCodeLensProvider } from "./DownloadYamlExtensionCodeLensProvider"; export { QuickActionsCodeLensProvider } from "./QuickActionsCodeLensProvider"; export { SuggestionsCodeLensProvider } from "./SuggestionsCodeLensProvider"; export { VerticalDiffCodeLensProvider as VerticalPerLineCodeLensProvider } from "./VerticalPerLineCodeLensProvider"; diff --git a/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts b/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts index 9138fba8b..e17312fa0 100644 --- a/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts +++ b/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts @@ -19,6 +19,8 @@ let suggestionsCodeLensDisposable: vscode.Disposable | undefined = undefined; let configPyCodeLensDisposable: vscode.Disposable | undefined = undefined; let tutorialCodeLensDisposable: vscode.Disposable | undefined = undefined; let quickActionsCodeLensDisposable: vscode.Disposable | undefined = undefined; +let downloadYamlExtensionCodeLensDisposable: vscode.Disposable | undefined = + undefined; /** * Registers the Quick Actions CodeLens provider if Quick Actions are enabled. @@ -96,6 +98,10 @@ export function registerAllCodeLensProviders( tutorialCodeLensDisposable.dispose(); } + if (downloadYamlExtensionCodeLensDisposable) { + downloadYamlExtensionCodeLensDisposable.dispose(); + } + const verticalDiffCodeLens = new providers.VerticalPerLineCodeLensProvider( editorToVerticalDiffCodeLens, ); @@ -110,6 +116,11 @@ export function registerAllCodeLensProviders( new providers.SuggestionsCodeLensProvider(), ); + downloadYamlExtensionCodeLensDisposable = registerCodeLensProvider( + "yaml", + new providers.DownloadYamlExtensionCodeLensProvider(), + ); + if (config) { registerQuickActionsProvider(config, context); diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index e0c826fb1..fa526b6e5 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/naming-convention */ -import { IDE, ILLM } from "core"; +import { IDE, ILLM, RuleWithSource } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; import { DataLogger } from "core/data/log"; import { Telemetry } from "core/util/posthog"; @@ -243,7 +243,10 @@ export class QuickEdit { throw new Error("No model selected"); } - await this._streamEditWithInputAndContext(prompt, model); + const { config } = await this.configHandler.loadConfig(); + const rules = config?.rules ?? []; // no need to error - getCurModel above will handle + + await this._streamEditWithInputAndContext(prompt, model, rules); this.openAcceptRejectMenu(prompt, path); }; @@ -295,7 +298,11 @@ export class QuickEdit { }`; }; - private async _streamEditWithInputAndContext(prompt: string, model: ILLM) { + private async _streamEditWithInputAndContext( + prompt: string, + model: ILLM, + rules: RuleWithSource[], + ) { // Extracts all file references from the prompt string, // which are denoted by an '@' symbol followed by // one or more non-whitespace characters. @@ -319,14 +326,13 @@ export class QuickEdit { void this.webviewProtocol.request("incrementFtc", undefined); - await this.verticalDiffManager.streamEdit( - prompt, - model, - undefined, - undefined, - this.previousInput, - this.range, - ); + await this.verticalDiffManager.streamEdit({ + input: prompt, + llm: model, + quickEdit: this.previousInput, + range: this.range, + rules, + }); } private getInitialItems(): vscode.QuickPickItem[] { diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index 03d9b2174..2e6acfb86 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -1,7 +1,7 @@ import crypto from "crypto"; import { ControlPlaneSessionInfo } from "core/control-plane/client"; -import { EXTENSION_NAME, getControlPlaneEnvSync } from "core/control-plane/env"; +import { getControlPlaneEnvSync } from "core/control-plane/env"; import fetch from "node-fetch"; import { v4 as uuidv4 } from "uuid"; import { @@ -16,7 +16,6 @@ import { ProgressLocation, Uri, window, - workspace, } from "vscode"; import { PromiseAdapter, promiseFromEvent } from "./promiseUtils"; @@ -25,13 +24,7 @@ import { UriEventHandler } from "./uriHandler"; const AUTH_NAME = "Continue"; -const enableControlServerBeta = workspace - .getConfiguration(EXTENSION_NAME) - .get("enableContinueForTeams", false); -const controlPlaneEnv = getControlPlaneEnvSync( - true ? "production" : "none", - enableControlServerBeta, -); +const controlPlaneEnv = getControlPlaneEnvSync(true ? "production" : "none"); const SESSIONS_SECRET_KEY = `${controlPlaneEnv.AUTH_TYPE}.sessions`; diff --git a/gui/package-lock.json b/gui/package-lock.json index 2105fc59b..00986cfcf 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -93,7 +93,7 @@ "tailwindcss": "^3.2.7", "typescript": "^5.6.3", "typescript-eslint": "^8.16.0", - "vite": "^4.5.11", + "vite": "^4.5.13", "vitest": "^2.1.3" }, "engines": { @@ -222,7 +222,8 @@ "cross-env": "^7.0.3", "jest": "^29.7.0", "ts-jest": "^29.2.3", - "ts-node": "^10.9.2" + "ts-node": "^10.9.2", + "zod-to-json-schema": "^3.24.5" } }, "node_modules/@adobe/css-tools": { @@ -12255,9 +12256,9 @@ } }, "node_modules/vite": { - "version": "4.5.11", - "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.11.tgz", - "integrity": "sha512-4mVdhLkZ0vpqZLGJhNm+X1n7juqXApEMGlUXcOQawA45UmpxivOYaMBkI/Js3FlBsNA8hCgEnX5X04moFitSGw==", + "version": "4.5.13", + "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.13.tgz", + "integrity": "sha512-Hgp8IF/yZDzKsN1hQWOuQZbrKiaFsbQud+07jJ8h9m9PaHWkpvZ5u55Xw5yYjWRXwRQ4jwFlJvY7T7FUJG9MCA==", "dev": true, "license": "MIT", "dependencies": { diff --git a/gui/package.json b/gui/package.json index 1a46aa97e..50d2c6122 100644 --- a/gui/package.json +++ b/gui/package.json @@ -101,7 +101,7 @@ "tailwindcss": "^3.2.7", "typescript": "^5.6.3", "typescript-eslint": "^8.16.0", - "vite": "^4.5.11", + "vite": "^4.5.13", "vitest": "^2.1.3" }, "engine-strict": true, diff --git a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx b/gui/src/components/AcceptRejectAllButtons.tsx similarity index 90% rename from gui/src/components/StepContainer/AcceptRejectAllButtons.tsx rename to gui/src/components/AcceptRejectAllButtons.tsx index 8d2e59dd3..7a9c28062 100644 --- a/gui/src/components/StepContainer/AcceptRejectAllButtons.tsx +++ b/gui/src/components/AcceptRejectAllButtons.tsx @@ -1,10 +1,10 @@ -import { useContext } from "react"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; import { ApplyState } from "core"; -import { getMetaKeyLabel } from "../../util"; -import { useAppSelector } from "../../redux/hooks"; -import { selectIsSingleRangeEditOrInsertion } from "../../redux/slices/sessionSlice"; +import { useContext } from "react"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { useAppSelector } from "../redux/hooks"; +import { selectIsSingleRangeEditOrInsertion } from "../redux/slices/sessionSlice"; +import { getMetaKeyLabel } from "../util"; export interface AcceptRejectAllButtonsProps { pendingApplyStates: ApplyState[]; diff --git a/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx b/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx index 3d59ac239..9651ec235 100644 --- a/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx +++ b/gui/src/components/CodeToEditCard/CodeToEditListItem.tsx @@ -1,18 +1,18 @@ -import FileIcon from "../FileIcon"; import { ChevronDownIcon, ChevronRightIcon, XMarkIcon, } from "@heroicons/react/24/outline"; -import { useState } from "react"; -import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; -import { getMarkdownLanguageTagForFile } from "core/util"; -import styled from "styled-components"; import { CodeToEdit } from "core"; +import { getMarkdownLanguageTagForFile } from "core/util"; import { getLastNUriRelativePathParts, getUriPathBasename, } from "core/util/uri"; +import { useState } from "react"; +import styled from "styled-components"; +import FileIcon from "../FileIcon"; +import StyledMarkdownPreview from "../StyledMarkdownPreview"; export interface CodeToEditListItemProps { code: CodeToEdit; diff --git a/gui/src/components/StepContainer/FeedbackButtons.tsx b/gui/src/components/FeedbackButtons.tsx similarity index 86% rename from gui/src/components/StepContainer/FeedbackButtons.tsx rename to gui/src/components/FeedbackButtons.tsx index 4ef09a833..6ad0992df 100644 --- a/gui/src/components/StepContainer/FeedbackButtons.tsx +++ b/gui/src/components/FeedbackButtons.tsx @@ -1,12 +1,12 @@ import { - HandThumbUpIcon, HandThumbDownIcon, + HandThumbUpIcon, } from "@heroicons/react/24/outline"; -import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import { ChatHistoryItem } from "core"; -import { useState, useContext } from "react"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useAppSelector } from "../../redux/hooks"; +import { useContext, useState } from "react"; +import { IdeMessengerContext } from "../context/IdeMessenger"; +import { useAppSelector } from "../redux/hooks"; +import HeaderButtonWithToolTip from "./gui/HeaderButtonWithToolTip"; export interface FeedbackButtonsProps { item: ChatHistoryItem; diff --git a/gui/src/components/StepContainer/EditActions.tsx b/gui/src/components/StepContainer/EditActions.tsx index d40ed72b9..08a61e2e3 100644 --- a/gui/src/components/StepContainer/EditActions.tsx +++ b/gui/src/components/StepContainer/EditActions.tsx @@ -1,12 +1,12 @@ import { ChatHistoryItem } from "core"; -import AcceptRejectAllButtons from "./AcceptRejectAllButtons"; -import FeedbackButtons from "./FeedbackButtons"; import { renderChatMessage } from "core/util/messageContent"; -import { CopyIconButton } from "../gui/CopyIconButton"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { exitEditMode } from "../../redux/thunks/exitEditMode"; import { loadLastSession } from "../../redux/thunks/session"; +import AcceptRejectAllButtons from "../AcceptRejectAllButtons"; +import FeedbackButtons from "../FeedbackButtons"; +import { CopyIconButton } from "../gui/CopyIconButton"; export interface EditActionsProps { index: number; diff --git a/gui/src/components/StepContainer/Reasoning.tsx b/gui/src/components/StepContainer/Reasoning.tsx index d5537c82b..b2c7ec19e 100644 --- a/gui/src/components/StepContainer/Reasoning.tsx +++ b/gui/src/components/StepContainer/Reasoning.tsx @@ -10,7 +10,7 @@ import { vscQuickInputBackground, } from ".."; import { getFontSize } from "../../util"; -import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../StyledMarkdownPreview"; interface ReasoningProps { item: ChatHistoryItem; diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index f016b3474..dce39ea6f 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -1,12 +1,12 @@ import { BarsArrowDownIcon, TrashIcon } from "@heroicons/react/24/outline"; import { ChatHistoryItem } from "core"; import { renderChatMessage } from "core/util/messageContent"; +import { useAppSelector } from "../../redux/hooks"; +import { selectIsInEditMode } from "../../redux/slices/sessionSlice"; +import FeedbackButtons from "../FeedbackButtons"; import { CopyIconButton } from "../gui/CopyIconButton"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import EditActions from "./EditActions"; -import FeedbackButtons from "./FeedbackButtons"; -import { useAppSelector } from "../../redux/hooks"; -import { selectIsInEditMode } from "../../redux/slices/sessionSlice"; export interface ResponseActionsProps { isTruncated: boolean; diff --git a/gui/src/components/StepContainer/StepContainer.tsx b/gui/src/components/StepContainer/StepContainer.tsx index 01560e595..aac4b877a 100644 --- a/gui/src/components/StepContainer/StepContainer.tsx +++ b/gui/src/components/StepContainer/StepContainer.tsx @@ -8,7 +8,7 @@ import { useAppSelector } from "../../redux/hooks"; import { selectUIConfig } from "../../redux/slices/configSlice"; import { deleteMessage } from "../../redux/slices/sessionSlice"; import { getFontSize } from "../../util"; -import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../StyledMarkdownPreview"; import Reasoning from "./Reasoning"; import ResponseActions from "./ResponseActions"; import ThinkingIndicator from "./ThinkingIndicator"; @@ -43,9 +43,6 @@ export default function StepContainer(props: StepContainerProps) { historyItemAfterThis?.message.role === "thinking"; const hideActions = hideActionSpace || (isStreaming && props.isLast); - // const isStepAheadOfCurCheckpoint = - // isInEditMode && Math.floor(props.index / 2) > curCheckpointIndex; - useEffect(() => { if (!isStreaming) { const content = renderChatMessage(props.item.message).trim(); @@ -83,9 +80,7 @@ export default function StepContainer(props: StepContainerProps) { } return ( -
+
{uiConfig?.displayRawMarkdown ? (
 void;
 }
 
-export default function ApplyActions(props: ApplyActionsProps) {
+export function ApplyActions(props: ApplyActionsProps) {
   const [hasRejected, setHasRejected] = useState(false);
   const [showApplied, setShowApplied] = useState(false);
   const isClosed = props.applyState?.status === "closed";
@@ -37,11 +36,10 @@ export default function ApplyActions(props: ApplyActionsProps) {
 
   const applyButton = (text: string) => (
     
+    
+  );
+}
diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo.tsx
new file mode 100644
index 000000000..550d1fd28
--- /dev/null
+++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/FileInfo.tsx
@@ -0,0 +1,42 @@
+import { getLastNPathParts } from "core/util/uri";
+import FileIcon from "../../FileIcon";
+import { ToolTip } from "../../gui/Tooltip";
+
+export interface FileInfoProps {
+  filepath: string;
+  onClick?: () => void;
+  range?: string;
+}
+
+const TOOLTIP_ID = "file-info-tooltip";
+
+export const FileInfo = ({ filepath, range, onClick }: FileInfoProps) => {
+  return (
+    <>
+      
+
+ +
+ + {getLastNPathParts(filepath, 1)} + {range && ` ${range}`} + +
+ + + ); +}; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/GeneratingCodeLoader.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/GeneratingCodeLoader.tsx similarity index 81% rename from gui/src/components/markdown/StepContainerPreToolbar/GeneratingCodeLoader.tsx rename to gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/GeneratingCodeLoader.tsx index c430c8d62..b730b30e5 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/GeneratingCodeLoader.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/GeneratingCodeLoader.tsx @@ -5,7 +5,7 @@ export interface GeneratingCodeLoaderProps { codeBlockContent: string; } -export default function GeneratingCodeLoader({ +export function GeneratingCodeLoader({ showLineCount, codeBlockContent, }: GeneratingCodeLoaderProps) { @@ -16,7 +16,7 @@ export default function GeneratingCodeLoader({ : `${numLinesCodeBlock} lines generated`; return ( - + {showLineCount ? linesGeneratedText : "Generating"} diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/InsertButton.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/InsertButton.tsx new file mode 100644 index 000000000..b8784dd07 --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/InsertButton.tsx @@ -0,0 +1,21 @@ +import { ArrowLeftEndOnRectangleIcon } from "@heroicons/react/24/outline"; + +/** + * Button that inserts code at the current cursor position + */ +interface InsertButtonProps { + onInsert: () => void; +} + +export function InsertButton({ onInsert }: InsertButtonProps) { + return ( +
+
+ +
+
+ ); +} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx similarity index 71% rename from gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx rename to gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx index 35bc54349..07da9e7da 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/RunInTerminalButton.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx @@ -7,9 +7,7 @@ interface RunInTerminalButtonProps { command: string; } -export default function RunInTerminalButton({ - command, -}: RunInTerminalButtonProps) { +export function RunInTerminalButton({ command }: RunInTerminalButtonProps) { const ideMessenger = useContext(IdeMessengerContext); function runInTerminal() { @@ -18,7 +16,7 @@ export default function RunInTerminalButton({ return (
<> - Run + Run
diff --git a/gui/src/components/markdown/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx similarity index 100% rename from gui/src/components/markdown/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx rename to gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx index 9ffed883c..b60691d7b 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ToolbarButtonWithTooltip.tsx @@ -1,7 +1,7 @@ import { ReactNode, useMemo } from "react"; import { Tooltip } from "react-tooltip"; -import { lightGray, vscForeground } from "../.."; import styled from "styled-components"; +import { lightGray, vscForeground } from "../.."; import { getFontSize } from "../../../util"; export const ToolbarButton = styled.button` diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx similarity index 59% rename from gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx rename to gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx index 0397603f3..111359fc8 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx @@ -1,6 +1,6 @@ import { ChevronDownIcon } from "@heroicons/react/24/outline"; import { inferResolvedUriFromRelativePath } from "core/util/ideUtils"; -import { useContext, useState } from "react"; +import { useContext, useEffect, useMemo, useState } from "react"; import styled from "styled-components"; import { defaultBorderRadius, @@ -8,6 +8,7 @@ import { vscEditorBackground, } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useIdeMessengerRequest } from "../../../hooks"; import { useWebviewListener } from "../../../hooks/useWebviewListener"; import { useAppSelector } from "../../../redux/hooks"; import { @@ -16,12 +17,13 @@ import { } from "../../../redux/slices/sessionSlice"; import { getFontSize } from "../../../util"; import { isTerminalCodeBlock } from "../utils"; -import ApplyActions from "./ApplyActions"; -import CopyButton from "./CopyButton"; +import { ApplyActions } from "./ApplyActions"; +import { CopyButton } from "./CopyButton"; +import { CreateFileButton } from "./CreateFileButton"; import { FileInfo } from "./FileInfo"; -import GeneratingCodeLoader from "./GeneratingCodeLoader"; -import InsertButton from "./InsertButton"; -import RunInTerminalButton from "./RunInTerminalButton"; +import { GeneratingCodeLoader } from "./GeneratingCodeLoader"; +import { InsertButton } from "./InsertButton"; +import { RunInTerminalButton } from "./RunInTerminalButton"; const TopDiv = styled.div` display: flex; @@ -59,7 +61,7 @@ export interface StepContainerPreToolbarProps { disableManualApply?: boolean; } -export default function StepContainerPreToolbar({ +export function StepContainerPreToolbar({ codeBlockContent, language, relativeFilepath, @@ -77,11 +79,21 @@ export default function StepContainerPreToolbar({ expanded ?? (isInEditMode ? false : true), ); - // We store the resolved file URI to ensure we use the same file when - // accepting/rejecting diffs, even if no `relativeFilepath` is provided - const [resolvedFileUri, setResolvedFileUri] = useState( - undefined, + const [relativeFilepathUri, setRelativeFilepathUri] = useState( + null, ); + + const fileExistsInput = useMemo( + () => (relativeFilepathUri ? { filepath: relativeFilepathUri } : null), + [relativeFilepathUri], + ); + + const { + result: fileExists, + refresh: refreshFileExists, + isLoading: isLoadingFileExists, + } = useIdeMessengerRequest("fileExists", fileExistsInput); + const nextCodeBlockIndex = useAppSelector( (state) => state.session.codeBlockApplyStates.curIndex, ); @@ -90,24 +102,54 @@ export default function StepContainerPreToolbar({ selectApplyStateByStreamId(state, codeBlockStreamId), ); + /** + * In the case where `relativeFilepath` is defined, this will just be `relativeFilepathUri`. + * However, if no `relativeFilepath` is defined, then this will + * be the URI of the currently open file at the time the user clicks "Apply". + */ + const [appliedFileUri, setAppliedFileUri] = useState( + undefined, + ); + const isNextCodeBlock = nextCodeBlockIndex === codeBlockIndex; const hasFileExtension = relativeFilepath && /\.[0-9a-z]+$/i.test(relativeFilepath); - const displayFilepath = relativeFilepath ?? resolvedFileUri; + // If we are creating a file, we already render that in the button + // so we don't want to dispaly it twice here + const displayFilepath = relativeFilepath ?? appliedFileUri; - async function getFileUri() { + // TODO: This logic should be moved to a thunk + // Handle apply keyboard shortcut + useWebviewListener( + "applyCodeFromChat", + async () => onClickApply(), + [isNextCodeBlock, codeBlockContent], + !isNextCodeBlock, + ); + + useEffect(() => { + const getRelativeFilepathUri = async () => { + if (relativeFilepath) { + const resolvedUri = await inferResolvedUriFromRelativePath( + relativeFilepath, + ideMessenger.ide, + ); + setRelativeFilepathUri(resolvedUri); + } + }; + getRelativeFilepathUri(); + }, [relativeFilepath, ideMessenger.ide]); + + async function getFileUriToApplyTo() { // If we've already resolved a file URI (from clicking apply), use that - if (resolvedFileUri) { - return resolvedFileUri; + if (appliedFileUri) { + return appliedFileUri; } - // If a relative filepath was provided, try to resolve it - if (relativeFilepath) { - return await inferResolvedUriFromRelativePath( - relativeFilepath, - ideMessenger.ide, - ); + // If we have the `relativeFilepathUri`, use that + if (relativeFilepathUri) { + return relativeFilepathUri; } // If no filepath was provided, get the current file @@ -120,40 +162,32 @@ export default function StepContainerPreToolbar({ } async function onClickApply() { - const fileUri = await getFileUri(); + const fileUri = await getFileUriToApplyTo(); if (!fileUri) { ideMessenger.ide.showToast( "error", "Could not resolve filepath to apply changes", ); - return; } - setResolvedFileUri(fileUri); - + // applyToFile will create the file if it doesn't exist ideMessenger.post("applyToFile", { streamId: codeBlockStreamId, filepath: fileUri, text: codeBlockContent, }); + + setAppliedFileUri(fileUri); + refreshFileExists(); } function onClickInsertAtCursor() { ideMessenger.post("insertAtCursor", { text: codeBlockContent }); } - // TODO: This logic should be moved to a thunk - // Handle apply keyboard shortcut - useWebviewListener( - "applyCodeFromChat", - async () => onClickApply(), - [isNextCodeBlock, codeBlockContent], - !isNextCodeBlock, - ); - async function handleDiffAction(action: "accept" | "reject") { - const filepath = await getFileUri(); + const filepath = await getFileUriToApplyTo(); if (!filepath) { ideMessenger.ide.showToast( "error", @@ -167,13 +201,13 @@ export default function StepContainerPreToolbar({ streamId: codeBlockStreamId, }); - setResolvedFileUri(undefined); + setAppliedFileUri(undefined); } function onClickFilename() { - if (resolvedFileUri) { + if (appliedFileUri) { ideMessenger.post("showFile", { - filepath: resolvedFileUri, + filepath: appliedFileUri, }); } @@ -184,8 +218,32 @@ export default function StepContainerPreToolbar({ } } - // We want until there is an extension in the filepath to avoid rendering - // an incomplete filepath + const renderActionButtons = () => { + if (isTerminalCodeBlock(language, codeBlockContent)) { + return ; + } + + if (isLoadingFileExists) { + return null; + } + + if (fileExists) { + return ( + handleDiffAction("accept")} + onClickReject={() => handleDiffAction("reject")} + /> + ); + } + + return ; + }; + + // We wait until there is an extension in the filepath to avoid rendering + // an incomplete filepath if (relativeFilepath && !hasFileExtension) { return children; } @@ -196,7 +254,7 @@ export default function StepContainerPreToolbar({
setIsExpanded(!isExpanded)} - className={`h-3.5 w-3.5 flex-shrink-0 cursor-pointer text-gray-400 hover:brightness-125 ${ + className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer hover:brightness-125 ${ isExpanded ? "rotate-0" : "-rotate-90" }`} /> @@ -204,10 +262,12 @@ export default function StepContainerPreToolbar({ ) : ( - {language} + + {language} + )}
@@ -219,20 +279,12 @@ export default function StepContainerPreToolbar({ /> ) : ( <> - - +
+ + +
- {isTerminalCodeBlock(language, codeBlockContent) ? ( - - ) : ( - handleDiffAction("accept")} - onClickReject={() => handleDiffAction("reject")} - /> - )} + {renderActionButtons()} )}
diff --git a/gui/src/components/markdown/SymbolLink.tsx b/gui/src/components/StyledMarkdownPreview/SymbolLink.tsx similarity index 100% rename from gui/src/components/markdown/SymbolLink.tsx rename to gui/src/components/StyledMarkdownPreview/SymbolLink.tsx diff --git a/gui/src/components/markdown/SyntaxHighlightedPre.tsx b/gui/src/components/StyledMarkdownPreview/SyntaxHighlightedPre.tsx similarity index 100% rename from gui/src/components/markdown/SyntaxHighlightedPre.tsx rename to gui/src/components/StyledMarkdownPreview/SyntaxHighlightedPre.tsx diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/StyledMarkdownPreview/index.tsx similarity index 99% rename from gui/src/components/markdown/StyledMarkdownPreview.tsx rename to gui/src/components/StyledMarkdownPreview/index.tsx index 3f7c82bca..40494ee6c 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/StyledMarkdownPreview/index.tsx @@ -22,7 +22,7 @@ import { ToolTip } from "../gui/Tooltip"; import FilenameLink from "./FilenameLink"; import "./katex.css"; import "./markdown.css"; -import StepContainerPreToolbar from "./StepContainerPreToolbar"; +import { StepContainerPreToolbar } from "./StepContainerPreToolbar"; import SymbolLink from "./SymbolLink"; import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre"; import { isSymbolNotRif, matchCodeToSymbolOrFile } from "./utils"; diff --git a/gui/src/components/markdown/katex.css b/gui/src/components/StyledMarkdownPreview/katex.css similarity index 100% rename from gui/src/components/markdown/katex.css rename to gui/src/components/StyledMarkdownPreview/katex.css diff --git a/gui/src/components/markdown/markdown.css b/gui/src/components/StyledMarkdownPreview/markdown.css similarity index 100% rename from gui/src/components/markdown/markdown.css rename to gui/src/components/StyledMarkdownPreview/markdown.css diff --git a/gui/src/components/markdown/utils.ts b/gui/src/components/StyledMarkdownPreview/utils.ts similarity index 94% rename from gui/src/components/markdown/utils.ts rename to gui/src/components/StyledMarkdownPreview/utils.ts index 3961f11d0..8b2af26c8 100644 --- a/gui/src/components/markdown/utils.ts +++ b/gui/src/components/StyledMarkdownPreview/utils.ts @@ -23,10 +23,6 @@ const commonTerminalCommands = [ "bundle", ]; -export function getTerminalCommand(text: string): string { - return text.startsWith("$ ") ? text.slice(2) : text; -} - export function isTerminalCodeBlock( language: string | undefined | null, text: string, diff --git a/gui/src/components/markdown/utils/fixDoubleDollarLatex.ts b/gui/src/components/StyledMarkdownPreview/utils/fixDoubleDollarLatex.ts similarity index 100% rename from gui/src/components/markdown/utils/fixDoubleDollarLatex.ts rename to gui/src/components/StyledMarkdownPreview/utils/fixDoubleDollarLatex.ts diff --git a/gui/src/components/markdown/utils/patchNestedMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts similarity index 100% rename from gui/src/components/markdown/utils/patchNestedMarkdown.ts rename to gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts diff --git a/gui/src/components/markdown/utils/remarkTables.tsx b/gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx similarity index 100% rename from gui/src/components/markdown/utils/remarkTables.tsx rename to gui/src/components/StyledMarkdownPreview/utils/remarkTables.tsx diff --git a/gui/src/components/dialogs/index.tsx b/gui/src/components/dialogs/index.tsx index 1cf0567ee..c49b47721 100644 --- a/gui/src/components/dialogs/index.tsx +++ b/gui/src/components/dialogs/index.tsx @@ -1,3 +1,4 @@ +import { XMarkIcon } from "@heroicons/react/24/outline"; import React, { isValidElement, useEffect } from "react"; import ReactMarkdown from "react-markdown"; import styled from "styled-components"; @@ -10,9 +11,6 @@ import { vscBackground, vscForeground, } from ".."; -import { useDispatch } from "react-redux"; -import { setShowDialog } from "../../redux/slices/uiSlice"; -import { XMarkIcon } from "@heroicons/react/24/outline"; interface TextDialogProps { showDialog: boolean; @@ -26,7 +24,8 @@ const ScreenCover = styled.div` width: 100%; height: 100%; background-color: ${parseColorForHex(VSC_BACKGROUND_VAR)}aa; - z-index: 1000; + z-index: 100000; + flex-direction: column; `; const DialogContainer = styled.div` @@ -34,23 +33,16 @@ const DialogContainer = styled.div` top: 50%; left: 50%; transform: translate(-50%, -50%); -`; - -const Dialog = styled.div` color: ${vscForeground}; background-color: ${vscBackground}; border-radius: ${defaultBorderRadius}; display: flex; flex-direction: column; border: 1px solid ${lightGray}; - margin: auto; word-wrap: break-word; - // overflow: hidden; `; const TextDialog = (props: TextDialogProps) => { - const dispatch = useDispatch(); - useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { if (event.key === "Escape") { @@ -71,22 +63,20 @@ const TextDialog = (props: TextDialogProps) => { return ( ); diff --git a/gui/src/components/gui/Tooltip.tsx b/gui/src/components/gui/Tooltip.tsx index cf934f750..1eae5b77b 100644 --- a/gui/src/components/gui/Tooltip.tsx +++ b/gui/src/components/gui/Tooltip.tsx @@ -1,9 +1,10 @@ +import { CSSProperties } from "react"; import ReactDOM from "react-dom"; -import { Tooltip } from "react-tooltip"; +import { ITooltip, Tooltip } from "react-tooltip"; import { vscBackground, vscForeground, vscInputBorder } from ".."; import { fontSize } from "../../util"; -const TooltipStyles = { +const TooltipStyles: CSSProperties = { fontSize: fontSize(-2), backgroundColor: vscBackground, outline: `0.5px solid ${vscInputBorder}`, @@ -14,7 +15,7 @@ const TooltipStyles = { textAlign: "center", }; -export function ToolTip(props: any) { +export function ToolTip(props: ITooltip) { const combinedStyles = { ...TooltipStyles, ...props.style, diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 252126425..08c5a910f 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -148,6 +148,9 @@ function InputToolbar(props: InputToolbarProps) { for (const file of files) { props.onImageFileSelected?.(file); } + if (fileInputRef.current) { + fileInputRef.current.value = ""; + } }} /> @@ -158,7 +161,7 @@ function InputToolbar(props: InputToolbarProps) { fileInputRef.current?.click(); }} /> - + Attach an image @@ -171,7 +174,7 @@ function InputToolbar(props: InputToolbarProps) { className="h-3 w-3 hover:brightness-125" /> - + Add context (files, docs, urls, etc.) diff --git a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx index 4ecf299b7..f7464e793 100644 --- a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx +++ b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx @@ -116,7 +116,7 @@ export function BlockSettingsTopToolbar() { ); return ( -
+
-
+
diff --git a/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx b/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx index 61eb0790a..a79d05a56 100644 --- a/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx +++ b/gui/src/components/mainInput/Lump/sections/ExploreBlocksButton.tsx @@ -1,3 +1,4 @@ +import { BlockType } from "@continuedev/config-yaml"; import { ArrowTopRightOnSquareIcon, PlusIcon, @@ -7,12 +8,7 @@ import { GhostButton } from "../../.."; import { useAuth } from "../../../../context/Auth"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; import { useAppDispatch } from "../../../../redux/hooks"; -import { - setDialogMessage, - setShowDialog, -} from "../../../../redux/slices/uiSlice"; import { fontSize } from "../../../../util"; -import AddDocsDialog from "../../../dialogs/AddDocsDialog"; export function ExploreBlocksButton(props: { blockType: string }) { const { selectedProfile } = useAuth(); @@ -30,16 +26,19 @@ export function ExploreBlocksButton(props: { blockType: string }) { const handleClick = () => { if (isLocal) { - switch (props.blockType) { - case "docs": - dispatch(setShowDialog(true)); - dispatch(setDialogMessage()); - break; - default: - ideMessenger.request("config/openProfile", { - profileId: selectedProfile.id, - }); - } + ideMessenger.request("config/addLocalWorkspaceBlock", { + blockType: props.blockType as BlockType, + }); + // switch (props.blockType) { + // case "docs": + // dispatch(setShowDialog(true)); + // dispatch(setDialogMessage()); + // break; + // default: + // ideMessenger.request("config/openProfile", { + // profileId: selectedProfile.id, + // }); + // } } else { ideMessenger.request("controlPlane/openUrl", { path: `new?type=block&blockType=${props.blockType}`, diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index cd9e94d91..562d7e50b 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -1,185 +1,210 @@ -import { parseConfigYaml, type Rule } from "@continuedev/config-yaml"; -import { ArrowsPointingOutIcon, PencilIcon } from "@heroicons/react/24/outline"; +import { parseConfigYaml } from "@continuedev/config-yaml"; +import { + ArrowsPointingOutIcon, + EyeIcon, + PencilIcon, +} from "@heroicons/react/24/outline"; +import { RuleWithSource } from "core"; +import { + DEFAULT_CHAT_SYSTEM_MESSAGE, + DEFAULT_CHAT_SYSTEM_MESSAGE_URL, +} from "core/llm/constructMessages"; import { useContext, useMemo } from "react"; -import { useSelector } from "react-redux"; import { defaultBorderRadius, vscCommandCenterActiveBorder } from "../../.."; import { useAuth } from "../../../../context/Auth"; import { IdeMessengerContext } from "../../../../context/IdeMessenger"; -import { useAppDispatch } from "../../../../redux/hooks"; +import { useAppDispatch, useAppSelector } from "../../../../redux/hooks"; import { setDialogMessage, setShowDialog, } from "../../../../redux/slices/uiSlice"; -import { RootState } from "../../../../redux/store"; -import { fontSize } from "../../../../util"; import HeaderButtonWithToolTip from "../../../gui/HeaderButtonWithToolTip"; -import { useLump } from "../LumpContext"; +import { useFontSize } from "../../../ui/font"; import { ExploreBlocksButton } from "./ExploreBlocksButton"; interface RuleCardProps { - index: number; - rule: Rule; - onClick: () => void; - title: string; + rule: RuleWithSource; } -const RuleCard: React.FC = ({ index, rule, onClick, title }) => { +const RuleCard: React.FC = ({ rule }) => { const dispatch = useAppDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + + const handleOpen = async () => { + if (rule.slug) { + ideMessenger.request("controlPlane/openUrl", { + path: `${rule.slug}/new-version`, + orgSlug: undefined, + }); + } else if (rule.ruleFile) { + ideMessenger.post("openFile", { + path: rule.ruleFile, + }); + } else if (rule.source === "default") { + ideMessenger.post("openUrl", DEFAULT_CHAT_SYSTEM_MESSAGE_URL); + } else { + ideMessenger.post("config/openProfile", { + profileId: undefined, + }); + } + }; + + const title = useMemo(() => { + if (rule.name) { + return rule.name; + } else { + if (rule.source === ".continuerules") { + return "Project rules"; + } else if (rule.source === "default") { + return "Default chat system message"; + } else if (rule.source === "json-systemMessage") { + return "JSON systemMessage)"; + } else if (rule.source === "model-chat-options") { + return "Base System Chat Message"; + } else { + return "Assistant rule"; + } + } + }, [rule]); function onClickExpand() { dispatch(setShowDialog(true)); dispatch( setDialogMessage( -
+

{title}

-
-            {/** TODO: Render the rule in a more readable way */}
-            {JSON.stringify(rule)}
-          
+
{rule.rule}
, ), ); } - const renderRuleContent = () => { - if (typeof rule === "string") { - return
{rule}
; - } - - if (rule.rule) { - return ( -
-
{rule.rule}
- {rule.if &&
if: {rule.if}
} -
- ); - } - - return
{JSON.stringify(rule)}
; - }; - + const smallFont = useFontSize(-2); + const tinyFont = useFontSize(-3); return (
-
-
-
-
- {title} -
-
- {renderRuleContent()} -
-
-
+
+
+ + {title} + +
{" "} - - - + {rule.source === "default" ? ( + + + + ) : ( + + + + )}
+ + + {rule.rule} + + {rule.if ? ( +
+ Applies if + + {rule.if.replace(/\${{|}}/g, "")} + +
+ ) : null}
); }; export function RulesSection() { - const ideMessenger = useContext(IdeMessengerContext); const { selectedProfile } = useAuth(); - const { hideLump } = useLump(); - const rules = useSelector( - (state: RootState) => state.config.config.rules ?? [], - ); + const config = useAppSelector((store) => store.config.config); + const mode = useAppSelector((store) => store.session.mode); + const sortedRules: RuleWithSource[] = useMemo(() => { + const rules = [...config.rules.map((rule) => ({ ...rule }))]; - const mergedRules = useMemo(() => { - const parsed = selectedProfile?.rawYaml - ? parseConfigYaml(selectedProfile?.rawYaml ?? "") - : undefined; - return rules.map((rule, index) => ({ - unrolledRule: rule, - ruleFromYaml: parsed?.rules?.[index], - })); - }, [rules]); + // Use profile rawYaml to infer slugs + if (selectedProfile?.rawYaml) { + try { + const parsed = parseConfigYaml(selectedProfile.rawYaml); + const parsedRules = parsed?.rules ?? []; + let index = 0; + for (const rule of rules) { + if (rule.source === "rules-block") { + let slug: string | undefined = undefined; + const yamlRule = parsedRules[index]; + if (yamlRule) { + if (typeof yamlRule !== "string" && "uses" in yamlRule) { + slug = yamlRule.uses; + } else { + slug = `${selectedProfile?.fullSlug.ownerSlug}/${selectedProfile?.fullSlug.packageSlug}`; + } + } + if (slug) { + rule.slug = slug; + } - const openUrl = (path: string) => { - ideMessenger.request("controlPlane/openUrl", { - path, - orgSlug: undefined, - }); - hideLump(); - }; + index++; + } + } + } catch (e) { + console.error( + "Rules notch section: failed to parse selected profile", + e, + ); + } + } + // Add a displayed rule for the base system chat message when in chat mode + if (mode === "chat") { + const baseMessage = + config.selectedModelByRole.chat?.baseChatSystemMessage; + if (baseMessage) { + rules.unshift({ + rule: baseMessage, + source: "model-chat-options", + }); + } else { + rules.unshift({ + rule: DEFAULT_CHAT_SYSTEM_MESSAGE, + source: "default", + }); + } + } + + return rules; + }, [config, selectedProfile, mode]); return ( -
-
- {mergedRules.map((rule, index) => { - if (!rule.ruleFromYaml) { - return ( - { - ideMessenger.post("config/openProfile", { - profileId: undefined, - }); - hideLump(); - }} - title="Locally Defined Rule" - /> - ); - } - - if (typeof rule.ruleFromYaml === "string") { - const slug = `${selectedProfile?.fullSlug.ownerSlug}/${selectedProfile?.fullSlug.packageSlug}`; - - return ( - openUrl(`${slug}/new-version`)} - title="Inline Rule" - /> - ); - } - - if ("uses" in rule.ruleFromYaml) { - const ruleSlug = rule.ruleFromYaml?.uses; - - return ( - openUrl(`${ruleSlug}/new-version`)} - title={ruleSlug} - /> - ); - } - - // TODO: Handle rules as object with 'if' - return null; - })} -
+
+ {sortedRules.map((rule, index) => ( + + ))}
); diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx index c414d7f1c..8055e7fa9 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/CodeBlock/CodeBlockPreview.tsx @@ -6,7 +6,7 @@ import { useContext, useMemo } from "react"; import { vscBadgeBackground } from "../../../.."; import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; import FileIcon from "../../../../FileIcon"; -import StyledMarkdownPreview from "../../../../markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../../../../StyledMarkdownPreview"; import { ExpandableToolbarPreview } from "../../components/ExpandableToolbarPreview"; import { NodeViewWrapper } from "../../components/NodeViewWrapper"; diff --git a/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx b/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx index a89ba2e6a..40e3c8d2b 100644 --- a/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ThinkingBlockPeek.tsx @@ -6,7 +6,7 @@ import { useEffect, useState } from "react"; import styled from "styled-components"; import { defaultBorderRadius, lightGray, vscBackground } from "../.."; import { getFontSize } from "../../../util"; -import StyledMarkdownPreview from "../../markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../../StyledMarkdownPreview"; const SpoilerButton = styled.div` background-color: ${vscBackground}; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx b/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx deleted file mode 100644 index 7b204190b..000000000 --- a/gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { getLastNPathParts } from "core/util/uri"; -import FileIcon from "../../FileIcon"; - -export interface FileInfoProps { - filepath: string; - onClick: () => void; - range?: string; -} - -export const FileInfo = ({ filepath, range, onClick }: FileInfoProps) => { - return ( -
-
- -
- - {getLastNPathParts(filepath, 1)} - {range && ` ${range}`} - -
- ); -}; diff --git a/gui/src/components/markdown/StepContainerPreToolbar/InsertButton.tsx b/gui/src/components/markdown/StepContainerPreToolbar/InsertButton.tsx deleted file mode 100644 index 7d56e012b..000000000 --- a/gui/src/components/markdown/StepContainerPreToolbar/InsertButton.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { ArrowLeftEndOnRectangleIcon } from "@heroicons/react/24/outline"; -import { lightGray } from "../.."; - -/** - * Button that inserts code at the current cursor position - */ -interface InsertButtonProps { - onInsert: () => void; -} - -export default function InsertButton({ onInsert }: InsertButtonProps) { - return ( -
-
- -
-
- ); -} diff --git a/gui/src/components/markdown/StepContainerPreToolbar/index.ts b/gui/src/components/markdown/StepContainerPreToolbar/index.ts deleted file mode 100644 index 6e974689a..000000000 --- a/gui/src/components/markdown/StepContainerPreToolbar/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { default } from "./StepContainerPreToolbar"; diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index 329a1ee38..de255fe51 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -29,7 +29,6 @@ interface AuthContextType { selectedProfile: ProfileDescription | null; profiles: ProfileDescription[] | null; refreshProfiles: () => void; - controlServerBetaEnabled: boolean; organizations: OrganizationDescription[]; } @@ -117,18 +116,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ [], ); - const [controlServerBetaEnabled, setControlServerBetaEnabled] = - useState(false); - - // Hacky, remove once continue for teams is deprecated - useWebviewListener( - "configUpdate", - async (msg) => { - setControlServerBetaEnabled(msg.usingContinueForTeams); - }, - [], - ); - const refreshProfiles = useCallback(async () => { try { await ideMessenger.request("config/refreshProfiles", undefined); @@ -149,7 +136,6 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ profiles: currentOrg?.profiles ?? [], refreshProfiles, organizations: orgs, - controlServerBetaEnabled, }} > {children} diff --git a/gui/src/hooks/index.ts b/gui/src/hooks/index.ts new file mode 100644 index 000000000..8688c91e5 --- /dev/null +++ b/gui/src/hooks/index.ts @@ -0,0 +1 @@ +export * from "./useIdeMessengerRequest"; diff --git a/gui/src/hooks/useIdeMessengerRequest.ts b/gui/src/hooks/useIdeMessengerRequest.ts new file mode 100644 index 000000000..f03a17571 --- /dev/null +++ b/gui/src/hooks/useIdeMessengerRequest.ts @@ -0,0 +1,44 @@ +import type { FromWebviewProtocol } from "core/protocol"; +import type { SuccessWebviewSingleMessage } from "core/protocol/util"; +import { useContext, useEffect, useState } from "react"; +import { IdeMessengerContext } from "../context/IdeMessenger"; + +/** + * Generic hook for making IDE messenger requests with automatic error handling and refresh capability + */ +export function useIdeMessengerRequest( + messageType: T, + data: FromWebviewProtocol[T][0] | null, +) { + const ideMessenger = useContext(IdeMessengerContext); + const [result, setResult] = useState< + SuccessWebviewSingleMessage["content"] | null + >(null); + const [isLoading, setIsLoading] = useState(false); + + async function makeRequest() { + if (!data) { + setResult(null); + return; + } + + setIsLoading(true); + try { + const response = await ideMessenger.request(messageType, data); + if (response.status === "success") { + setResult(response.content); + } else { + console.error(`Error in ${messageType} request:`, response.error); + setResult(null); + } + } finally { + setIsLoading(false); + } + } + + useEffect(() => { + makeRequest(); + }, [data, messageType]); + + return { result, isLoading, refresh: makeRequest }; +} diff --git a/gui/src/pages/config/UserSettingsForm.tsx b/gui/src/pages/config/UserSettingsForm.tsx index 152d701ae..6c7d7c325 100644 --- a/gui/src/pages/config/UserSettingsForm.tsx +++ b/gui/src/pages/config/UserSettingsForm.tsx @@ -8,7 +8,6 @@ import { Input } from "../../components"; import NumberInput from "../../components/gui/NumberInput"; import { Select } from "../../components/gui/Select"; import ToggleSwitch from "../../components/gui/Switch"; -import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { updateConfig } from "../../redux/slices/configSlice"; @@ -17,7 +16,6 @@ import { getFontSize } from "../../util"; export function UserSettingsForm() { /////// User settings section ////// const dispatch = useAppDispatch(); - const { controlServerBetaEnabled } = useAuth(); const ideMessenger = useContext(IdeMessengerContext); const config = useAppSelector((state) => state.config.config); @@ -118,7 +116,7 @@ export function UserSettingsForm() {
) : null} */} - {!controlServerBetaEnabled || hubEnabled ? ( + {hubEnabled ? (

User settings

diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 40db6fd8c..751398410 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -13,6 +13,7 @@ import { useCallback, useContext, useEffect, useRef, useState } from "react"; import { ErrorBoundary } from "react-error-boundary"; import styled from "styled-components"; import { Button, lightGray, vscBackground } from "../../components"; +import AcceptRejectAllButtons from "../../components/AcceptRejectAllButtons"; import CodeToEditCard from "../../components/CodeToEditCard"; import FeedbackDialog from "../../components/dialogs/FeedbackDialog"; import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog"; @@ -24,7 +25,6 @@ import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils"; import { useOnboardingCard } from "../../components/OnboardingCard"; import StepContainer from "../../components/StepContainer"; -import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons"; import { TabBar } from "../../components/TabBar/TabBar"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useWebviewListener } from "../../hooks/useWebviewListener"; diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index e3b0002e1..7e50b7305 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -1,5 +1,5 @@ import { getMarkdownLanguageTagForFile } from "core/util"; -import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview"; interface CreateFileToolCallProps { relativeFilepath: string; diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index f1592a7fe..304dcb4c7 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -1,7 +1,7 @@ import { getMarkdownLanguageTagForFile } from "core/util"; import { useMemo } from "react"; -import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; -import AcceptRejectAllButtons from "../../../components/StepContainer/AcceptRejectAllButtons"; +import AcceptRejectAllButtons from "../../../components/AcceptRejectAllButtons"; +import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview"; import { useAppSelector } from "../../../redux/hooks"; type EditToolCallProps = { diff --git a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx index 4bb104cce..e8c9772a9 100644 --- a/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx +++ b/gui/src/pages/gui/ToolCallDiv/RunTerminalCommand.tsx @@ -1,5 +1,5 @@ import { ToolCallState } from "core"; -import StyledMarkdownPreview from "../../../components/markdown/StyledMarkdownPreview"; +import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview"; interface RunTerminalCommandToolCallProps { command: string; diff --git a/gui/src/redux/slices/configSlice.ts b/gui/src/redux/slices/configSlice.ts index 9c33ec3ff..c19bf7c97 100644 --- a/gui/src/redux/slices/configSlice.ts +++ b/gui/src/redux/slices/configSlice.ts @@ -41,6 +41,7 @@ const EMPTY_CONFIG: BrowserSerializedContinueConfig = { rerank: null, embed: null, }, + rules: [], }; const initialState: ConfigState = { diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index c5442da55..63b5e6189 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -88,6 +88,8 @@ export const streamResponseThunk = createAsyncThunk< const messages = constructMessages( [...updatedHistory], selectedChatModel?.baseChatSystemMessage, + state.config.config.rules, + selectedChatModel.model, ); posthog.capture("step run", { diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 9cb6a657f..5a0083886 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -62,7 +62,10 @@ export const streamResponseAfterToolCall = createAsyncThunk< const messages = constructMessages( [...updatedHistory], selectedChatModel?.baseChatSystemMessage, + state.config.config.rules, + selectedChatModel.model, ); + unwrapResult(await dispatch(streamNormalInput({ messages }))); }), ); diff --git a/packages/config-yaml/.gitignore b/packages/config-yaml/.gitignore new file mode 100644 index 000000000..b73759d7b --- /dev/null +++ b/packages/config-yaml/.gitignore @@ -0,0 +1 @@ +schema/ \ No newline at end of file diff --git a/packages/config-yaml/package-lock.json b/packages/config-yaml/package-lock.json index 4e5b8df05..7af4afcc8 100644 --- a/packages/config-yaml/package-lock.json +++ b/packages/config-yaml/package-lock.json @@ -22,7 +22,8 @@ "cross-env": "^7.0.3", "jest": "^29.7.0", "ts-jest": "^29.2.3", - "ts-node": "^10.9.2" + "ts-node": "^10.9.2", + "zod-to-json-schema": "^3.24.5" } }, "node_modules/@ampproject/remapping": { @@ -3823,6 +3824,16 @@ "funding": { "url": "https://github.com/sponsors/colinhacks" } + }, + "node_modules/zod-to-json-schema": { + "version": "3.24.5", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.24.5.tgz", + "integrity": "sha512-/AuWwMP+YqiPbsJx5D6TfgRTc4kTLjsh5SOcd4bLsfUg2RcEXrFMJl1DGgdHy2aCfsIA/cr/1JM0xcB2GZji8g==", + "dev": true, + "license": "ISC", + "peerDependencies": { + "zod": "^3.24.1" + } } } } diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index f32235580..c2dfb6362 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -10,7 +10,8 @@ }, "scripts": { "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest", - "build": "tsc" + "build": "tsc", + "generate-schema": "tsc && node dist/scripts/generateJsonSchema.js" }, "author": "Continue Dev, Inc.", "license": "Apache-2.0", @@ -25,6 +26,7 @@ "cross-env": "^7.0.3", "jest": "^29.7.0", "ts-jest": "^29.2.3", - "ts-node": "^10.9.2" + "ts-node": "^10.9.2", + "zod-to-json-schema": "^3.24.5" } } diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index 026c7e181..e0e440bb0 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -337,7 +337,7 @@ export async function unrollBlocks( } } - // Rules are a bit different because they can be strings, so hanlde separately + // Rules are a bit different because they can be strings, so handle separately if (assistant.rules) { const rules: (Rule | null)[] = []; for (const rule of assistant.rules) { diff --git a/packages/config-yaml/src/schemas/commonSlugs.ts b/packages/config-yaml/src/schemas/commonSlugs.ts new file mode 100644 index 000000000..3ba10bbd5 --- /dev/null +++ b/packages/config-yaml/src/schemas/commonSlugs.ts @@ -0,0 +1,30 @@ +export const commonModelSlugs = [ + "anthropic/claude-3-7-sonnet", + "togetherai/llama-4-maverick-instruct-17bx128e", + "google/gemini-2.5-pro", + "mistral/codestral", + "voyageai/voyage-code-3", + "relace/instant-apply", + "xai/grok-2", + "openai/gpt-4o", + "togetherai/llama-4-scout-instruct-17bx16e", + "anthropic/claude-3-5-sonnet", + "google/gemini-2.0-flash", + "voyageai/rerank-2", + "ollama/deepseek-r1", + "morphllm/morph-v0", + "anthropic/claude-3-5-haiku", + "lmstudio/deepseek-r1", + "openai/o3-mini", + "voyageai/voyage-code-2", + "ollama/qwen2.5-coder-1.5b", + "openai/gpt-4o-mini", + "openai/o1", + "mistral/mistral-embed", + "ollama/nomic-embed-text-latest", + "lmstudio/deepseek-r1-8b", + "mistral/mistral-large", + "lmstudio/qwen2.5-coder-1.5b", + "ollama/deepseek-r1-8b", + "openai/text-embedding-3-large", +]; diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 2b2ba0461..521dcab3e 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -1,4 +1,5 @@ import * as z from "zod"; +import { commonModelSlugs } from "./commonSlugs.js"; import { dataSchema } from "./data/index.js"; import { modelSchema, partialModelSchema } from "./models.js"; @@ -15,12 +16,16 @@ const mcpServerSchema = z.object({ env: z.record(z.string()).optional(), }); +export type MCPServer = z.infer; + const promptSchema = z.object({ name: z.string(), description: z.string().optional(), prompt: z.string(), }); +export type Prompt = z.infer; + const docSchema = z.object({ name: z.string(), startUrl: z.string(), @@ -28,6 +33,8 @@ const docSchema = z.object({ faviconUrl: z.string().optional(), }); +export type DocsConfig = z.infer; + const ruleObjectSchema = z.object({ name: z.string(), rule: z.string(), @@ -38,15 +45,22 @@ const ruleSchema = z.union([z.string(), ruleObjectSchema]); export type Rule = z.infer; -export const blockItemWrapperSchema = (schema: T) => +const defaultUsesSchema = z.string(); + +export const blockItemWrapperSchema = ( + schema: T, + usesSchema: z.ZodTypeAny = defaultUsesSchema, +) => z.object({ - uses: z.string(), + uses: usesSchema, with: z.record(z.string()).optional(), override: schema.partial().optional(), }); -export const blockOrSchema = (schema: T) => - z.union([schema, blockItemWrapperSchema(schema)]); +export const blockOrSchema = ( + schema: T, + usesSchema: z.ZodTypeAny = defaultUsesSchema, +) => z.union([schema, blockItemWrapperSchema(schema, usesSchema)]); export const commonMetadataSchema = z.object({ tags: z.string().optional(), @@ -64,13 +78,17 @@ export const baseConfigYamlSchema = z.object({ metadata: z.record(z.string()).and(commonMetadataSchema.partial()).optional(), }); +const modelsUsesSchema = z + .string() + .or(z.enum(commonModelSlugs as [string, ...string[]])); + export const configYamlSchema = baseConfigYamlSchema.extend({ models: z .array( z.union([ modelSchema, z.object({ - uses: z.string(), + uses: modelsUsesSchema, with: z.record(z.string()).optional(), override: partialModelSchema.optional(), }), @@ -85,7 +103,7 @@ export const configYamlSchema = baseConfigYamlSchema.extend({ z.union([ ruleSchema, z.object({ - uses: z.string(), + uses: defaultUsesSchema, with: z.record(z.string()).optional(), }), ]), diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index 2334b4c7c..ad3318a15 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -80,6 +80,7 @@ const baseModelFields = { embedOptions: embedOptionsSchema.optional(), chatOptions: chatOptionsSchema.optional(), promptTemplates: promptTemplatesSchema.optional(), + useLegacyCompletionsEndpoint: z.boolean().optional(), env: z .record(z.string(), z.union([z.string(), z.boolean(), z.number()])) .optional(), diff --git a/packages/config-yaml/src/scripts/generateJsonSchema.ts b/packages/config-yaml/src/scripts/generateJsonSchema.ts new file mode 100644 index 000000000..308dcf951 --- /dev/null +++ b/packages/config-yaml/src/scripts/generateJsonSchema.ts @@ -0,0 +1,28 @@ +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import { zodToJsonSchema } from 'zod-to-json-schema'; +import { configYamlSchema } from '../schemas/index.js'; + +// Get the directory name of the current module +const __dirname = path.dirname(fileURLToPath(import.meta.url)); + +// Convert Zod schema to JSON schema +const jsonSchema = zodToJsonSchema(configYamlSchema, { + $refStrategy: 'none', + name: 'ConfigYaml', +}); + +// Output directory and file path +const outDir = path.resolve(__dirname, '../../schema'); +const outFile = path.join(outDir, 'config-yaml-schema.json'); + +// Ensure output directory exists +if (!fs.existsSync(outDir)) { + fs.mkdirSync(outDir, { recursive: true }); +} + +// Write the JSON schema to file +fs.writeFileSync(outFile, JSON.stringify(jsonSchema, null, 2)); + +console.log(`JSON schema has been written to ${outFile}`); \ No newline at end of file diff --git a/packages/openai-adapters/src/apis/Gemini.ts b/packages/openai-adapters/src/apis/Gemini.ts index ab76a28d0..23b3af58d 100644 --- a/packages/openai-adapters/src/apis/Gemini.ts +++ b/packages/openai-adapters/src/apis/Gemini.ts @@ -114,7 +114,7 @@ export class GeminiApi implements BaseLlmApi { return null; // Don't include system message in contents } - if (msg.role == "assistant" && msg.tool_calls?.length) { + if (msg.role === "assistant" && msg.tool_calls?.length) { for (const toolCall of msg.tool_calls) { toolCallIdToNameMap.set(toolCall.id, toolCall.function.name); } @@ -171,7 +171,7 @@ export class GeminiApi implements BaseLlmApi { const finalBody: any = { generationConfig, contents, - // if this.systemMessage is defined, reformat it for Gemini API + // if there is a system message, reformat it for Gemini API ...(sysMsg && !isV1API && { systemInstruction: { parts: [{ text: sysMsg.content }] }, diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index ab72a85b1..745b94186 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -37,18 +37,23 @@ export class OpenAIApi implements BaseLlmApi { modifyChatBody(body: T): T { // o-series models - only apply for official OpenAI API const isOfficialOpenAIAPI = this.apiBase === "https://api.openai.com/v1/"; - if (isOfficialOpenAIAPI && body.model.startsWith("o")) { - // a) use max_completion_tokens instead of max_tokens - body.max_completion_tokens = body.max_tokens; - body.max_tokens = undefined; + if (isOfficialOpenAIAPI) { + if (body.model.startsWith("o")) { + // a) use max_completion_tokens instead of max_tokens + body.max_completion_tokens = body.max_tokens; + body.max_tokens = undefined; - // b) use "developer" message role rather than "system" - body.messages = body.messages.map((message) => { - if (message.role === "system") { - return { ...message, role: "developer" } as any; - } - return message; - }); + // b) use "developer" message role rather than "system" + body.messages = body.messages.map((message) => { + if (message.role === "system") { + return { ...message, role: "developer" } as any; + } + return message; + }); + } + if (body.tools?.length && !body.model.startsWith("o3")) { + body.parallel_tool_calls = false; + } } return body; }