diff --git a/binary/package-lock.json b/binary/package-lock.json index 85720e9fd..51ea6b1f1 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -48,7 +48,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.71", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -67,6 +67,7 @@ "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", + "filtrex": "^3.1.0", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", "handlebars": "^4.7.8", diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index 79b598f1e..7a29f8a8f 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -88,7 +88,6 @@ export class RootPathContextService { default: // const type = node.type; // console.log(getSyntaxTreeString(node)); - // debugger; query = await getQueryForFile( filepath, @@ -165,7 +164,6 @@ export class RootPathContextService { )) { const key = RootPathContextService.keyFromNode(parentKey, astNode); // const type = astNode.type; - // debugger; const foundInCache = this.cache.get(key); const newSnippets = diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index f2fefbb39..f157bf21d 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -127,7 +127,7 @@ async function configYamlToContinueConfig( models: [], tools: [...allTools], mcpServerStatuses: [], - systemMessage: config.rules?.join("\n"), + systemMessage: undefined, experimental: { modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({ transport: { @@ -211,15 +211,15 @@ async function configYamlToContinueConfig( for (const model of config.models ?? []) { model.roles = model.roles ?? modelsArrayRoles; // Default to all 4 chat-esque roles if not specified try { - const llms = await llmsFromModelConfig( + const llms = await llmsFromModelConfig({ model, ide, uniqueId, ideSettings, writeLog, platformConfigMetadata, - continueConfig.systemMessage, - ); + config: continueConfig, + }); if (modelsArrayRoles.some((role) => model.roles?.includes(role))) { continueConfig.models.push(...llms); diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index e9d5bd55c..6eabfd040 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -1,6 +1,6 @@ import { ModelConfig } from "@continuedev/config-yaml"; -import { IDE, IdeSettings, LLMOptions } from "../.."; +import { ContinueConfig, IDE, IdeSettings, LLMOptions } from "../.."; import { BaseLLM } from "../../llm"; import { LLMClasses } from "../../llm/llms"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; @@ -13,22 +13,29 @@ function getModelClass( return LLMClasses.find((llm) => llm.providerName === model.provider); } -function getContinueProxyModelName( - ownerSlug: string, - packageSlug: string, - model: ModelConfig, -): string { - return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`; -} +// function getContinueProxyModelName( +// ownerSlug: string, +// packageSlug: string, +// model: ModelConfig, +// ): string { +// return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`; +// } -async function modelConfigToBaseLLM( - model: ModelConfig, - uniqueId: string, - ideSettings: IdeSettings, - writeLog: (log: string) => Promise, - platformConfigMetadata: PlatformConfigMetadata | undefined, - systemMessage: string | undefined, -): Promise { +async function modelConfigToBaseLLM({ + model, + uniqueId, + ideSettings, + writeLog, + platformConfigMetadata, + config, +}: { + model: ModelConfig; + uniqueId: string; + ideSettings: IdeSettings; + writeLog: (log: string) => Promise; + platformConfigMetadata: PlatformConfigMetadata | undefined; + config: ContinueConfig; +}): Promise { const cls = getModelClass(model); if (!cls) { @@ -50,7 +57,8 @@ async function modelConfigToBaseLLM( writeLog, uniqueId, title: model.name, - systemMessage, + systemMessage: config.systemMessage, + rules: config.rules, promptTemplates: model.promptTemplates, capabilities: { tools: model.capabilities?.includes("tool_use"), @@ -127,16 +135,25 @@ async function modelConfigToBaseLLM( return llm; } -async function autodetectModels( - llm: BaseLLM, - model: ModelConfig, - ide: IDE, - uniqueId: string, - ideSettings: IdeSettings, - writeLog: (log: string) => Promise, - platformConfigMetadata: PlatformConfigMetadata | undefined, - systemMessage: string | undefined, -): Promise { +async function autodetectModels({ + llm, + model, + ide, + uniqueId, + ideSettings, + writeLog, + platformConfigMetadata, + config, +}: { + llm: BaseLLM; + model: ModelConfig; + ide: IDE; + uniqueId: string; + ideSettings: IdeSettings; + writeLog: (log: string) => Promise; + platformConfigMetadata: PlatformConfigMetadata | undefined; + config: ContinueConfig; +}): Promise { try { const modelNames = await llm.listModels(); const detectedModels = await Promise.all( @@ -146,8 +163,8 @@ async function autodetectModels( return undefined; } - return await modelConfigToBaseLLM( - { + return await modelConfigToBaseLLM({ + model: { ...model, model: modelName, name: modelName, @@ -156,8 +173,8 @@ async function autodetectModels( ideSettings, writeLog, platformConfigMetadata, - systemMessage, - ); + config, + }); }), ); return detectedModels.filter((x) => typeof x !== "undefined") as BaseLLM[]; @@ -167,38 +184,46 @@ async function autodetectModels( } } -export async function llmsFromModelConfig( - model: ModelConfig, - ide: IDE, - uniqueId: string, - ideSettings: IdeSettings, - writeLog: (log: string) => Promise, - platformConfigMetadata: PlatformConfigMetadata | undefined, - systemMessage: string | undefined, -): Promise { - const baseLlm = await modelConfigToBaseLLM( +export async function llmsFromModelConfig({ + model, + ide, + uniqueId, + ideSettings, + writeLog, + platformConfigMetadata, + config, +}: { + model: ModelConfig; + ide: IDE; + uniqueId: string; + ideSettings: IdeSettings; + writeLog: (log: string) => Promise; + platformConfigMetadata: PlatformConfigMetadata | undefined; + config: ContinueConfig; +}): Promise { + const baseLlm = await modelConfigToBaseLLM({ model, uniqueId, ideSettings, writeLog, platformConfigMetadata, - systemMessage, - ); + config, + }); if (!baseLlm) { return []; } if (model.model === AUTODETECT) { - const models = await autodetectModels( - baseLlm, + const models = await autodetectModels({ + llm: baseLlm, model, ide, uniqueId, ideSettings, writeLog, platformConfigMetadata, - systemMessage, - ); + config, + }); return models; } else { return [baseLlm]; diff --git a/core/index.d.ts b/core/index.d.ts index ba97377d3..9a6a40c21 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,4 +1,4 @@ -import { DataDestination, ModelRole } from "@continuedev/config-yaml"; +import { DataDestination, ModelRole, Rule } from "@continuedev/config-yaml"; import Parser from "web-tree-sitter"; import { GetGhTokenArgs } from "./protocol/ide"; declare global { @@ -497,6 +497,7 @@ export interface LLMOptions { templateMessages?: (messages: ChatMessage[]) => string; writeLog?: (str: string) => Promise; llmRequestHook?: (model: string, prompt: string) => any; + rules?: Rule[]; apiKey?: string; // continueProperties @@ -1312,7 +1313,7 @@ export interface ContinueConfig { docs?: SiteIndexingConfig[]; tools: Tool[]; mcpServerStatuses: MCPServerStatus[]; - rules?: string[]; + rules?: Rule[]; modelsByRole: Record; selectedModelByRole: Record; data?: DataDestination[]; @@ -1335,7 +1336,7 @@ export interface BrowserSerializedContinueConfig { docs?: SiteIndexingConfig[]; tools: Tool[]; mcpServerStatuses: MCPServerStatus[]; - rules?: string[]; + rules?: Rule[]; usePlatform: boolean; tabAutocompleteOptions?: Partial; modelsByRole: Record; diff --git a/core/llm/countTokens.test.ts b/core/llm/countTokens.test.ts index 6895e9269..92f9d92c5 100644 --- a/core/llm/countTokens.test.ts +++ b/core/llm/countTokens.test.ts @@ -1,3 +1,4 @@ +// @ts-nocheck // Generated by continue import { ChatMessage, MessagePart } from "../index.js"; import { diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 2973cba20..2fc01f9b8 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -1,7 +1,13 @@ import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; -import { ChatMessage, MessageContent, MessagePart } from "../index.js"; +import { + ChatMessage, + MessageContent, + MessagePart, + UserChatMessage, +} from "../index.js"; +import { Rule } from "@continuedev/config-yaml"; import { renderChatMessage } from "../util/messageContent.js"; import { AsyncEncoder, @@ -11,6 +17,8 @@ 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"; interface Encoding { encode: Tiktoken["encode"]; decode: Tiktoken["decode"]; @@ -399,16 +407,127 @@ function chatMessageIsEmpty(message: ChatMessage): boolean { } } -function compileChatMessages( - modelName: string, - msgs: ChatMessage[] | undefined, - contextLength: number, - maxTokens: number, - supportsImages: boolean, - prompt: string | undefined = undefined, - functions: any[] | undefined = undefined, - systemMessage: string | undefined = undefined, -): ChatMessage[] { +function addSystemMessage({ + messages, + systemMessage, + originalMessages, +}: { + messages: ChatMessage[]; + systemMessage: string | undefined; + originalMessages: ChatMessage[] | undefined; +}): ChatMessage[] { + if ( + !(systemMessage && systemMessage.trim() !== "") && + originalMessages?.[0]?.role !== "system" + ) { + return messages; + } + + 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; +} + +function compileChatMessages({ + modelName, + msgs, + contextLength, + maxTokens, + supportsImages, + prompt, + functions, + systemMessage, + rules, +}: { + modelName: string; + msgs: ChatMessage[] | undefined; + 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 })) @@ -425,29 +544,19 @@ function compileChatMessages( msgsCopy.push(promptMsg); } - if ( - (systemMessage && systemMessage.trim() !== "") || - msgs?.[0]?.role === "system" - ) { - let content = ""; - if (msgs?.[0]?.role === "system") { - content = renderChatMessage(msgs?.[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 - // Later moved to top, but want second-priority to last user message - msgsCopy.splice(-1, 0, systemChatMsg); - } + const lastUserMessage = getLastUserMessage(msgsCopy); + + msgsCopy = addSystemMessage({ + messages: msgsCopy, + systemMessage: + systemMessage ?? + getSystemMessage({ + userMessage: lastUserMessage, + rules, + currentModel: modelName, + }), + originalMessages: msgs, + }); let functionTokens = 0; if (functions) { diff --git a/core/llm/index.ts b/core/llm/index.ts index 028bc42c3..cc7d7123c 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -1,4 +1,4 @@ -import { ModelRole } from "@continuedev/config-yaml"; +import { ModelRole, Rule } from "@continuedev/config-yaml"; import { fetchwithRequestOptions } from "@continuedev/fetch"; import { findLlmInfo } from "@continuedev/llm-info"; import { @@ -143,6 +143,7 @@ export abstract class BaseLLM implements ILLM { cacheBehavior?: CacheBehavior; capabilities?: ModelCapability; roles?: ModelRole[]; + rules?: Rule[]; deployment?: string; apiVersion?: string; @@ -242,6 +243,7 @@ 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; @@ -286,21 +288,17 @@ export abstract class BaseLLM implements ILLM { CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH; } - return compileChatMessages( - options.model, - messages, + return compileChatMessages({ + modelName: options.model, + msgs: messages, contextLength, - options.maxTokens ?? DEFAULT_MAX_TOKENS, - this.supportsImages(), - undefined, + maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, + supportsImages: this.supportsImages(), + prompt: undefined, functions, - this.systemMessage, - ); - } - - private _getSystemMessage(): string | undefined { - // TODO: Merge with config system message - return this.systemMessage; + systemMessage: this.systemMessage, + rules: this.rules ?? [], + }); } private _templatePromptLikeMessages(prompt: string): string { @@ -310,7 +308,7 @@ export abstract class BaseLLM implements ILLM { const msgs: ChatMessage[] = [{ role: "user", content: prompt }]; - const systemMessage = this._getSystemMessage(); + const systemMessage = this.systemMessage; if (systemMessage) { msgs.unshift({ role: "system", content: systemMessage }); } diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 573170ece..7fefbd329 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -4,7 +4,7 @@ import { ConverseStreamCommand, ConverseStreamCommandOutput, InvokeModelCommand, - Message + Message, } from "@aws-sdk/client-bedrock-runtime"; import { fromNodeProviderChain } from "@aws-sdk/credential-providers"; @@ -12,7 +12,7 @@ import { ChatMessage, Chunk, CompletionOptions, - LLMOptions + LLMOptions, } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; @@ -52,10 +52,14 @@ class Bedrock extends BaseLLM { private _currentToolResponse: Partial | null = null; private _promptCachingMetrics: PromptCachingMetrics = { cacheReadInputTokens: 0, - cacheWriteInputTokens: 0 + cacheWriteInputTokens: 0, }; - public requestOptions: { region?: string; credentials?: any; headers?: Record }; + public requestOptions: { + region?: string; + credentials?: any; + headers?: Record; + }; constructor(options: LLMOptions) { super(options); @@ -121,12 +125,17 @@ class Bedrock extends BaseLLM { }, ); - const input = this._generateConverseInput(messages, { ...options, stream: true }); + const input = this._generateConverseInput(messages, { + ...options, + stream: true, + }); const command = new ConverseStreamCommand(input); let response: ConverseStreamCommandOutput; try { - response = await client.send(command, { abortSignal: signal }) as ConverseStreamCommandOutput; + response = (await client.send(command, { + abortSignal: signal, + })) as ConverseStreamCommandOutput; } catch (error: unknown) { console.error(error); const message = error instanceof Error ? error.message : "Unknown error"; @@ -140,9 +149,9 @@ class Bedrock extends BaseLLM { // Reset cache metrics for new request this._promptCachingMetrics = { cacheReadInputTokens: 0, - cacheWriteInputTokens: 0 + cacheWriteInputTokens: 0, }; - + try { for await (const chunk of response.stream) { if (chunk.metadata?.usage) { @@ -150,47 +159,69 @@ class Bedrock extends BaseLLM { } if (chunk.contentBlockDelta?.delta) { - - const delta: any = chunk.contentBlockDelta.delta + const delta: any = chunk.contentBlockDelta.delta; // Handle text content if (chunk.contentBlockDelta.delta.text) { - yield { role: "assistant", content: chunk.contentBlockDelta.delta.text }; + yield { + role: "assistant", + content: chunk.contentBlockDelta.delta.text, + }; continue; } // Handle text content if ((chunk.contentBlockDelta.delta as any).reasoningContent?.text) { - yield { role: "thinking", content: (chunk.contentBlockDelta.delta as any).reasoningContent.text }; + yield { + role: "thinking", + content: (chunk.contentBlockDelta.delta as any).reasoningContent + .text, + }; continue; } // Handle signature for thinking if (delta.reasoningContent?.signature) { - yield { role: "thinking", content: "", signature: delta.reasoningContent.signature }; + yield { + role: "thinking", + content: "", + signature: delta.reasoningContent.signature, + }; continue; } // Handle redacted thinking if (delta.redactedReasoning?.data) { - yield { role: "thinking", content: "", redactedThinking: delta.redactedReasoning.data }; + yield { + role: "thinking", + content: "", + redactedThinking: delta.redactedReasoning.data, + }; continue; } - if (chunk.contentBlockDelta.delta.toolUse?.input && this._currentToolResponse) { + if ( + chunk.contentBlockDelta.delta.toolUse?.input && + this._currentToolResponse + ) { // Append the new input to the existing string if (this._currentToolResponse.input === undefined) { this._currentToolResponse.input = ""; } - this._currentToolResponse.input += chunk.contentBlockDelta.delta.toolUse.input; + this._currentToolResponse.input += + chunk.contentBlockDelta.delta.toolUse.input; continue; } } if (chunk.contentBlockStart?.start) { - const start: any = chunk.contentBlockStart.start + const start: any = chunk.contentBlockStart.start; if (start.redactedReasoning) { - yield { role: "thinking", content: "", redactedThinking: start.redactedReasoning.data }; + yield { + role: "thinking", + content: "", + redactedThinking: start.redactedReasoning.data, + }; continue; } @@ -199,7 +230,7 @@ class Bedrock extends BaseLLM { this._currentToolResponse = { toolUseId: toolUse.toolUseId, name: toolUse.name, - input: "" + input: "", }; } continue; @@ -210,14 +241,16 @@ class Bedrock extends BaseLLM { yield { role: "assistant", content: "", - toolCalls: [{ - id: this._currentToolResponse.toolUseId, - type: "function", - function: { - name: this._currentToolResponse.name, - arguments: this._currentToolResponse.input - } - }], + toolCalls: [ + { + id: this._currentToolResponse.toolUseId, + type: "function", + function: { + name: this._currentToolResponse.name, + arguments: this._currentToolResponse.input, + }, + }, + ], }; this._currentToolResponse = null; } @@ -229,13 +262,16 @@ class Bedrock extends BaseLLM { if (error instanceof Error) { if ("code" in error) { // AWS SDK specific errors - throw new Error(`AWS Bedrock stream error (${(error as any).code}): ${error.message}`); + throw new Error( + `AWS Bedrock stream error (${(error as any).code}): ${error.message}`, + ); } throw new Error(`Error processing Bedrock stream: ${error.message}`); } - throw new Error("Error processing Bedrock stream: Unknown error occurred"); + throw new Error( + "Error processing Bedrock stream: Unknown error occurred", + ); } - } /** @@ -252,39 +288,41 @@ class Bedrock extends BaseLLM { const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage; - const enablePromptCaching = shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation; + const enablePromptCaching = + shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation; // Add header for prompt caching if (enablePromptCaching) { this.requestOptions.headers = { ...this.requestOptions.headers, - "x-amzn-bedrock-enablepromptcaching": "true" + "x-amzn-bedrock-enablepromptcaching": "true", }; } - const supportsTools = PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false; + const supportsTools = + PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false; return { modelId: options.model, messages: convertedMessages, - system: this.systemMessage ? ( - shouldCacheSystemMessage ? - [ - { text: this.systemMessage }, - { cachePoint: { type: "default" } } - ] : - [{ text: this.systemMessage }] - ) : undefined, - toolConfig: supportsTools && options.tools ? { - tools: options.tools.map(tool => ({ - toolSpec: { - name: tool.function.name, - description: tool.function.description, - inputSchema: { - json: tool.function.parameters + system: this.systemMessage + ? shouldCacheSystemMessage + ? [{ text: this.systemMessage }, { cachePoint: { type: "default" } }] + : [{ text: this.systemMessage }] + : undefined, + toolConfig: + supportsTools && options.tools + ? { + tools: options.tools.map((tool) => ({ + toolSpec: { + name: tool.function.name, + description: tool.function.description, + inputSchema: { + json: tool.function.parameters, + }, + }, + })), } - } - })) - } : undefined, + : undefined, inferenceConfig: { maxTokens: options.maxTokens, temperature: options.temperature, @@ -302,21 +340,28 @@ class Bedrock extends BaseLLM { .slice(0, 4), }, additionalModelRequestFields: { - "thinking": options.reasoning ? { - "type": "enabled", - "budget_tokens": options.reasoningBudgetTokens - } : undefined, - } + thinking: options.reasoning + ? { + type: "enabled", + budget_tokens: options.reasoningBudgetTokens, + } + : undefined, + }, }; } - private _convertMessage(message: ChatMessage, addCaching: boolean = false): Message | null { + private _convertMessage( + message: ChatMessage, + addCaching: boolean = false, + ): Message | null { // Handle system messages explicitly if (message.role === "system") { return null; } - const cachePoint = addCaching ? { cachePoint: { type: "default" } } : undefined; + const cachePoint = addCaching + ? { cachePoint: { type: "default" } } + : undefined; // Tool response handling if (message.role === "tool") { @@ -328,12 +373,12 @@ class Bedrock extends BaseLLM { toolUseId: message.toolCallId, content: [ { - text: message.content || "" - } - ] - } - } - ] + text: message.content || "", + }, + ], + }, + }, + ], }; } @@ -346,8 +391,8 @@ class Bedrock extends BaseLLM { toolUseId: toolCall.id, name: toolCall.function?.name, input: JSON.parse(toolCall.function?.arguments || "{}"), - } - })) + }, + })), }; } @@ -355,26 +400,27 @@ class Bedrock extends BaseLLM { if (message.redactedThinking) { const content: ContentBlock.ReasoningContentMember = { reasoningContent: { - redactedContent: new Uint8Array(Buffer.from(message.redactedThinking)) - } + redactedContent: new Uint8Array( + Buffer.from(message.redactedThinking), + ), + }, }; return { role: "assistant", - content: [content] + content: [content], }; } else { const content: ContentBlock.ReasoningContentMember = { reasoningContent: { reasoningText: { text: (message.content as string) || "", - signature: message.signature - } - - } + signature: message.signature, + }, + }, }; return { role: "assistant", - content: [content] + content: [content], }; } } @@ -387,7 +433,7 @@ class Bedrock extends BaseLLM { } return { role: message.role, - content + content, }; } @@ -396,7 +442,7 @@ class Bedrock extends BaseLLM { const content: any[] = []; // Process all parts first - message.content.forEach(part => { + message.content.forEach((part) => { if (part.type === "text") { content.push({ text: part.text }); } else if (part.type === "imageUrl" && part.imageUrl) { @@ -407,9 +453,9 @@ class Bedrock extends BaseLLM { image: { format, source: { - bytes: Buffer.from(base64Data, "base64") - } - } + bytes: Buffer.from(base64Data, "base64"), + }, + }, }); } catch (error) { console.warn(`Failed to process image: ${error}`); @@ -424,7 +470,7 @@ class Bedrock extends BaseLLM { return { role: message.role, - content + content, } as Message; } return null; @@ -439,22 +485,24 @@ class Bedrock extends BaseLLM { .filter((index) => index !== -1) .slice(-2); - const converted = filteredmessages.map((message, filteredMsgIdx) => { - // Add cache_control parameter to the last two user messages - // The second-to-last because it retrieves potentially already cached contents, - // The last one because we want it cached for later retrieval. - // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html - const addCaching = - this.cacheBehavior?.cacheConversation && - lastTwoUserMsgIndices.includes(filteredMsgIdx); + const converted = filteredmessages + .map((message, filteredMsgIdx) => { + // Add cache_control parameter to the last two user messages + // The second-to-last because it retrieves potentially already cached contents, + // The last one because we want it cached for later retrieval. + // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html + const addCaching = + this.cacheBehavior?.cacheConversation && + lastTwoUserMsgIndices.includes(filteredMsgIdx); - try { - return this._convertMessage(message, addCaching); - } catch (error) { - console.error(`Failed to convert message: ${error}`); - return null; - } - }).filter(Boolean); + try { + return this._convertMessage(message, addCaching); + } catch (error) { + console.error(`Failed to convert message: ${error}`); + return null; + } + }) + .filter(Boolean); return converted; } @@ -520,7 +568,6 @@ class Bedrock extends BaseLLM { return modelConfig.extractEmbeddings(responseBody); } - private _getModelConfig() { const modelConfigs: { [key: string]: ModelConfig } = { cohere: { @@ -558,7 +605,11 @@ class Bedrock extends BaseLLM { const credentials = await this._getCredentials(); const client = new BedrockRuntimeClient({ region: this.region, - credentials, + credentials: { + accessKeyId: credentials.accessKeyId, + secretAccessKey: credentials.secretAccessKey, + sessionToken: credentials.sessionToken || "", + }, }); // Base payload for both models @@ -597,11 +648,15 @@ class Bedrock extends BaseLLM { if (error instanceof Error) { if ("code" in error) { // AWS SDK specific errors - throw new Error(`AWS Bedrock rerank error (${(error as any).code}): ${error.message}`); + throw new Error( + `AWS Bedrock rerank error (${(error as any).code}): ${error.message}`, + ); } throw new Error(`Error in BedrockReranker.rerank: ${error.message}`); } - throw new Error("Error in BedrockReranker.rerank: Unknown error occurred"); + throw new Error( + "Error in BedrockReranker.rerank: Unknown error occurred", + ); } } } diff --git a/core/llm/rules/isRuleActive.test.ts b/core/llm/rules/isRuleActive.test.ts new file mode 100644 index 000000000..f50b9972a --- /dev/null +++ b/core/llm/rules/isRuleActive.test.ts @@ -0,0 +1,59 @@ +import { isRuleActive } from "./isRuleActive"; + +describe("isRuleActive", () => { + const rule = { + name: "My Rule", + rule: "Do no harm", + if: '${{ contains(current.model.model, "claude-3-7-sonnet") and glob("*.tsx") }}', + }; + + it("should return false when activePaths is empty", () => { + expect( + isRuleActive({ + rule, + activePaths: [], + currentModel: "claude-3-7-sonnet", + }), + ).toBe(false); + }); + + it("should return false when no matching paths exist", () => { + expect( + isRuleActive({ + rule, + activePaths: ["test.py", "main.js"], + currentModel: "claude-3-7-sonnet", + }), + ).toBe(false); + }); + + it("should return true when both conditions are met", () => { + expect( + isRuleActive({ + rule, + activePaths: ["Component.tsx", "main.js"], + currentModel: "claude-3-7-sonnet", + }), + ).toBe(true); + }); + + it("should return false when only glob matches but model doesn't", () => { + expect( + isRuleActive({ + rule, + activePaths: ["Component.tsx"], + currentModel: "gpt-4", + }), + ).toBe(false); + }); + + it("should return false when model matches but glob doesn't", () => { + expect( + isRuleActive({ + rule, + activePaths: ["Component.ts"], + currentModel: "claude-3-7-sonnet", + }), + ).toBe(false); + }); +}); diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts new file mode 100644 index 000000000..47125c644 --- /dev/null +++ b/core/llm/rules/isRuleActive.ts @@ -0,0 +1,68 @@ +import { Rule } from "@continuedev/config-yaml"; +import { compileExpression } from "filtrex"; +import { minimatch } from "minimatch"; + +const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/; + +const createGlobFunction = (activePaths: string[]) => { + return (pattern: string) => { + const result = activePaths.some((path) => minimatch(path, pattern)); + return result; + }; +}; + +const contains = (str: string, searchStr: string): boolean => { + return str.includes(searchStr); +}; + +const evaluateIf = ({ + condition, + activePaths, + currentModel, +}: { + condition: string; + activePaths: string[]; + currentModel: string; +}) => { + const expression = condition.match(TEMPLATE_VAR_REGEX)?.[1]?.trim(); + if (!expression) { + return true; + } + + try { + const evaluate = compileExpression(expression, { + extraFunctions: { + glob: createGlobFunction(activePaths), + contains, + }, + constants: { + "current.model.model": currentModel, + }, + }); + + return evaluate({}); + } catch (error) { + console.error("Error evaluating rule condition:", error); + return false; + } +}; + +export const isRuleActive = ({ + rule, + activePaths, + currentModel, +}: { + rule: Rule; + activePaths: string[]; + currentModel: string; +}): boolean => { + if (typeof rule === "string") { + return true; + } + + if (rule.if) { + return evaluateIf({ condition: rule.if, activePaths, currentModel }); + } + + return true; +}; diff --git a/core/llm/utils/extractPathsFromCodeBlocks.ts b/core/llm/utils/extractPathsFromCodeBlocks.ts new file mode 100644 index 000000000..7573a1f6f --- /dev/null +++ b/core/llm/utils/extractPathsFromCodeBlocks.ts @@ -0,0 +1,22 @@ +/** + * Extracts file paths from markdown code blocks + */ +export function extractPathsFromCodeBlocks(content: string): string[] { + // Match: + // 1. Starting ``` + // 2. Optional language identifier + // 3. Required whitespace + // 4. File path (captured) that must contain a dot and extension + const codeBlockRegex = /```(?:[\w-+#]+)?\s+([^\s\n()]+\.[a-zA-Z0-9]+)/g; + const paths: string[] = []; + let match; + + while ((match = codeBlockRegex.exec(content)) !== null) { + const path = match[1]; + if (path && !path.startsWith("```")) { + paths.push(path); + } + } + + return paths; +} diff --git a/core/package-lock.json b/core/package-lock.json index f56faf7e8..24aeb4f18 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.71", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -32,6 +32,7 @@ "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", + "filtrex": "^3.1.0", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", "handlebars": "^4.7.8", @@ -2976,9 +2977,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.67", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.67.tgz", - "integrity": "sha512-RbJXSH2Z9XmaN1h9Dm0Qfru7UeAdCAEWMiEgJ9A2FGHysR9oxbQDqptk1Y61oDSpYeX+lWsxkz/SFIc2PjNnKg==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.71.tgz", + "integrity": "sha512-c7KVaYfldaYHf2EqeqE9Oo1son33iTp6MAY+WRPJVs9XWmRWOA6Cn7YDf575FpwX6UsPCT/Eb0JJme8AC7UE6g==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", @@ -8587,6 +8588,11 @@ "node": ">=8" } }, + "node_modules/filtrex": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/filtrex/-/filtrex-3.1.0.tgz", + "integrity": "sha512-mHzZ2wUISETF1OaEcNRiGz1ljuIV8c/C9td9qyAZ+wTwigkAk5RO9YrCxQKk5H9v7joDRFIBik9U5RTK9eXZ/A==" + }, "node_modules/find-replace": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-3.0.0.tgz", diff --git a/core/package.json b/core/package.json index b6067afae..a405bad55 100644 --- a/core/package.json +++ b/core/package.json @@ -47,7 +47,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.71", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -66,6 +66,7 @@ "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", + "filtrex": "^3.1.0", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", "handlebars": "^4.7.8", diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index b9c409a6d..506f6bf62 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.10 +pluginVersion=1.0.11 # 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/vscode/package-lock.json b/extensions/vscode/package-lock.json index c01a1eb12..bef92c30c 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -106,7 +106,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.71", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -125,6 +125,7 @@ "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", + "filtrex": "^3.1.0", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", "handlebars": "^4.7.8", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 769ed476b..15599a1c0 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.19", + "version": "1.1.20", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 6a1e35424..836360e51 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -634,16 +634,6 @@ const getCommandsMap: ( editDecorationManager.clear(); void sidebar.webviewProtocol?.request("exitEditMode", undefined); }, - // "continue.quickEdit": async (args: QuickEditShowParams) => { - // let linesOfCode = undefined; - // if (args.range) { - // linesOfCode = args.range.end.line - args.range.start.line; - // } - // captureCommandTelemetry("quickEdit", { - // linesOfCode, - // }); - // quickEdit.show(args); - // }, "continue.writeCommentsForCode": async () => { captureCommandTelemetry("writeCommentsForCode"); @@ -708,37 +698,6 @@ const getCommandsMap: ( vscode.commands.executeCommand("continue.continueGUIView.focus"); sidebar.webviewProtocol?.request("addModel", undefined); }, - "continue.sendMainUserInput": (text: string) => { - sidebar.webviewProtocol?.request("userInput", { - input: text, - }); - }, - "continue.selectRange": (startLine: number, endLine: number) => { - if (!vscode.window.activeTextEditor) { - return; - } - vscode.window.activeTextEditor.selection = new vscode.Selection( - startLine, - 0, - endLine, - 0, - ); - }, - "continue.foldAndUnfold": ( - foldSelectionLines: number[], - unfoldSelectionLines: number[], - ) => { - vscode.commands.executeCommand("editor.unfold", { - selectionLines: unfoldSelectionLines, - }); - vscode.commands.executeCommand("editor.fold", { - selectionLines: foldSelectionLines, - }); - }, - "continue.sendToTerminal": (text: string) => { - captureCommandTelemetry("sendToTerminal"); - ide.runCommand(text); - }, "continue.newSession": () => { sidebar.webviewProtocol?.request("newSession", undefined); }, diff --git a/extensions/vscode/tsconfig.json b/extensions/vscode/tsconfig.json index b35899669..a7a58f894 100644 --- a/extensions/vscode/tsconfig.json +++ b/extensions/vscode/tsconfig.json @@ -9,6 +9,7 @@ "strict": true, "esModuleInterop": true, "resolveJsonModule": true, + "skipLibCheck": true, "types": ["mocha"] // This solves conflict between jest and mocha: https://github.com/cypress-io/cypress/issues/7435#issuecomment-631695007 }, "include": ["src/**/*", "../../core/**/*.ts", "../../core/**/*.d.ts"], diff --git a/gui/package-lock.json b/gui/package-lock.json index 0feba0d10..df7ea183b 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -7,7 +7,7 @@ "name": "gui", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.71", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", @@ -111,7 +111,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.71", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -130,6 +130,7 @@ "diff": "^7.0.0", "dotenv": "^16.4.5", "fastest-levenshtein": "^1.0.16", + "filtrex": "^3.1.0", "follow-redirects": "^1.15.5", "google-auth-library": "^9.14.2", "handlebars": "^4.7.8", @@ -554,9 +555,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.67", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.67.tgz", - "integrity": "sha512-RbJXSH2Z9XmaN1h9Dm0Qfru7UeAdCAEWMiEgJ9A2FGHysR9oxbQDqptk1Y61oDSpYeX+lWsxkz/SFIc2PjNnKg==", + "version": "1.0.71", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.71.tgz", + "integrity": "sha512-c7KVaYfldaYHf2EqeqE9Oo1son33iTp6MAY+WRPJVs9XWmRWOA6Cn7YDf575FpwX6UsPCT/Eb0JJme8AC7UE6g==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", diff --git a/gui/package.json b/gui/package.json index 3210a55f5..fa4b439af 100644 --- a/gui/package.json +++ b/gui/package.json @@ -15,7 +15,7 @@ "test:watch": "vitest" }, "dependencies": { - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.71", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", diff --git a/gui/src/App.tsx b/gui/src/App.tsx index deb1e376f..8f7725db9 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -3,7 +3,6 @@ import Layout from "./components/Layout"; import { SubmenuContextProvidersProvider } from "./context/SubmenuContextProviders"; import { VscThemeProvider } from "./context/VscTheme"; import useSetup from "./hooks/useSetup"; -import { AddNewModel, ConfigureProvider } from "./pages/AddNewModel"; import ConfigPage from "./pages/config"; import ConfigErrorPage from "./pages/config-error"; import ErrorPage from "./pages/error"; @@ -34,14 +33,6 @@ const router = createMemoryRouter([ path: "/stats", element: , }, - { - path: "/addModel", - element: , - }, - { - path: "/addModel/provider/:providerName", - element: , - }, { path: ROUTES.CONFIG_ERROR, element: , diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index d2d91f1ea..5b70f2e62 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -6,7 +6,6 @@ import { AuthProvider } from "../context/Auth"; import { LocalStorageProvider } from "../context/LocalStorage"; import { useWebviewListener } from "../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; -import { selectUseHub } from "../redux/selectors"; import { focusEdit, setEditStatus } from "../redux/slices/editModeState"; import { addCodeToEdit, @@ -250,21 +249,6 @@ const Layout = () => { } }, [location]); - const useHub = useAppSelector(selectUseHub); - - // Existing users that have already seen the onboarding card - // should be shown an intro card for hub.continue.dev - // useEffect(() => { - // if (useHub !== true) { - // return; - // } - // const seenHubIntro = getLocalStorage("seenHubIntro"); - // if (!onboardingCard.show && !seenHubIntro) { - // onboardingCard.setActiveTab("ExistingUserHubIntro"); - // } - // setLocalStorage("seenHubIntro", true); - // }, [onboardingCard.show, useHub]); - return ( diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 4cb7b0051..6bb3d1637 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -1,4 +1,4 @@ -import { parseConfigYaml } from "@continuedev/config-yaml"; +import { parseConfigYaml, Rule } from "@continuedev/config-yaml"; import { ArrowsPointingOutIcon, PencilIcon } from "@heroicons/react/24/outline"; import { useContext, useMemo } from "react"; import { useSelector } from "react-redux"; @@ -17,7 +17,7 @@ import { ExploreBlocksButton } from "./ExploreBlocksButton"; interface RuleCardProps { index: number; - rule: string; + rule: Rule; onClick: () => void; title: string; } @@ -31,12 +31,32 @@ const RuleCard: React.FC = ({ index, rule, onClick, title }) => { setDialogMessage(

{title}

-
{rule}
+
+            {/** TODO: Render the rule in a more readable way */}
+            {JSON.stringify(rule)}
+          
, ), ); } + const renderRuleContent = () => { + if (typeof rule === "string") { + return
{rule}
; + } + + if (rule.rule) { + return ( +
+
{rule.rule}
+ {rule.if &&
if: {rule.if}
} +
+ ); + } + + return
{JSON.stringify(rule)}
; + }; + return (
= ({ index, rule, onClick, title }) => { }} className="line-clamp-3 text-gray-400" > - {rule} + {renderRuleContent()}
@@ -137,27 +157,25 @@ export function RulesSection() { ); } - if (!rule.ruleFromYaml?.uses) { - return null; + if ("uses" in rule.ruleFromYaml) { + const ruleSlug = rule.ruleFromYaml?.uses; + + return ( + openUrl(`${ruleSlug}/new-version`)} + title={ruleSlug} + /> + ); } - const ruleSlug = rule.ruleFromYaml?.uses; - - return ( - openUrl(`${ruleSlug}/new-version`)} - title={ruleSlug} - /> - ); + // TODO: Handle rules as object with 'if' + return null; })}
); } -function useTypedDispatch() { - throw new Error("Function not implemented."); -} diff --git a/gui/src/pages/AddNewModel/AddNewModel.tsx b/gui/src/pages/AddNewModel/AddNewModel.tsx deleted file mode 100644 index e2fa104ea..000000000 --- a/gui/src/pages/AddNewModel/AddNewModel.tsx +++ /dev/null @@ -1,238 +0,0 @@ -import { ArrowLeftIcon, Cog6ToothIcon } from "@heroicons/react/24/outline"; -import _ from "lodash"; -import React, { useContext } from "react"; -import { useDispatch } from "react-redux"; -import { Link, useNavigate } from "react-router-dom"; -import styled from "styled-components"; -import { - defaultBorderRadius, - lightGray, - vscBackground, -} from "../../components"; -import ModelCard from "../../components/modelSelection/ModelCard"; -import Toggle from "../../components/modelSelection/Toggle"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useNavigationListener } from "../../hooks/useNavigationListener"; -import { setDefaultModel } from "../../redux/slices/configSlice"; -import { ModelPackage, models } from "./configs/models"; -import { providers } from "./configs/providers"; -import { CustomModelButton } from "./ConfigureProvider"; - -const IntroDiv = styled.div` - padding: 8px 12px; - border-radius: ${defaultBorderRadius}; - border: 1px solid ${lightGray}; - margin-top: 1rem; - margin-bottom: 1rem; -`; - -const GridDiv = styled.div` - display: grid; - grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); - grid-gap: 1.25rem; - justify-items: center; - align-items: center; -`; - -/** - * Used to display groupings in the Models tab - */ -const modelsByProvider: Record = { - "Open AI": [models.gpt4turbo, models.gpt4o, models.gpt35turbo], - Anthropic: [models.claude3Opus, models.claude3Sonnet, models.claude35Haiku], - Mistral: [ - models.codestral, - models.mistral7b, - models.mistral8x7b, - models.mistral8x22b, - models.mistralSmall, - models.mistralLarge, - ], - Cohere: [models.commandR, models.commandRPlus], - DeepSeek: [ - models.deepseekCoderApi, - models.deepseekChatApi, - models.deepseekReasonerApi, - ], - Gemini: [models.geminiPro, models.gemini15Pro, models.gemini15Flash], - "Open Source": [models.llama3Chat, models.mistralOs, models.deepseek], -}; - -function AddNewModel() { - const navigate = useNavigate(); - const dispatch = useDispatch(); - useNavigationListener(); - const ideMessenger = useContext(IdeMessengerContext); - - const [providersSelected, setProvidersSelected] = React.useState(true); - - return ( -
-
- navigate("/")} - className="ml-4 inline-block cursor-pointer" - /> -

Add a new model

-
-
-
- - To add a new model you can either: -
    -
  • - Start by selecting and configuring a provider, then choosing your - model -
  • -
  • Select a specific model directly
  • -
- - Visit our setup overview docs - {" "} - to learn more. -
- -
- { - setProvidersSelected((prev) => !prev); - }} - > -
- - {providersSelected ? ( - <> -
-

Providers

-

- Select a provider below, or configure your own in{" "} - config.json -

-
- - - {Object.entries(providers).map(([providerName, modelInfo], i) => - modelInfo ? ( - { - console.log(`/addModel/provider/${providerName}`); - navigate(`/addModel/provider/${providerName}`); - }} - /> - ) : null, - )} - - - ) : ( - <> -
-

Models

-

- Select a model from the most popular options below, or configure - your own in config.json -

-
- - {Object.entries(modelsByProvider).map( - ([providerTitle, modelConfigsByProviderTitle]) => ( -
-
-

{providerTitle}

-
-
- - - {modelConfigsByProviderTitle.map((config) => ( - { - if (!selectedProvider) { - return; - } - const model = { - ...config.params, - ..._.merge( - {}, - ...(config.dimensions?.map((dimension, i) => { - if (!dimensionChoices?.[i]) return {}; - return { - ...dimension.options[dimensionChoices[i]], - }; - }) || []), - ), - provider: providers[selectedProvider]?.provider, - }; - ideMessenger.post("config/addModel", { model }); - dispatch( - setDefaultModel({ - title: model.title, - force: true, - }), - ); - navigate("/"); - }} - /> - ))} - -
- ), - )} - - )} - - { - ideMessenger.post("config/openProfile", { - profileId: undefined, - }); - }} - > -

