Merge branch 'main' into version-when-packaging

This commit is contained in:
uinstinct 2025-04-04 13:03:25 +05:30
commit bddcafd95a
35 changed files with 642 additions and 805 deletions

View file

@ -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",

View file

@ -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 =

View file

@ -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);

View file

@ -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<void>,
platformConfigMetadata: PlatformConfigMetadata | undefined,
systemMessage: string | undefined,
): Promise<BaseLLM | undefined> {
async function modelConfigToBaseLLM({
model,
uniqueId,
ideSettings,
writeLog,
platformConfigMetadata,
config,
}: {
model: ModelConfig;
uniqueId: string;
ideSettings: IdeSettings;
writeLog: (log: string) => Promise<void>;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM | undefined> {
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<void>,
platformConfigMetadata: PlatformConfigMetadata | undefined,
systemMessage: string | undefined,
): Promise<BaseLLM[]> {
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<void>;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
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<void>,
platformConfigMetadata: PlatformConfigMetadata | undefined,
systemMessage: string | undefined,
): Promise<BaseLLM[]> {
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<void>;
platformConfigMetadata: PlatformConfigMetadata | undefined;
config: ContinueConfig;
}): Promise<BaseLLM[]> {
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];

7
core/index.d.ts vendored
View file

@ -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<void>;
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<ModelRole, ILLM[]>;
selectedModelByRole: Record<ModelRole, ILLM | null>;
data?: DataDestination[];
@ -1335,7 +1336,7 @@ export interface BrowserSerializedContinueConfig {
docs?: SiteIndexingConfig[];
tools: Tool[];
mcpServerStatuses: MCPServerStatus[];
rules?: string[];
rules?: Rule[];
usePlatform: boolean;
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
modelsByRole: Record<ModelRole, ModelDescription[]>;

View file

@ -1,3 +1,4 @@
// @ts-nocheck
// Generated by continue
import { ChatMessage, MessagePart } from "../index.js";
import {

View file

@ -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) {

View file

@ -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 });
}

View file

@ -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<ToolUseState> | null = null;
private _promptCachingMetrics: PromptCachingMetrics = {
cacheReadInputTokens: 0,
cacheWriteInputTokens: 0
cacheWriteInputTokens: 0,
};
public requestOptions: { region?: string; credentials?: any; headers?: Record<string, string> };
public requestOptions: {
region?: string;
credentials?: any;
headers?: Record<string, string>;
};
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",
);
}
}
}

View file

@ -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);
});
});

View file

@ -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;
};

View file

@ -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;
}

14
core/package-lock.json generated
View file

@ -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",

View file

@ -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",

View file

@ -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

View file

@ -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",

View file

@ -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"

View file

@ -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);
},

View file

@ -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"],

11
gui/package-lock.json generated
View file

@ -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",

View file

@ -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",

View file

@ -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: <Stats />,
},
{
path: "/addModel",
element: <AddNewModel />,
},
{
path: "/addModel/provider/:providerName",
element: <ConfigureProvider />,
},
{
path: ROUTES.CONFIG_ERROR,
element: <ConfigErrorPage />,

View file

@ -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 (
<LocalStorageProvider>
<AuthProvider>

View file

@ -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<RuleCardProps> = ({ index, rule, onClick, title }) => {
setDialogMessage(
<div className="p-4 text-center">
<h3>{title}</h3>
<pre className="max-w-full overflow-x-scroll">{rule}</pre>
<pre className="max-w-full overflow-x-scroll">
{/** TODO: Render the rule in a more readable way */}
{JSON.stringify(rule)}
</pre>
</div>,
),
);
}
const renderRuleContent = () => {
if (typeof rule === "string") {
return <div>{rule}</div>;
}
if (rule.rule) {
return (
<div>
<div>{rule.rule}</div>
{rule.if && <div className="text-gray-500">if: {rule.if}</div>}
</div>
);
}
return <div>{JSON.stringify(rule)}</div>;
};
return (
<div
style={{
@ -62,7 +82,7 @@ const RuleCard: React.FC<RuleCardProps> = ({ index, rule, onClick, title }) => {
}}
className="line-clamp-3 text-gray-400"
>
{rule}
{renderRuleContent()}
</div>
</div>
<div className="flex items-center gap-1">
@ -137,27 +157,25 @@ export function RulesSection() {
);
}
if (!rule.ruleFromYaml?.uses) {
return null;
if ("uses" in rule.ruleFromYaml) {
const ruleSlug = rule.ruleFromYaml?.uses;
return (
<RuleCard
key={index}
index={index}
rule={rule.unrolledRule}
onClick={() => openUrl(`${ruleSlug}/new-version`)}
title={ruleSlug}
/>
);
}
const ruleSlug = rule.ruleFromYaml?.uses;
return (
<RuleCard
key={index}
index={index}
rule={rule.unrolledRule}
onClick={() => openUrl(`${ruleSlug}/new-version`)}
title={ruleSlug}
/>
);
// TODO: Handle rules as object with 'if'
return null;
})}
</div>
<ExploreBlocksButton blockType="rules" />
</div>
);
}
function useTypedDispatch() {
throw new Error("Function not implemented.");
}