- - Open Assistant configuration -

-
-
-
- ); -} - -export default AddNewModel; diff --git a/gui/src/pages/AddNewModel/ConfigureProvider.tsx b/gui/src/pages/AddNewModel/ConfigureProvider.tsx deleted file mode 100644 index 33a3366d6..000000000 --- a/gui/src/pages/AddNewModel/ConfigureProvider.tsx +++ /dev/null @@ -1,245 +0,0 @@ -import { ArrowLeftIcon } from "@heroicons/react/24/outline"; -import _ from "lodash"; -import { useCallback, useContext, useEffect, useState } from "react"; -import { FormProvider, useForm } from "react-hook-form"; -import { useDispatch } from "react-redux"; -import { useNavigate, useParams } from "react-router-dom"; -import styled from "styled-components"; -import { - Input, - defaultBorderRadius, - lightGray, - vscBackground, -} from "../../components"; -import StyledMarkdownPreview from "../../components/markdown/StyledMarkdownPreview"; -import ModelCard from "../../components/modelSelection/ModelCard"; -import { ModelProviderTag } from "../../components/modelSelection/ModelProviderTag"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useNavigationListener } from "../../hooks/useNavigationListener"; -import { updatedObj } from "../../util"; -import type { ProviderInfo } from "./configs/providers"; -import { providers } from "./configs/providers"; -import { setDefaultModel } from "../../redux/slices/configSlice"; - -const GridDiv = styled.div` - display: grid; - grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); - grid-gap: 2rem; - padding: 1rem; - justify-items: center; - align-items: center; -`; - -export const CustomModelButton = styled.div<{ disabled: boolean }>` - border: 1px solid ${lightGray}; - border-radius: ${defaultBorderRadius}; - padding: 4px 8px; - display: flex; - justify-content: center; - align-items: center; - transition: all 0.5s; - - ${(props) => - props.disabled - ? ` - opacity: 0.5; - ` - : ` - &:hover { - border: 1px solid #be1b55; - background-color: #be1b5522; - cursor: pointer; - } - `} -`; - -function ConfigureProvider() { - useNavigationListener(); - const formMethods = useForm(); - const { providerName } = useParams(); - const ideMessenger = useContext(IdeMessengerContext); - const dispatch = useDispatch(); - const navigate = useNavigate(); - const [modelInfo, setModelInfo] = useState( - undefined, - ); - - useEffect(() => { - if (providerName) { - setModelInfo(providers[providerName]); - } - }, [providerName]); - - const disableModelCards = useCallback(() => { - return ( - modelInfo?.collectInputFor?.some((d) => { - if (!d.required) return false; - const val = formMethods.watch(d.key); - return ( - typeof val === "undefined" || (typeof val === "string" && val === "") - ); - }) || false - ); - }, [modelInfo, formMethods]); - - return ( - -
-
- navigate("/addModel")} - className="ml-4 inline-block cursor-pointer" - /> -