View file

@ -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<string, ModelPackage[]> = {
"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 (
<div className="mb-6 overflow-y-scroll">
<div
className="sticky top-0 m-0 flex items-center p-0"
style={{
borderBottom: `0.5px solid ${lightGray}`,
backgroundColor: vscBackground,
zIndex: 2,
}}
>
<ArrowLeftIcon
width="1.2em"
height="1.2em"
onClick={() => navigate("/")}
className="ml-4 inline-block cursor-pointer"
/>
<h3 className="m-2 inline-block text-lg font-bold">Add a new model</h3>
</div>
<br />
<div className="px-6">
<IntroDiv>
To add a new model you can either:
<ul>
<li>
Start by selecting and configuring a provider, then choosing your
model
</li>
<li>Select a specific model directly</li>
</ul>
<Link
target="_blank"
to="https://docs.continue.dev/model-setup/overview"
>
Visit our setup overview docs
</Link>{" "}
to learn more.
</IntroDiv>
<div className="col-span-full py-4">
<Toggle
selected={providersSelected}
optionOne={"Start with a provider"}
optionTwo={"Select a specific model"}
onClick={() => {
setProvidersSelected((prev) => !prev);
}}
></Toggle>
</div>
{providersSelected ? (
<>
<div className="col-span-full mb-8 text-center leading-relaxed">
<h2 className="mb-0">Providers</h2>
<p className="mt-2">
Select a provider below, or configure your own in{" "}
<code>config.json</code>
</p>
</div>
<GridDiv>
{Object.entries(providers).map(([providerName, modelInfo], i) =>
modelInfo ? (
<ModelCard
key={`${providerName}-${i}`}
title={modelInfo.title}
description={modelInfo.description}
tags={modelInfo.tags}
icon={modelInfo.icon}
refUrl={`https://docs.continue.dev/reference/Model%20Providers/${
modelInfo.refPage || modelInfo.provider.toLowerCase()
}`}
onClick={(e) => {
console.log(`/addModel/provider/${providerName}`);
navigate(`/addModel/provider/${providerName}`);
}}
/>
) : null,
)}
</GridDiv>
</>
) : (
<>
<div className="col-span-full text-center leading-relaxed">
<h2 className="mb-0">Models</h2>
<p className="mt-2">
Select a model from the most popular options below, or configure
your own in <code>config.json</code>
</p>
</div>
{Object.entries(modelsByProvider).map(
([providerTitle, modelConfigsByProviderTitle]) => (
<div className="mb-6 flex flex-col">
<div className="mb-4 w-full items-center">
<h3 className="">{providerTitle}</h3>
<hr
style={{
height: "0px",
width: "100%",
color: lightGray,
border: `1px solid ${lightGray}`,
borderRadius: "2px",
}}
/>
</div>
<GridDiv>
{modelConfigsByProviderTitle.map((config) => (
<ModelCard
title={config.title}
description={config.description}
tags={config.tags}
icon={config.icon}
dimensions={config.dimensions}
providerOptions={config.providerOptions}
onClick={(e, dimensionChoices, selectedProvider) => {
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("/");
}}
/>
))}
</GridDiv>
</div>
),
)}
</>
)}
<CustomModelButton
className="mt-12"
disabled={false}
onClick={(e) => {
ideMessenger.post("config/openProfile", {
profileId: undefined,
});
}}
>
<h3 className="my-2 text-center">
<Cog6ToothIcon className="inline-block h-5 w-5 px-4 align-middle" />
Open Assistant configuration
</h3>
</CustomModelButton>
</div>
</div>
);
}
export default AddNewModel;