- Configure provider -

-
- -
-
- {window.vscMediaUrl && modelInfo?.icon && ( - - )} -

{modelInfo?.title}

-
- - {modelInfo?.tags?.map((tag, i) => ( - - ))} - - -
- - {(modelInfo?.collectInputFor?.filter((d) => d.required).length || 0) > - 0 && ( - <> -

Enter required parameters

- - {modelInfo?.collectInputFor - ?.filter((d) => d.required) - .map((d, idx) => ( -
- - -
- ))} - - )} - - {(modelInfo?.collectInputFor?.filter((d) => !d.required).length || - 0) > 0 && ( -
- - Advanced (optional) - - - {modelInfo?.collectInputFor?.map((d, idx) => { - if (d.required) return null; - return ( -
- - -
- ); - })} -
- )} - -

Select a model preset

-
- - {modelInfo?.packages.map((pkg, idx) => { - return ( - { - if (disableModelCards()) return; - let formParams: any = {}; - for (const d of modelInfo.collectInputFor || []) { - const val = formMethods.watch(d.key); - if (val === "" || val === undefined || val === null) { - continue; - } - formParams = updatedObj(formParams, { - [d.key]: d.inputType === "text" ? val : parseFloat(val), - }); - } - - const model = { - ...pkg.params, - ...modelInfo.params, - ..._.merge( - {}, - ...(pkg.dimensions?.map((dimension, i) => { - if (!dimensionChoices?.[i]) return {}; - return { - ...dimension.options[dimensionChoices[i]], - }; - }) || []), - ), - ...formParams, - provider: modelInfo.provider, - }; - ideMessenger.post("config/addModel", { model }); - dispatch( - setDefaultModel({ title: model.title, force: true }), - ); - navigate("/"); - }} - /> - ); - })} - -
-
- ); -} - -export default ConfigureProvider; diff --git a/gui/src/pages/AddNewModel/index.ts b/gui/src/pages/AddNewModel/index.ts deleted file mode 100644 index fa5775f14..000000000 --- a/gui/src/pages/AddNewModel/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { default as AddNewModel } from "./AddNewModel"; -export { default as ConfigureProvider } from "./ConfigureProvider"; diff --git a/gui/src/util/localStorage.ts b/gui/src/util/localStorage.ts index 28d63b847..918618723 100644 --- a/gui/src/util/localStorage.ts +++ b/gui/src/util/localStorage.ts @@ -15,8 +15,6 @@ type LocalStorageTypes = { showTutorialCard: boolean; shownProfilesIntroduction: boolean; disableIndexing: boolean; - /** Indicates whether the user has seen any kind of onboarding card since hub.continue.dev */ - seenHubIntro: boolean; }; export enum LocalStorageKey { diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index d7d96c4f0..703632362 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.67", + "version": "1.0.71", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/config-yaml/src/README.md b/packages/config-yaml/src/README.md index 4ef80cb49..c68cd8fdc 100644 --- a/packages/config-yaml/src/README.md +++ b/packages/config-yaml/src/README.md @@ -15,3 +15,14 @@ This happens on the server, unless using local mode. ## Client rendering The unrolled config.yaml is then rendered on the client. This is done by replacing all user secret template variables with their values and replacing all other secrets with secret locations. + +## Publishing + +Make sure you are logged into the npm registry with `npm login`. + +Then, bump the version in `package.json` and then run: + +```bash +npm run build +npm publish --access public +``` diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index f376fbc84..92a0b0157 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -17,6 +17,7 @@ import { blockSchema, ConfigYaml, configYamlSchema, + Rule, } from "../schemas/index.js"; import { useProxyForUnrenderedSecrets } from "./clientRender.js"; @@ -62,7 +63,7 @@ export function parseBlock(configYaml: string): Block { } } -const TEMPLATE_VAR_REGEX = /\${{[\s]*([^}\s]+)[\s]*}}/g; +export const TEMPLATE_VAR_REGEX = /\${{[\s]*([^}\s]+)[\s]*}}/g; export function getTemplateVariables(templatedYaml: string): string[] { const variables = new Set(); @@ -313,13 +314,13 @@ export async function unrollBlocks( } } - // Rules are a bit different because they're just strings, so handle separately + // Rules are a bit different because they can be strings, so hanlde separately if (assistant.rules) { - const rules: string[] = []; + const rules: Rule[] = []; for (const rule of assistant.rules) { - if (typeof rule === "string") { + if (typeof rule === "string" || !("uses" in rule)) { rules.push(rule); - } else { + } else if ("uses" in rule) { const blockConfigYaml = await resolveBlock( decodeFullSlug(rule.uses), rule.with, diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 1ca03b0b6..ae12c99a7 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -28,6 +28,16 @@ const docSchema = z.object({ faviconUrl: z.string().optional(), }); +const ruleObjectSchema = z.object({ + name: z.string(), + rule: z.string(), + if: z.string().optional(), +}); + +const ruleSchema = z.union([z.string(), ruleObjectSchema]); + +export type Rule = z.infer; + export const blockItemWrapperSchema = (schema: T) => z.object({ uses: z.string(), @@ -63,7 +73,7 @@ export const configYamlSchema = baseConfigYamlSchema.extend({ rules: z .array( z.union([ - z.string(), + ruleSchema, z.object({ uses: z.string(), with: z.record(z.string()).optional(), @@ -82,7 +92,7 @@ export const assistantUnrolledSchema = baseConfigYamlSchema.extend({ context: z.array(contextSchema).optional(), data: z.array(dataSchema).optional(), mcpServers: z.array(mcpServerSchema).optional(), - rules: z.array(z.string()).optional(), + rules: z.array(ruleSchema).optional(), prompts: z.array(promptSchema).optional(), docs: z.array(docSchema).optional(), }); @@ -95,7 +105,9 @@ export const blockSchema = baseConfigYamlSchema.and( z.object({ context: z.array(contextSchema).length(1) }), z.object({ data: z.array(dataSchema).length(1) }), z.object({ mcpServers: z.array(mcpServerSchema).length(1) }), - z.object({ rules: z.array(z.string()).length(1) }), + z.object({ + rules: z.array(ruleSchema).length(1), + }), z.object({ prompts: z.array(promptSchema).length(1) }), z.object({ docs: z.array(docSchema).length(1) }), ]), diff --git a/packages/fetch/package.json b/packages/fetch/package.json index 6a7097284..e0a924706 100644 --- a/packages/fetch/package.json +++ b/packages/fetch/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/fetch", - "version": "1.0.4", + "version": "1.0.5", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/fetch/src/fetch.ts b/packages/fetch/src/fetch.ts index 01fc631db..d4e8145d0 100644 --- a/packages/fetch/src/fetch.ts +++ b/packages/fetch/src/fetch.ts @@ -15,9 +15,9 @@ export function fetchwithRequestOptions( init?: RequestInit, requestOptions?: RequestOptions, ): Promise { - let url = url_; - if (typeof url === "string") { - url = new URL(url); + const url = typeof url_ === "string" ? new URL(url_) : url_; + if (url.host === "localhost") { + url.host = "127.0.0.1"; } const TIMEOUT = 7200; // 7200 seconds = 2 hours diff --git a/packages/fetch/src/stream.ts b/packages/fetch/src/stream.ts index d0e8e4633..7f33e377d 100644 --- a/packages/fetch/src/stream.ts +++ b/packages/fetch/src/stream.ts @@ -2,6 +2,7 @@ export async function* toAsyncIterable( nodeReadable: NodeJS.ReadableStream, ): AsyncGenerator { for await (const chunk of nodeReadable) { + // @ts-expect-error yield chunk as Uint8Array; } }