View file

@ -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<ProviderInfo | undefined>(
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 (
<FormProvider {...formMethods}>
<div className="overflow-y-scroll">
<div
className="sticky top-0 m-0 flex items-center p-0"
style={{
borderBottom: `0.5px solid ${lightGray}`,
backgroundColor: vscBackground,
zIndex: 2,
}}
>
<ArrowLeftIcon
width="1.2em"
height="1.2em"
onClick={() => navigate("/addModel")}
className="ml-4 inline-block cursor-pointer"
/>
<h3 className="m-2 inline-block text-lg font-bold">
Configure provider
</h3>
</div>
<div className="px-2">
<div style={{ display: "flex", alignItems: "center" }}>
{window.vscMediaUrl && modelInfo?.icon && (
<img
src={`${window.vscMediaUrl}/logos/${modelInfo?.icon}`}
height="24px"
style={{ marginRight: "10px" }}
/>
)}
<h2>{modelInfo?.title}</h2>
</div>
{modelInfo?.tags?.map((tag, i) => (
<ModelProviderTag key={i} tag={tag} />
))}
<StyledMarkdownPreview
className="mt-2"
source={modelInfo?.longDescription || modelInfo?.description}
/>
<br />
{(modelInfo?.collectInputFor?.filter((d) => d.required).length || 0) >
0 && (
<>
<h3 className="mb-2">Enter required parameters</h3>
{modelInfo?.collectInputFor
?.filter((d) => d.required)
.map((d, idx) => (
<div key={idx} className="mb-2">
<label htmlFor={d.key}>{d.label}</label>
<Input
type={d.inputType}
id={d.key}
className="m-2 rounded-md border-2 border-gray-200 p-2"
placeholder={d.placeholder ?? d.label}
defaultValue={d.defaultValue}
min={d.min}
max={d.max}
step={d.step}
{...formMethods.register(d.key, {
required: true,
})}
/>
</div>
))}
</>
)}
{(modelInfo?.collectInputFor?.filter((d) => !d.required).length ||
0) > 0 && (
<details>
<summary className="mb-2 cursor-pointer">
<b>Advanced (optional)</b>
</summary>
{modelInfo?.collectInputFor?.map((d, idx) => {
if (d.required) return null;
return (
<div key={idx}>
<label htmlFor={d.key}>{d.label}</label>
<Input
type={d.inputType}
id={d.key}
className="m-2 rounded-md border-2 border-gray-200 p-2"
placeholder={d.placeholder ?? d.label}
defaultValue={d.defaultValue}
min={d.min}
max={d.max}
step={d.step}
{...formMethods.register(d.key, {
required: false,
})}
/>
</div>
);
})}
</details>
)}
<h3 className="mb-2">Select a model preset</h3>
</div>
<GridDiv>
{modelInfo?.packages.map((pkg, idx) => {
return (
<ModelCard
key={idx}
disabled={disableModelCards()}
title={pkg.title}
description={pkg.description}
tags={pkg.tags}
refUrl={pkg.refUrl}
icon={pkg.icon || modelInfo.icon}
dimensions={pkg.dimensions}
onClick={(e, dimensionChoices) => {
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("/");
}}
/>
);
})}
</GridDiv>
</div>
</FormProvider>
);
}
export default ConfigureProvider;

View file

@ -1,2 +0,0 @@
export { default as AddNewModel } from "./AddNewModel";
export { default as ConfigureProvider } from "./ConfigureProvider";

View file

@ -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 {

View file

@ -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",

View file

@ -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
```

View file

@ -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<string>();
@ -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,

View file

@ -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<typeof ruleSchema>;
export const blockItemWrapperSchema = <T extends z.AnyZodObject>(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) }),
]),

View file

@ -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",

View file

@ -15,9 +15,9 @@ export function fetchwithRequestOptions(
init?: RequestInit,
requestOptions?: RequestOptions,
): Promise<Response> {
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

View file

@ -2,6 +2,7 @@ export async function* toAsyncIterable(
nodeReadable: NodeJS.ReadableStream,
): AsyncGenerator<Uint8Array> {
for await (const chunk of nodeReadable) {
// @ts-expect-error
yield chunk as Uint8Array;
}
}