Merge branch 'nate/alwaysUseProxy' into pe/assistant-unroll-bugfix

This commit is contained in:
Nate 2025-04-04 12:49:49 -07:00
commit cf4eb29f50
80 changed files with 2078 additions and 1691 deletions

View file

@ -44,11 +44,11 @@
"version": "1.1.0",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
"@aws-sdk/client-sagemaker-runtime": "^3.758.0",
"@aws-sdk/credential-providers": "^3.758.0",
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
"@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

@ -235,15 +235,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];

View file

@ -3,6 +3,7 @@ import Cohere from "../llm/llms/Cohere";
import FreeTrial from "../llm/llms/FreeTrial";
import HuggingFaceTEI from "../llm/llms/HuggingFaceTEI";
import { LLMReranker } from "../llm/llms/llm";
import SiliconFlow from "../llm/llms/SiliconFlow";
import ContinueProxy from "../llm/llms/stubs/ContinueProxy";
import Voyage from "../llm/llms/Voyage";
import WatsonX from "../llm/llms/WatsonX";
@ -16,4 +17,5 @@ export const AllRerankers: { [key: string]: any } = {
"free-trial": FreeTrial,
"huggingface-tei": HuggingFaceTEI,
"continue-proxy": ContinueProxy,
siliconflow: SiliconFlow,
};

View file

@ -35,7 +35,7 @@ class FolderContextProvider extends BaseContextProvider {
const folders = await walkDirs(
args.ide,
{
onlyDirs: true,
include: "dirs",
source: "load submenu items - folder",
},
workspaceDirs,

View file

@ -54,7 +54,7 @@ class RepoMapContextProvider extends BaseContextProvider {
const folders = await walkDirs(
args.ide,
{
onlyDirs: true,
include: "dirs",
source: "load submenu items - repo map",
},
workspaceDirs,

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

@ -97,7 +97,7 @@ describe("walkDir functions", () => {
);
});
it("should handle onlyDirs option", async () => {
it("should handle include option", async () => {
addToTestDir([
"src/",
["src/file1.ts", "content1"],
@ -109,7 +109,7 @@ describe("walkDir functions", () => {
(await testIde.getWorkspaceDirs())[0],
testIde,
{
onlyDirs: true,
include: "dirs",
},
);

View file

@ -10,10 +10,11 @@ import {
} from "./ignore";
export interface WalkerOptions {
onlyDirs?: boolean;
include?: "dirs" | "files" | "both";
returnRelativeUrisPaths?: boolean;
source?: string;
overrideDefaultIgnores?: Ignore;
recursive?: boolean;
}
type Entry = [string, FileType];
@ -195,7 +196,7 @@ class DFSWalker {
if (this.entryIsDirectory(entry)) {
relPath = `${relPath}/`;
} else {
if (this.options.onlyDirs) {
if (this.options.include === "dirs") {
continue;
}
}
@ -221,19 +222,22 @@ class DFSWalker {
}
if (this.entryIsDirectory(entry)) {
stack.push({
walkableEntry,
ignoreContexts,
});
if (this.options.onlyDirs) {
// when onlyDirs is enabled the walker will only return directory names
if (this.options.recursive) {
stack.push({
walkableEntry,
ignoreContexts,
});
}
if (this.options.include !== "files") {
// if yielding dirs or both, walker includes relative paths
const trailingSlash = this.options.include === "dirs" ? "" : "/";
if (this.options.returnRelativeUrisPaths) {
yield walkableEntry.relativeUriPath;
yield walkableEntry.relativeUriPath + trailingSlash;
} else {
yield walkableEntry.uri;
yield walkableEntry.uri + trailingSlash;
}
}
} else {
} else if (this.options.include !== "dirs") {
if (this.options.returnRelativeUrisPaths) {
yield walkableEntry.relativeUriPath;
} else {
@ -257,8 +261,9 @@ class DFSWalker {
}
const defaultOptions: WalkerOptions = {
onlyDirs: false,
include: "files",
returnRelativeUrisPaths: false,
recursive: true,
};
export async function* walkDirAsync(

View file

@ -1,5 +1,5 @@
const DEFAULT_MAX_TOKENS = 4096;
const DEFAULT_CONTEXT_LENGTH = 8096;
const DEFAULT_CONTEXT_LENGTH = 8192;
const DEFAULT_TEMPERATURE = 0.5;
const DEFAULT_ARGS = {

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"];
@ -251,16 +259,35 @@ function pruneChatHistory(
}, 0);
// 0. Prune any messages that take up more than 1/3 of the context length
const longestMessages = [...chatHistory];
longestMessages.sort((a, b) => b.content.length - a.content.length);
const zippedMessagesAndTokens: [ChatMessage, number][] = [];
const longerThanOneThird = longestMessages.filter(
(message: ChatMessage) =>
countTokens(message.content, modelName) > contextLength / 3,
// Zipped ChatMessage with its token counts
chatHistory.forEach((message) => {
const zippedItem: [ChatMessage, number] = [
message,
countTokens(message.content, modelName),
];
zippedMessagesAndTokens.push(zippedItem);
});
const zippedLongerThanOneThird = zippedMessagesAndTokens.filter(
([_message, tokens]: [ChatMessage, number]) => tokens > contextLength / 3,
);
const distanceFromThird = longerThanOneThird.map(
(message: ChatMessage) =>
countTokens(message.content, modelName) - contextLength / 3,
zippedLongerThanOneThird.sort(
(
[_messageA, tokensA]: [ChatMessage, number],
[_messageB, tokensB]: [ChatMessage, number],
) => {
return tokensB - tokensA;
},
);
const longerThanOneThird = zippedLongerThanOneThird.map(
([message, _token]: [ChatMessage, number]) => message,
);
const distanceFromThird = zippedLongerThanOneThird.map(
([_message, token]: [ChatMessage, number]) => token - contextLength / 3,
);
for (let i = 0; i < longerThanOneThird.length; i++) {
@ -280,7 +307,7 @@ function pruneChatHistory(
// 1. Replace beyond last 5 messages with summary
let i = 0;
while (totalTokens > contextLength && i < chatHistory.length - 5) {
const message = chatHistory[0];
const message = chatHistory[i];
totalTokens -= countTokens(message.content, modelName);
totalTokens += countTokens(summarize(message), modelName);
message.content = summarize(message);
@ -288,11 +315,7 @@ function pruneChatHistory(
}
// 2. Remove entire messages until the last 5
while (
chatHistory.length > 5 &&
totalTokens > contextLength &&
chatHistory.length > 0
) {
while (chatHistory.length > 5 && totalTokens > contextLength) {
const message = chatHistory.shift()!;
totalTokens -= countTokens(message.content, modelName);
}
@ -384,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 }))
@ -410,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

@ -2,8 +2,9 @@ import {
BedrockRuntimeClient,
ContentBlock,
ConverseStreamCommand,
ConverseStreamCommandOutput,
InvokeModelCommand,
Message
Message,
} from "@aws-sdk/client-bedrock-runtime";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
@ -11,7 +12,7 @@ import {
ChatMessage,
Chunk,
CompletionOptions,
LLMOptions
LLMOptions,
} from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
@ -31,6 +32,14 @@ interface ToolUseState {
input: string;
}
/**
* Interface for prompt caching metrics
*/
interface PromptCachingMetrics {
cacheReadInputTokens: number;
cacheWriteInputTokens: number;
}
class Bedrock extends BaseLLM {
static providerName = "bedrock";
static defaultOptions: Partial<LLMOptions> = {
@ -41,8 +50,16 @@ class Bedrock extends BaseLLM {
};
private _currentToolResponse: Partial<ToolUseState> | null = null;
private _promptCachingMetrics: PromptCachingMetrics = {
cacheReadInputTokens: 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);
@ -108,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;
let response: ConverseStreamCommandOutput;
try {
response = await client.send(command, { abortSignal: signal });
response = (await client.send(command, {
abortSignal: signal,
})) as ConverseStreamCommandOutput;
} catch (error: unknown) {
console.error(error);
const message = error instanceof Error ? error.message : "Unknown error";
@ -124,51 +146,82 @@ class Bedrock extends BaseLLM {
throw new Error("No stream received from Bedrock API");
}
// Reset cache metrics for new request
this._promptCachingMetrics = {
cacheReadInputTokens: 0,
cacheWriteInputTokens: 0,
};
try {
for await (const chunk of response.stream) {
if (chunk.metadata?.usage) {
console.log(`${JSON.stringify(chunk.metadata.usage)}`);
}
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;
}
@ -177,7 +230,7 @@ class Bedrock extends BaseLLM {
this._currentToolResponse = {
toolUseId: toolUse.toolUseId,
name: toolUse.name,
input: ""
input: "",
};
}
continue;
@ -188,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;
}
@ -207,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",
);
}
}
/**
@ -228,22 +286,43 @@ class Bedrock extends BaseLLM {
): any {
const convertedMessages = this._convertMessages(messages);
const supportsTools = PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
const shouldCacheSystemMessage =
!!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
const enablePromptCaching =
shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation;
// Add header for prompt caching
if (enablePromptCaching) {
this.requestOptions.headers = {
...this.requestOptions.headers,
"x-amzn-bedrock-enablepromptcaching": "true",
};
}
const supportsTools =
PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
return {
modelId: options.model,
messages: convertedMessages,
system: this.systemMessage ? [{ 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,
@ -261,20 +340,29 @@ 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): 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;
// Tool response handling
if (message.role === "tool") {
return {
@ -285,12 +373,12 @@ class Bedrock extends BaseLLM {
toolUseId: message.toolCallId,
content: [
{
text: message.content || ""
}
]
}
}
]
text: message.content || "",
},
],
},
},
],
};
}
@ -303,8 +391,8 @@ class Bedrock extends BaseLLM {
toolUseId: toolCall.id,
name: toolCall.function?.name,
input: JSON.parse(toolCall.function?.arguments || "{}"),
}
}))
},
})),
};
}
@ -312,84 +400,111 @@ 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],
};
}
}
// Standard text message
if (typeof message.content === "string") {
const content: any[] = [{ text: message.content }];
if (addCaching) {
content.push({ cachePoint: { type: "default" } });
}
return {
role: message.role,
content: [{ text: message.content }]
content,
};
}
// Improved multimodal content handling
if (Array.isArray(message.content)) {
const content: any[] = [];
// Process all parts first
message.content.forEach((part) => {
if (part.type === "text") {
content.push({ text: part.text });
} else if (part.type === "imageUrl" && part.imageUrl) {
try {
const [mimeType, base64Data] = part.imageUrl.url.split(",");
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
content.push({
image: {
format,
source: {
bytes: Buffer.from(base64Data, "base64"),
},
},
});
} catch (error) {
console.warn(`Failed to process image: ${error}`);
}
}
});
// Add cache point as a separate block at the end if needed
if (addCaching && content.length > 0) {
content.push({ cachePoint: { type: "default" } });
}
return {
role: message.role,
content: message.content.map(part => {
if (part.type === "text") {
return { text: part.text };
}
if (part.type === "imageUrl" && part.imageUrl) {
try {
const [mimeType, base64Data] = part.imageUrl.url.split(",");
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
return {
image: {
format,
source: {
bytes: Buffer.from(base64Data, "base64")
}
}
};
} catch (error) {
console.warn(`Failed to process image: ${error}`);
return null;
}
}
return null;
}).filter(Boolean)
content,
} as Message;
}
return null;
}
private _convertMessages(messages: ChatMessage[]): any[] {
const filteredmessages = messages.filter(
(m) => m.role !== "system" && !!m.content,
);
const lastTwoUserMsgIndices = filteredmessages
.map((msg, index) => (msg.role === "user" ? index : -1))
.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 = messages
.map((message) => {
try {
return this._convertMessage(message);
return this._convertMessage(message, addCaching);
} catch (error) {
console.error(`Failed to convert message: ${error}`);
return null;
}
})
.filter(Boolean);
return converted;
return converted;
}
private async _getCredentials() {
@ -453,7 +568,6 @@ class Bedrock extends BaseLLM {
return modelConfig.extractEmbeddings(responseBody);
}
private _getModelConfig() {
const modelConfigs: { [key: string]: ModelConfig } = {
cohere: {
@ -491,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
@ -530,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",
);
}
}
}

133
core/llm/llms/Docker.ts Normal file
View file

@ -0,0 +1,133 @@
import { spawn } from "child_process";
import { LLMOptions, ModelInstaller } from "../../index.js";
import OpenAI from "./OpenAI.js";
/**
* Docker Model Runner provider
*
* Integrates with Docker Desktop's Model Runner feature (currently in beta)
* that allows running local AI models through Docker.
*
* Docker Model Runner provides an OpenAI-compatible API endpoint, making it
* easy to integrate with existing OpenAI-compatible code.
*
* More information at: https://docs.docker.com/desktop/features/model-runner/
*/
class Docker extends OpenAI implements ModelInstaller {
static providerName = "docker";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://model-runner.docker.internal/v1/",
model: "gemma3-4B-F4", // Default model
};
private modelMap: Record<string, string> = {
// Map of "continue model name" to Docker model name
// Models can be pulled using: docker model pull <model_name>
"llama3.3-70b": "ai/llama3.3:70B-Q4_K_M",
"smollm2-360M-F4": "ai/smollm2:360M-Q4_K_M",
"smollm2-360M-F16": "ai/ai/smollm2:360M-F16",
"qwen2.5-7B-F16": "ai/qwen2.5:7B-F16",
"qwen2.5-7B-F4": "ai/qwen2.5:7B-Q4_K_M",
"phi4-14B-F16": "ai/phi4:14B-F16",
"phi4-14B-F4": "ai/phi4:14B-Q4_K_M",
"mistral-7B-F16": "ai/mistral:7B-F16",
"mistral-7B-F4": "ai/mistral:7B-Q4_K_M",
"mistral-nemo-12B": "ai/mistral-nemo:12B-Q4_K_M",
"gemma3-4B-F16": "ai/gemma3:4B-F16",
"gemma3-4B-F4": "ai/gemma3:4B-Q4_K_M",
"llama3.2-3B-F16": "ai/llama3.2:3B-F16",
"llama3.2-3B-F4": "ai/llama3.2:3B-Q4_K_M",
"llama3.2-1B-F16": "ai/llama3.2:1B-F16",
"llama3.2-1B-F8": "ai/llama3.2:1B-Q8_0",
"qwq-32B-F16": "ai/qwq:32B-F16",
"qwq-32B-F4": "ai/qwq:32B-Q4_K_M",
"deepseek-r1-distill-llama-70B-F4": "ai/deepseek-r1-distill-llama:70B-Q4_K_M",
"deepseek-r1-distill-llama-8B-F16": "ai/deepseek-r1-distill-llama:8B-F16",
"deepseek-r1-distill-llama-8B-Q4": "ai/deepseek-r1-distill-llama:8B-Q4_K_M"
};
constructor(options: LLMOptions) {
super(options);
// Handle model name mapping
if (this.model && this.modelMap[this.model]) {
this.model = this.modelMap[this.model];
}
}
private async executeDockerCommand(
args: string[],
signal?: AbortSignal
): Promise<{ stdout: string; stderr: string }> {
return new Promise((resolve, reject) => {
const proc = spawn('docker', args, { shell: true });
let stdout = '';
let stderr = '';
proc.stdout.on('data', (data) => {
stdout += data.toString();
});
proc.stderr.on('data', (data) => {
stderr += data.toString();
});
proc.on('close', (code) => {
if (code === 0) {
resolve({ stdout, stderr });
} else {
reject(new Error(`Docker command failed with code ${code}: ${stderr}`));
}
});
if (signal) {
signal.addEventListener('abort', () => {
proc.kill();
reject(new Error('Docker command was aborted'));
});
}
});
}
async listModels(): Promise<string[]> {
try {
// Execute docker model ls and parse the output
const { stdout } = await this.executeDockerCommand(['model', 'ls', '--format', '{{.Repository}}/{{.Tag}}']);
return stdout.split('\n')
.map(line => line.trim())
.filter(Boolean);
} catch (error) {
console.error("Failed to list Docker models:", error);
return Object.values(this.modelMap);
}
}
async installModel(
modelName: string,
signal: AbortSignal,
progressReporter?: (task: string, increment: number, total: number) => void
): Promise<any> {
const targetModel = this.modelMap[modelName] || modelName;
try {
// Report starting the installation
progressReporter?.(`Installing Docker model ${targetModel}`, 0, 100);
// Pull the model
const { stdout, stderr } = await this.executeDockerCommand(['model', 'pull', targetModel], signal);
// Report completion
progressReporter?.(`Docker model ${targetModel} installed successfully`, 100, 100);
return { success: true, stdout, stderr };
} catch (error) {
console.error(`Failed to install Docker model ${targetModel}:`, error);
// Fix: Type check the error before accessing message property
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to install Docker model ${targetModel}: ${errorMessage}`);
}
}
}
export default Docker;

View file

@ -0,0 +1,70 @@
import { CompletionOptions, LLMOptions } from "../../index.js";
import { streamSse } from "../stream.js";
import OpenAI from "./OpenAI.js";
/**
* Inception Labs provider
*
* Integrates with Inception Labs' OpenAI-compatible API endpoints.
* Provides access to Mercury models for autocomplete and other tasks.
*
* Different models use different API endpoints:
* - mercury-editor-mini-experimental: zaragoza.api.inceptionlabs.ai
* - mercury-editor-small-experimental: copenhagen.api.inceptionlabs.ai
*
* More information at: https://docs.inceptionlabs.ai/
*/
class Inception extends OpenAI {
static providerName = "inception";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://copenhagen.api.inceptionlabs.ai/v1/",
model: "mercury-editor-small-experimental",
completionOptions: {
temperature: 0.0,
maxTokens: 150,
presencePenalty: 1.5,
stop: ["\n\n", "\n \n", "<|endoftext|>"],
model: "mercury-editor-small-experimental", // Added model to fix TypeScript error
},
};
supportsFim(): boolean {
return true;
}
async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const endpoint = new URL("completions", this.apiBase);
const resp = await this.fetch(endpoint, {
method: "POST",
body: JSON.stringify({
model: options.model,
prompt: prefix,
suffix,
max_tokens: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
stop: options.stop,
stream: true,
}),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
signal,
});
for await (const chunk of streamSse(resp)) {
yield chunk.choices[0].text;
}
}
}
export default Inception;

View file

@ -1,4 +1,4 @@
import { CompletionOptions, LLMOptions } from "../../index.js";
import { Chunk, CompletionOptions, LLMOptions } from "../../index.js";
import { streamSse } from "../stream.js";
import { osModelsEditPrompt } from "../templates/edit.js";
@ -52,6 +52,41 @@ class SiliconFlow extends OpenAI {
yield chunk.choices[0].text;
}
}
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
if (!query || query.trim() === "") {
console.warn("[SiliconFlow] rerank: query is empty");
return [];
}
if (!chunks || chunks.length === 0) {
console.warn("[SiliconFlow] rerank: chunks is empty");
return [];
}
const endpoint = new URL("rerank", this.apiBase);
const resp = await this.fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify({
model: this.model,
query,
documents: chunks.map((chunk) => chunk.content),
}),
});
if (!resp.ok) {
throw new Error(await resp.text());
}
const data = (await resp.json()) as any;
const results = data.results.sort((a: any, b: any) => a.index - b.index);
return results.map((result: any) => result.relevance_score);
}
}
export default SiliconFlow;

View file

@ -18,6 +18,7 @@ import Cloudflare from "./Cloudflare";
import Cohere from "./Cohere";
import DeepInfra from "./DeepInfra";
import Deepseek from "./Deepseek";
import Docker from "./Docker";
import Fireworks from "./Fireworks";
import Flowise from "./Flowise";
import FreeTrial from "./FreeTrial";
@ -26,6 +27,7 @@ import Gemini from "./Gemini";
import Groq from "./Groq";
import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI";
import HuggingFaceTGI from "./HuggingFaceTGI";
import Inception from "./Inception";
import Kindo from "./Kindo";
import LlamaCpp from "./LlamaCpp";
import Llamafile from "./Llamafile";
@ -87,6 +89,7 @@ export const LLMClasses = [
ContinueProxy,
Cloudflare,
Deepseek,
Docker,
Msty,
Azure,
WatsonX,
@ -104,6 +107,7 @@ export const LLMClasses = [
SiliconFlow,
Scaleway,
Relace,
Inception,
];
export async function llmFromDescription(

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

1106
core/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -43,9 +43,9 @@
"typescript": "^5.6.3"
},
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
"@aws-sdk/client-sagemaker-runtime": "^3.758.0",
"@aws-sdk/credential-providers": "^3.758.0",
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
"@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.75",
"@continuedev/fetch": "^1.0.4",
@ -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,10 +3,14 @@ export enum BuiltInToolNames {
ReadCurrentlyOpenFile = "builtin_read_currently_open_file",
CreateNewFile = "builtin_create_new_file",
RunTerminalCommand = "builtin_run_terminal_command",
ViewSubdirectory = "builtin_view_subdirectory",
ViewRepoMap = "builtin_view_repo_map",
ExactSearch = "builtin_exact_search",
SearchWeb = "builtin_search_web",
ViewDiff = "builtin_view_diff",
LSTool = "builtin_ls",
// excluded from allTools for now
ViewRepoMap = "builtin_view_repo_map",
ViewSubdirectory = "builtin_view_subdirectory",
}
export const BUILT_IN_GROUP_NAME = "Built-In";

View file

@ -5,13 +5,12 @@ import { BuiltInToolNames } from "./builtIn";
import { createNewFileImpl } from "./implementations/createNewFile";
import { exactSearchImpl } from "./implementations/exactSearch";
import { lsToolImpl } from "./implementations/lsTool";
import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile";
import { readFileImpl } from "./implementations/readFile";
import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
import { searchWebImpl } from "./implementations/searchWeb";
import { viewDiffImpl } from "./implementations/viewDiff";
import { viewRepoMapImpl } from "./implementations/viewRepoMap";
import { viewSubdirectoryImpl } from "./implementations/viewSubdirectory";
async function callHttpTool(
url: string,
@ -149,12 +148,14 @@ export async function callTool(
return await searchWebImpl(args, extras);
case BuiltInToolNames.ViewDiff:
return await viewDiffImpl(args, extras);
case BuiltInToolNames.ViewRepoMap:
return await viewRepoMapImpl(args, extras);
case BuiltInToolNames.ViewSubdirectory:
return await viewSubdirectoryImpl(args, extras);
case BuiltInToolNames.LSTool:
return await lsToolImpl(args, extras);
case BuiltInToolNames.ReadCurrentlyOpenFile:
return await readCurrentlyOpenFileImpl(args, extras);
// case BuiltInToolNames.ViewRepoMap:
// return await viewRepoMapImpl(args, extras);
// case BuiltInToolNames.ViewSubdirectory:
// return await viewSubdirectoryImpl(args, extras);
default:
return await callToolFromUri(uri, args, extras);
}

View file

@ -0,0 +1,33 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const lsTool: Tool = {
type: "function",
displayTitle: "LS Tool",
wouldLikeTo: "list files and folders in {{{ dirPath }}}",
isCurrently: "listing files and folders in {{{ dirPath }}}",
hasAlready: "listed files and folders in {{{ dirPath }}}",
readonly: true,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.LSTool,
description: "List files and folders in a given directory",
parameters: {
type: "object",
required: ["dirPath", "recursive"],
properties: {
dirPath: {
type: "string",
description:
"The directory path relative to the root of the project. Always use forward slash paths like '/'. rather than e.g. '.'",
},
recursive: {
type: "boolean",
description:
"If true, lists files and folders recursively. To prevent unexpected large results, use this sparingly",
},
},
},
},
};

View file

@ -0,0 +1,31 @@
import { ToolImpl } from ".";
import { walkDir } from "../../indexing/walkDir";
import { resolveRelativePathInDir } from "../../util/ideUtils";
export const lsToolImpl: ToolImpl = async (args, extras) => {
const uri = await resolveRelativePathInDir(args.dirPath, extras.ide);
if (!uri) {
throw new Error(
`Directory ${args.dirPath} not found. Make sure to use forward-slash paths. Do not use e.g. "."`,
);
}
const entries = await walkDir(uri, extras.ide, {
returnRelativeUrisPaths: true,
include: "both",
recursive: args.recursive ?? false,
});
const content =
entries.length > 0
? entries.join("\n")
: `No files/folders found in ${args.dirPath}`;
return [
{
name: "File/folder list",
description: `Files/folders in ${args.dirPath}`,
content,
},
];
};

View file

@ -1,21 +1,24 @@
import { createNewFileTool } from "./definitions/createNewFile";
import { exactSearchTool } from "./definitions/exactSearch";
import { lsTool } from "./definitions/lsTool";
import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile";
import { readFileTool } from "./definitions/readFile";
import { runTerminalCommandTool } from "./definitions/runTerminalCommand";
import { searchWebTool } from "./definitions/searchWeb";
import { viewDiffTool } from "./definitions/viewDiff";
import { viewRepoMapTool } from "./definitions/viewRepoMap";
import { viewSubdirectoryTool } from "./definitions/viewSubdirectory";
export const allTools = [
readFileTool,
createNewFileTool,
runTerminalCommandTool,
viewSubdirectoryTool,
viewRepoMapTool,
exactSearchTool,
searchWebTool,
viewDiffTool,
readCurrentlyOpenFileTool,
lsTool,
// replacing with ls tool for now
// viewSubdirectoryTool,
// viewRepoMapTool,
];

View file

@ -21,7 +21,7 @@ We recommend configuring **GPT-4o** as your chat model.
- name: GPT-4o
provider: openai
model: gpt-4o
apiKey: <YOUR_HUGGINGFACE_TEI_API_KEY>
apiKey: <YOUR_OPENAI_API_KEY>
```
</TabItem>
<TabItem value="json" label="JSON">
@ -32,7 +32,7 @@ We recommend configuring **GPT-4o** as your chat model.
"title": "GPT-4o",
"provider": "openai",
"model": "gpt-4o",
"apiKey": "<YOUR_HUGGINGFACE_TEI_API_KEY>"
"apiKey": "<YOUR_OPENAI_API_KEY>"
}
]
}
@ -57,7 +57,7 @@ We recommend configuring **text-embedding-3-large** as your embeddings model.
- name: OpenAI Embeddings
provider: openai
model: text-embedding-3-large
apiKey: <YOUR_HUGGINGFACE_TEI_API_KEY>
apiKey: <YOUR_OPENAI_API_KEY>
roles:
- embed
```
@ -68,7 +68,7 @@ We recommend configuring **text-embedding-3-large** as your embeddings model.
"embeddingsProvider": {
"provider": "openai",
"model": "text-embedding-3-large",
"apiKey": "<YOUR_HUGGINGFACE_TEI_API_KEY>"
"apiKey": "<YOUR_OPENAI_API_KEY>"
}
}
```

View file

@ -20,5 +20,5 @@ You can easily access your assistant configuration from the Continue Chat sideba
![configure an assistant](/img/configure-continue.png)
- See [Editing Hub Assistants](../hub/assistants/edit-an-assistant.md) for more details on managing your hug assistant
- See [Editing Hub Assistants](../hub/assistants/edit-an-assistant.md) for more details on managing your hub assistant
- See the [Config Deep Dive](./deep-dives/configuration.md) for more details on configuring local assistants.

View file

@ -227,7 +227,7 @@ More information about usage/params for each context provider can be found [here
```yaml title="config.yaml"
context:
- provider: files
- provider: file
- provider: code
- provider: codebase
params:

View file

@ -9617,9 +9617,10 @@
"license": "ISC"
},
"node_modules/image-size": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/image-size/-/image-size-1.2.0.tgz",
"integrity": "sha512-4S8fwbO6w3GeCVN6OPtA9I5IGKkcDMPcKndtUlpJuCwu7JLjtj7JZpwqLuyY2nrmQT3AWsCJLSKPsc2mPBSl3w==",
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/image-size/-/image-size-1.2.1.tgz",
"integrity": "sha512-rH+46sQJ2dlwfjfhCyNx5thzrv+dtmBIhPHk0zgRUukHzZ/kRueTJXoYYsclBaKcSMBWuGbOFXtioLpzTb5euw==",
"license": "MIT",
"dependencies": {
"queue": "6.0.2"
},

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.9
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

@ -956,7 +956,10 @@
"gemini-2.0-flash",
"gemini-2.0-flash-thinking-exp-01-21",
"gemini-2.0-pro-exp-02-05",
"gemini-2.0-flash-lite-preview-02-05"
"gemini-2.0-flash-lite-preview-02-05",
"gemini-2.0-flash-lite",
"gemini-2.0-flash-exp-image-generation",
"gemini-2.5-pro-exp-03-25"
]
}
}
@ -2886,7 +2889,8 @@
"watsonx",
"llm",
"free-trial",
"huggingface-tei"
"huggingface-tei",
"siliconflow"
]
},
"params": {
@ -3053,6 +3057,40 @@
"required": ["truncation_direction"]
}
}
},
{
"if": {
"properties": {
"name": {
"enum": ["siliconflow"]
}
},
"required": ["name"]
},
"then": {
"properties": {
"params": {
"type": "object",
"properties": {
"model": {
"enum": [
"BAAI/bge-reranker-v2-m3",
"netease-youdao/bce-reranker-base_v1",
"Pro/BAAI/bge-reranker-v2-m3"
],
"default": "BAAI/bge-reranker-v2-m3"
},
"apiBase": {
"type": "string"
},
"apiKey": {
"type": "string"
}
},
"required": ["apiKey"]
}
}
}
}
]
},

View file

@ -102,11 +102,11 @@
"version": "1.1.0",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
"@aws-sdk/client-sagemaker-runtime": "^3.758.0",
"@aws-sdk/credential-providers": "^3.758.0",
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
"@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",
@ -12293,9 +12294,10 @@
}
},
"node_modules/tar-fs": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz",
"integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==",
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz",
"integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==",
"license": "MIT",
"dependencies": {
"chownr": "^1.1.1",
"mkdirp-classic": "^0.5.2",
@ -12392,10 +12394,11 @@
}
},
"node_modules/targz/node_modules/tar-fs": {
"version": "1.16.3",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-1.16.3.tgz",
"integrity": "sha512-NvCeXpYx7OsmOh8zIOP/ebG55zZmxLE0etfWRbWok+q2Qo8x/vOR/IJT1taADXPe+jsiu9axDb3X4B+iIgNlKw==",
"version": "1.16.4",
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-1.16.4.tgz",
"integrity": "sha512-u3XczWoYAIVXe5GOKK6+VeWaHjtc47W7hyuTo3+4cNakcCcuDmlkYiiHEsECwTkcI3h1VUgtwBQ54+RvY6cM4w==",
"dev": true,
"license": "MIT",
"dependencies": {
"chownr": "^1.0.1",
"mkdirp": "^0.5.1",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.18",
"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"],

7
gui/package-lock.json generated
View file

@ -107,9 +107,9 @@
"version": "1.1.0",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.758.0",
"@aws-sdk/client-sagemaker-runtime": "^3.758.0",
"@aws-sdk/credential-providers": "^3.758.0",
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
"@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/fetch": "^1.0.4",
@ -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",

BIN
gui/public/logos/docker.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

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,6 +1,6 @@
import { Editor, JSONContent } from "@tiptap/react";
import { ContextItemWithId, InputModifiers } from "core";
import { useMemo, useState } from "react";
import { useMemo } from "react";
import styled, { keyframes } from "styled-components";
import { defaultBorderRadius, vscBackground } from "..";
import { useAppSelector } from "../../redux/hooks";
@ -113,12 +113,10 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
}
: {};
const [lumpOpen, setLumpOpen] = useState(true);
return (
<div className={`${props.hidden ? "hidden" : ""}`}>
<div className={`relative flex flex-col px-2`}>
{props.isMainInput && <Lump open={lumpOpen} setOpen={setLumpOpen} />}
{props.isMainInput && <Lump />}
<GradientBorder
loading={isStreaming && props.isLastUserInput ? 1 : 0}
borderColor={
@ -135,8 +133,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
availableSlashCommands={filteredSlashCommands}
historyKey={historyKey}
toolbarOptions={toolbarOptions}
lumpOpen={lumpOpen}
setLumpOpen={setLumpOpen}
inputId={props.inputId}
/>
</GradientBorder>

View file

@ -31,7 +31,7 @@ import { ToolTip } from "../gui/Tooltip";
import ModelSelect from "../modelSelection/ModelSelect";
import ModeSelect from "../modelSelection/ModeSelect";
import { useFontSize } from "../ui/font";
import HoverItem from "./InputToolbar/bottom/HoverItem";
import HoverItem from "./InputToolbar/HoverItem";
const StyledDiv = styled.div<{ isHidden?: boolean }>`
padding-top: 4px;
@ -87,8 +87,6 @@ interface InputToolbarProps {
toolbarOptions?: ToolbarOptions;
disabled?: boolean;
isMainInput?: boolean;
lumpOpen: boolean;
setLumpOpen: (open: boolean) => void;
}
function InputToolbar(props: InputToolbarProps) {

View file

@ -1,22 +0,0 @@
import { EllipsisHorizontalIcon } from "@heroicons/react/24/outline";
import { ToolbarOptions } from "../../InputToolbar";
import HoverItem from "../bottom/HoverItem";
interface TopInputToolbarProps {
toolbarOptions?: ToolbarOptions;
onAddContextItem?: () => void;
lumpOpen: boolean;
setLumpOpen: (open: boolean) => void;
}
export function TopInputToolbar(props: TopInputToolbarProps) {
return (
<div className="-mb-2 -mt-1 flex items-center">
<HoverItem
onClick={() => props.setLumpOpen(!props.lumpOpen)}
className="ml-auto"
>
<EllipsisHorizontalIcon className="h-3 w-3 text-gray-400 hover:brightness-125" />
</HoverItem>
</div>
);
}

View file

@ -13,7 +13,7 @@ import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import { toggleBlockSettingsToolbar } from "../../../redux/slices/uiSlice";
import { fontSize } from "../../../util";
import AssistantSelect from "../../modelSelection/platform/AssistantSelect";
import HoverItem from "../InputToolbar/bottom/HoverItem";
import HoverItem from "../InputToolbar/HoverItem";
interface BlockSettingsToolbarIcon {
tooltip: string;
@ -129,7 +129,7 @@ export function BlockSettingsTopToolbar(props: BlockSettingsTopToolbarProps) {
</div>
</div>
</div>
<div className="ml-auto">
<div>
<AssistantSelect />
</div>
</div>

View file

@ -1,5 +1,6 @@
import { useContext } from "react";
import styled from "styled-components";
import { AnimatedEllipsis } from "../..";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import { cancelStream } from "../../../redux/thunks/cancelStream";
@ -8,7 +9,8 @@ import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar";
const Container = styled.div`
display: flex;
justify-content: flex-end;
justify-content: space-between;
align-items: center;
width: 100%;
`;
@ -24,6 +26,15 @@ interface TopToolbarProps {
setSelectedSection: (value: string | null) => void;
}
function GeneratingIndicator() {
return (
<div className="text-xs text-gray-400">
<span>Generating</span>
<AnimatedEllipsis />
</div>
);
}
export function LumpToolbar(props: TopToolbarProps) {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
@ -33,6 +44,7 @@ export function LumpToolbar(props: TopToolbarProps) {
if (ttsActive) {
return (
<Container>
<GeneratingIndicator />
<StopButton
className="text-gray-400"
onClick={() => {
@ -48,6 +60,7 @@ export function LumpToolbar(props: TopToolbarProps) {
if (isStreaming) {
return (
<Container>
<GeneratingIndicator />
<StopButton
className="text-gray-400"
onClick={() => {

View file

@ -9,12 +9,7 @@ import { useAppSelector } from "../../../redux/hooks";
import { LumpToolbar } from "./LumpToolbar";
import { SelectedSection } from "./sections/SelectedSection";
interface LumpProps {
open: boolean;
setOpen: (open: boolean) => void;
}
const LumpDiv = styled.div<{ open: boolean }>`
const LumpDiv = styled.div`
background-color: ${vscInputBackground};
margin-left: 4px;
margin-right: 4px;
@ -35,33 +30,50 @@ const ContentDiv = styled.div<{ hasSection: boolean; isVisible: boolean }>`
overflow-y: auto;
`;
export function Lump(props: LumpProps) {
const { open, setOpen } = props;
export function Lump() {
const [selectedSection, setSelectedSection] = useState<string | null>(null);
const [displayedSection, setDisplayedSection] = useState<string | null>(null);
const [isVisible, setIsVisible] = useState(false);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
useEffect(() => {
if (!selectedSection) {
return;
}
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") {
setSelectedSection(null);
}
};
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}, [selectedSection]);
useEffect(() => {
if (isStreaming) {
setSelectedSection(null);
}
}, [isStreaming]);
useEffect(() => {
if (selectedSection) {
setDisplayedSection(selectedSection);
setIsVisible(true);
} else {
setIsVisible(false);
// Delay clearing the displayed section until after the fade-out
const timeout = setTimeout(() => {
setDisplayedSection(null);
}, 300); // Match the transition duration
return () => clearTimeout(timeout);
}, 300);
return () => {
clearTimeout(timeout);
};
}
}, [selectedSection]);
if (!open) {
return null;
}
return (
<LumpDiv open={open}>
<LumpDiv>
<div className="mt-0.5 px-2">
<LumpToolbar
selectedSection={selectedSection}
@ -73,9 +85,7 @@ export function Lump(props: LumpProps) {
hasSection={!!selectedSection}
isVisible={isVisible}
>
{!isStreaming && (
<SelectedSection selectedSection={displayedSection} />
)}
<SelectedSection selectedSection={displayedSection} />
</ContentDiv>
</div>
</LumpDiv>

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

@ -4,7 +4,7 @@ import { MCPSection } from "./MCPSection";
import { ModelsSection } from "./ModelsSection";
import { PromptsSection } from "./PromptsSection";
import { RulesSection } from "./RulesSection";
import { ToolsSection } from "./ToolsSection";
import { ToolPoliciesSection } from "./tool-policies/ToolPoliciesSection";
interface SelectedSectionProps {
selectedSection: string | null;
@ -23,7 +23,7 @@ export function SelectedSection(props: SelectedSectionProps) {
case "context":
return <ContextSection />;
case "tools":
return <ToolsSection />;
return <ToolPoliciesSection />;
case "mcp":
return <MCPSection />;
default:

View file

@ -1,7 +0,0 @@
import { ToolPermissionsDialog } from "../../InputToolbar/bottom/ToolPermissionsDialog";
interface ToolsSectionProps {}
export function ToolsSection({}: ToolsSectionProps) {
return <ToolPermissionsDialog />;
}

View file

@ -1,12 +1,12 @@
import { Tool } from "core";
import { useMemo } from "react";
import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
import { toggleToolGroupSetting } from "../../../../redux/slices/uiSlice";
import { fontSize } from "../../../../util";
import ToggleSwitch from "../../../gui/Switch";
import ToolDropdownItem from "./ToolDropdownItem";
import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks";
import { toggleToolGroupSetting } from "../../../../../redux/slices/uiSlice";
import { fontSize } from "../../../../../util";
import ToggleSwitch from "../../../../gui/Switch";
import ToolPolicyItem from "./ToolPolicyItem";
export const ToolPermissionsDialog = () => {
export const ToolPoliciesSection = () => {
const availableTools = useAppSelector((state) => state.config.config.tools);
const toolGroupSettings = useAppSelector(
(store) => store.ui.toolGroupSettings,
@ -61,7 +61,7 @@ export const ToolPermissionsDialog = () => {
</div>
<div className="relative flex flex-col p-1">
{tools.map((tool) => (
<ToolDropdownItem
<ToolPolicyItem
key={tool.uri + tool.function.name}
tool={tool}
duplicatesDetected={duplicateDetection[tool.function.name]}

View file

@ -2,10 +2,13 @@ import { InformationCircleIcon } from "@heroicons/react/24/outline";
import { Tool } from "core";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { useAppSelector } from "../../../../redux/hooks";
import { addTool, toggleToolSetting } from "../../../../redux/slices/uiSlice";
import { fontSize } from "../../../../util";
import { ToolTip } from "../../../gui/Tooltip";
import { useAppSelector } from "../../../../../redux/hooks";
import {
addTool,
toggleToolSetting,
} from "../../../../../redux/slices/uiSlice";
import { fontSize } from "../../../../../util";
import { ToolTip } from "../../../../gui/Tooltip";
interface ToolDropdownItemProps {
tool: Tool;
@ -13,19 +16,19 @@ interface ToolDropdownItemProps {
excluded: boolean;
}
function ToolDropdownItem(props: ToolDropdownItemProps) {
function ToolPolicyItem(props: ToolDropdownItemProps) {
const dispatch = useDispatch();
const settings = useAppSelector(
const policy = useAppSelector(
(state) => state.ui.toolSettings[props.tool.function.name],
);
useEffect(() => {
if (!settings) {
if (!policy) {
dispatch(addTool(props.tool));
}
}, [props.tool.function.name, settings]);
}, [props.tool.function.name, policy]);
if (!settings) {
if (!policy) {
return null;
}
@ -81,13 +84,13 @@ function ToolDropdownItem(props: ToolDropdownItemProps) {
<span className="text-lightgray">Excluded</span>
) : (
<div className="flex cursor-pointer gap-2">
{(settings === "allowedWithPermission" || settings === undefined) && (
{(policy === "allowedWithPermission" || policy === undefined) && (
<span className="text-yellow-500">Ask First</span>
)}
{settings === "allowedWithoutPermission" && (
{policy === "allowedWithoutPermission" && (
<span className="text-green-500">Automatic</span>
)}
{settings === "disabled" && (
{policy === "disabled" && (
<span className="text-lightgray">Excluded</span>
)}
</div>
@ -96,4 +99,4 @@ function ToolDropdownItem(props: ToolDropdownItemProps) {
);
}
export default ToolDropdownItem;
export default ToolPolicyItem;

View file

@ -32,8 +32,6 @@ export interface TipTapEditorProps {
) => void;
editorState?: JSONContent;
toolbarOptions?: ToolbarOptions;
lumpOpen: boolean;
setLumpOpen: (open: boolean) => void;
placeholder?: string;
historyKey: string;
inputId: string;
@ -262,8 +260,6 @@ function TipTapEditor(props: TipTapEditorProps) {
activeKey={activeKey}
hidden={shouldHideToolbar && !props.isMainInput}
onAddContextItem={() => insertCharacterWithWhitespace("@")}
lumpOpen={props.lumpOpen}
setLumpOpen={props.setLumpOpen}
onEnter={onEnterRef.current}
onImageFileSelected={(file) => {
handleImageFile(ideMessenger, file).then((result) => {

View file

@ -1,12 +1,13 @@
import {
ArrowTopRightOnSquareIcon,
BuildingOfficeIcon,
CheckIcon,
ChevronDownIcon,
Cog6ToothIcon,
ExclamationTriangleIcon,
PlusIcon,
} from "@heroicons/react/24/outline";
import { useContext, useEffect, useMemo, useRef, useState } from "react";
import { useContext, useEffect, useMemo, useRef } from "react";
import { useAuth } from "../../../context/Auth";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { cycleProfile, selectProfileThunk } from "../../../redux";
@ -35,14 +36,16 @@ import AssistantIcon from "./AssistantIcon";
interface AssistantSelectOptionProps {
profile: ProfileDescription;
selected: boolean;
onClick: () => void;
}
const AssistantSelectOption = ({
profile,
selected,
onClick,
}: AssistantSelectOptionProps) => {
const navigate = useNavigate();
const [hovered, setHovered] = useState(false);
const hasFatalErrors = useMemo(() => {
return !!profile.errors?.find((error) => error.fatal);
@ -72,8 +75,6 @@ const AssistantSelectOption = ({
return (
<ListboxOption
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
value={profile.id}
disabled={hasFatalErrors}
onClick={!hasFatalErrors ? handleOptionClick : undefined}
@ -81,20 +82,22 @@ const AssistantSelectOption = ({
>
<div className="flex w-full flex-col gap-0.5">
<div className="flex w-full items-center justify-between">
<div className="flex w-full items-center">
<div className="flex w-full items-center gap-2">
<div className="mr-2 h-4 w-4 flex-shrink-0">
<AssistantIcon assistant={profile} />
</div>
<span className="line-clamp-1 flex-1">{profile.title}</span>
<span
className={`line-clamp-1 flex-1 ${selected ? "font-bold" : ""}`}
>
{profile.title}
</span>
</div>
<div className="ml-2 flex items-center">
<div className="flex flex-row items-center gap-2">
<div>{selected ? <CheckIcon className="h-3 w-3" /> : null}</div>
{!profile.errors?.length ? (
isLocalProfile(profile) ? (
<Cog6ToothIcon
className="h-3 w-3 flex-shrink-0 cursor-pointer"
style={{
opacity: hovered ? 1 : 0,
}}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
@ -103,9 +106,6 @@ const AssistantSelectOption = ({
/>
) : (
<ArrowTopRightOnSquareIcon
style={{
opacity: hovered ? 1 : 0,
}}
className="h-3 w-3 flex-shrink-0 cursor-pointer"
onClick={(e) => {
e.stopPropagation();
@ -215,7 +215,7 @@ export default function AssistantSelect() {
return (
<Listbox>
<div className="sm:max-w-4/5 relative flex">
<div className="relative">
<ListboxButton
data-testid="assistant-select-button"
ref={buttonRef}
@ -249,6 +249,7 @@ export default function AssistantSelect() {
key={idx}
profile={profile}
onClick={close}
selected={profile.id === selectedProfile.id}
/>
);
})}

View file

@ -46,7 +46,7 @@ const ListboxOptions = React.forwardRef<HTMLUListElement, ListboxOptionsProps>(
anchor={"bottom start"}
{...props}
className={cn(
"bg-vsc-input-background flex flex-col overflow-auto px-0 shadow-md",
"bg-vsc-input-background flex w-max min-w-[160px] max-w-[400px] flex-col overflow-auto px-0 shadow-md",
props.className,
)}
style={{

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

@ -887,6 +887,48 @@ export const models: { [key: string]: ModelPackage } = {
providerOptions: ["gemini"],
isOpenSource: false,
},
gemini20FlashLite: {
title: "Gemini 2.0 Flash Lite",
description:
"A more efficient version of Gemini 2.0 Flash optimized for faster responses and lower resource usage.",
params: {
title: "Gemini 2.0 Flash Lite",
model: "gemini-2.0-flash-lite",
contextLength: 1_048_576,
apiKey: "<API_KEY>",
},
icon: "gemini.png",
providerOptions: ["gemini"],
isOpenSource: false,
},
gemini20FlashImageGeneration: {
title: "Gemini 2.0 Flash Image Generation",
description:
"A version of Gemini 2.0 Flash optimized for image generation capabilities.",
params: {
title: "Gemini 2.0 Flash Image Generation",
model: "gemini-2.0-flash-exp-image-generation",
contextLength: 32_768,
apiKey: "<API_KEY>",
},
icon: "gemini.png",
providerOptions: ["gemini"],
isOpenSource: false,
},
gemini25ProExp: {
title: "Gemini 2.5 Pro Experimental",
description:
"Experimental version of Gemini 2.5 Pro with enhanced capabilities and larger output limits.",
params: {
title: "Gemini 2.5 Pro Experimental",
model: "gemini-2.5-pro-exp-03-25",
contextLength: 1_048_576,
apiKey: "<API_KEY>",
},
icon: "gemini.png",
providerOptions: ["gemini"],
isOpenSource: false,
},
commandR: {
title: "Command R",
description:

View file

@ -495,6 +495,9 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n
],
packages: [
models.gemini20Flash,
models.gemini20FlashLite,
models.gemini20FlashImageGeneration,
models.gemini25ProExp,
models.gemini15Pro,
models.geminiPro,
models.gemini15Flash,

View file

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

View file

@ -101,55 +101,69 @@ export function UserSettingsForm() {
}, [ideMessenger]);
return (
<div className="divide-x-0 divide-y-2 divide-solid divide-zinc-700">
<div className="flex flex-col pt-3">
{/* {selectedProfile && isLocalProfile(selectedProfile) ? (
<div className="flex items-center justify-center">
<SecondaryButton
className="flex flex-row items-center gap-1"
onClick={() => {
ideMessenger.post("config/openProfile", {
profileId: selectedProfile.id,
});
}}
>
<span>Open</span>
<span>Config</span>
<span className="xs:flex hidden">File</span>
</SecondaryButton>
</div>
) : null} */}
{!controlServerBetaEnabled || hubEnabled ? (
<div className="flex flex-col">
<div className="flex flex-col">
<div className="flex flex-col gap-4 py-6">
<div>
<h2 className="mb-2 mt-0">User settings</h2>
</div>
<div className="flex flex-col gap-4 py-4">
<div>
<h2 className="mb-2 mt-0 p-0">User settings</h2>
</div>
<div className="flex flex-col gap-4">
<ToggleSwitch
isToggled={showSessionTabs}
onToggle={() =>
handleUpdate({
showSessionTabs: !showSessionTabs,
})
}
text="Show Session Tabs"
/>
<ToggleSwitch
isToggled={codeWrap}
onToggle={() =>
handleUpdate({
codeWrap: !codeWrap,
})
}
text="Wrap Codeblocks"
/>
<div className="flex flex-col gap-4">
<ToggleSwitch
isToggled={showSessionTabs}
onToggle={() =>
handleUpdate({
showSessionTabs: !showSessionTabs,
})
}
text="Show Session Tabs"
/>
<ToggleSwitch
isToggled={codeWrap}
onToggle={() =>
handleUpdate({
codeWrap: !codeWrap,
})
}
text="Wrap Codeblocks"
/>
<ToggleSwitch
isToggled={showChatScrollbar}
onToggle={() =>
handleUpdate({
showChatScrollbar: !showChatScrollbar,
})
}
text="Show Chat Scrollbar"
/>
<ToggleSwitch
isToggled={readResponseTTS}
onToggle={() =>
handleUpdate({
readResponseTTS: !readResponseTTS,
})
}
text="Text-to-Speech Output"
/>
<ToggleSwitch
isToggled={showChatScrollbar}
onToggle={() =>
handleUpdate({
showChatScrollbar: !showChatScrollbar,
})
}
text="Show Chat Scrollbar"
/>
<ToggleSwitch
isToggled={readResponseTTS}
onToggle={() =>
handleUpdate({
readResponseTTS: !readResponseTTS,
})
}
text="Text-to-Speech Output"
/>
{/* <ToggleSwitch
{/* <ToggleSwitch
isToggled={useChromiumForDocsCrawling}
onToggle={() =>
handleUpdate({
@ -158,46 +172,46 @@ export function UserSettingsForm() {
}
text="Use Chromium for Docs Crawling"
/> */}
<ToggleSwitch
isToggled={!disableSessionTitles}
onToggle={() =>
handleUpdate({
disableSessionTitles: !disableSessionTitles,
})
}
text="Enable Session Titles"
/>
<ToggleSwitch
isToggled={!displayRawMarkdown}
onToggle={() =>
handleUpdate({
displayRawMarkdown: !displayRawMarkdown,
})
}
text="Format Markdown"
/>
<ToggleSwitch
isToggled={!disableSessionTitles}
onToggle={() =>
handleUpdate({
disableSessionTitles: !disableSessionTitles,
})
}
text="Enable Session Titles"
/>
<ToggleSwitch
isToggled={!displayRawMarkdown}
onToggle={() =>
handleUpdate({
displayRawMarkdown: !displayRawMarkdown,
})
}
text="Format Markdown"
/>
<ToggleSwitch
isToggled={allowAnonymousTelemetry}
onToggle={() =>
handleUpdate({
allowAnonymousTelemetry: !allowAnonymousTelemetry,
})
}
text="Allow Anonymous Telemetry"
/>
<ToggleSwitch
isToggled={allowAnonymousTelemetry}
onToggle={() =>
handleUpdate({
allowAnonymousTelemetry: !allowAnonymousTelemetry,
})
}
text="Allow Anonymous Telemetry"
/>
<ToggleSwitch
isToggled={!disableIndexing}
onToggle={() =>
handleUpdate({
disableIndexing: !disableIndexing,
})
}
text="Enable Indexing"
/>
<ToggleSwitch
isToggled={!disableIndexing}
onToggle={() =>
handleUpdate({
disableIndexing: !disableIndexing,
})
}
text="Enable Indexing"
/>
{/* <ToggleSwitch
{/* <ToggleSwitch
isToggled={useAutocompleteCache}
onToggle={() =>
handleUpdate({
@ -207,89 +221,86 @@ export function UserSettingsForm() {
text="Use Autocomplete Cache"
/> */}
<label className="flex items-center justify-between gap-3">
<span className="text-left">Font Size</span>
<NumberInput
value={fontSize}
onChange={(val) =>
handleUpdate({
fontSize: val,
})
}
min={7}
max={50}
<label className="flex items-center justify-between gap-3">
<span className="text-left">Font Size</span>
<NumberInput
value={fontSize}
onChange={(val) =>
handleUpdate({
fontSize: val,
})
}
min={7}
max={50}
/>
</label>
<label className="flex items-center justify-between gap-3">
<span className="line-clamp-1 text-left">
Multiline Autocompletions
</span>
<Select
value={useAutocompleteMultilineCompletions}
onChange={(e) =>
handleUpdate({
useAutocompleteMultilineCompletions: e.target.value as
| "auto"
| "always"
| "never",
})
}
>
<option value="auto">Auto</option>
<option value="always">Always</option>
<option value="never">Never</option>
</Select>
</label>
<form
className="flex flex-col gap-1"
onSubmit={(e) => {
e.preventDefault();
handleDisableAutocompleteSubmit();
}}
>
<div className="flex items-center justify-between">
<span>Disable autocomplete in files</span>
<div className="flex items-center gap-2">
<Input
value={formDisableAutocomplete}
className="max-w-[100px]"
onChange={(e) => {
setFormDisableAutocomplete(e.target.value);
}}
/>
</label>
<label className="flex items-center justify-between gap-3">
<span className="line-clamp-1 text-left">
Multiline Autocompletions
</span>
<Select
value={useAutocompleteMultilineCompletions}
onChange={(e) =>
handleUpdate({
useAutocompleteMultilineCompletions: e.target.value as
| "auto"
| "always"
| "never",
})
}
>
<option value="auto">Auto</option>
<option value="always">Always</option>
<option value="never">Never</option>
</Select>
</label>
<form
className="flex flex-col gap-1"
onSubmit={(e) => {
e.preventDefault();
handleDisableAutocompleteSubmit();
}}
>
<div className="flex items-center justify-between">
<span>Disable autocomplete in files</span>
<div className="flex items-center gap-2">
<Input
value={formDisableAutocomplete}
className="max-w-[100px]"
onChange={(e) => {
setFormDisableAutocomplete(e.target.value);
}}
/>
<div className="flex h-full flex-col">
{formDisableAutocomplete !==
disableAutocompleteInFiles ? (
<>
<div
onClick={handleDisableAutocompleteSubmit}
className="cursor-pointer"
>
<CheckIcon className="h-4 w-4 text-green-500 hover:opacity-80" />
</div>
<div
onClick={cancelChangeDisableAutocomplete}
className="cursor-pointer"
>
<XMarkIcon className="h-4 w-4 text-red-500 hover:opacity-80" />
</div>
</>
) : (
<div>
<CheckIcon className="text-vsc-foreground-muted h-4 w-4" />
</div>
)}
<div className="flex h-full flex-col">
{formDisableAutocomplete !== disableAutocompleteInFiles ? (
<>
<div
onClick={handleDisableAutocompleteSubmit}
className="cursor-pointer"
>
<CheckIcon className="h-4 w-4 text-green-500 hover:opacity-80" />
</div>
<div
onClick={cancelChangeDisableAutocomplete}
className="cursor-pointer"
>
<XMarkIcon className="h-4 w-4 text-red-500 hover:opacity-80" />
</div>
</>
) : (
<div>
<CheckIcon className="text-vsc-foreground-muted h-4 w-4" />
</div>
</div>
)}
</div>
<span className="text-vsc-foreground-muted text-lightgray self-end text-xs">
Comma-separated list of path matchers
</span>
</form>
</div>
</div>
</div>
<span className="text-vsc-foreground-muted text-lightgray self-end text-xs">
Comma-separated list of path matchers
</span>
</form>
</div>
</div>
) : null}

View file

@ -130,7 +130,7 @@ export function ToolCallDisplay(props: ToolCallDisplayProps) {
{args.map(([key, value]) => (
<div key={key} className="flex gap-2 py-0.5">
<span className="text-lightgray">{key}:</span>
<code className="line-clamp-1">{value}</code>
<code className="line-clamp-1">{value.toString()}</code>
</div>
))}
</div>

View file

@ -52,6 +52,7 @@ export const uiSlice = createSlice({
[BuiltInToolNames.ExactSearch]: "allowedWithoutPermission",
[BuiltInToolNames.SearchWeb]: "allowedWithoutPermission",
[BuiltInToolNames.ViewDiff]: "allowedWithoutPermission",
[BuiltInToolNames.LSTool]: "allowedWithoutPermission",
},
toolGroupSettings: {
BUILT_IN_GROUP_NAME: "include",

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 {

4
package-lock.json generated
View file

@ -8,7 +8,8 @@
"@typescript-eslint/parser": "^7.8.0",
"eslint-plugin-import": "^2.29.1",
"prettier": "^3.3.3",
"prettier-plugin-tailwindcss": "^0.6.8"
"prettier-plugin-tailwindcss": "^0.6.8",
"typescript": "^5.6.3"
}
},
"node_modules/@eslint-community/eslint-utils": {
@ -2976,7 +2977,6 @@
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz",
"integrity": "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==",
"dev": true,
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/config-yaml",
"version": "1.0.75",
"version": "1.0.76",
"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>();
@ -145,6 +146,7 @@ function extractFQSNMap(
async function extractRenderedSecretsMap(
rawContent: string,
platformClient: PlatformClient,
alwaysUseProxy: boolean = false,
): Promise<Record<string, string>> {
// Get all template variables
const templateVars = getTemplateVariables(rawContent);
@ -164,7 +166,7 @@ async function extractRenderedSecretsMap(
}
// User secrets are rendered
if ("value" in secretResult) {
if ("value" in secretResult && !alwaysUseProxy) {
map[encodeFQSN(secretResult.fqsn)] = secretResult.value;
} else {
// Other secrets are rendered as secret locations and then converted to proxy types later
@ -186,6 +188,7 @@ export interface RenderSecretsUnrollAssistantOptions {
currentUserSlug: string;
platformClient: PlatformClient;
onPremProxyUrl: string | null;
alwaysUseProxy?: boolean;
}
export type UnrollAssistantOptions =
@ -255,6 +258,7 @@ export async function unrollAssistantFromContent(
const secrets = await extractRenderedSecretsMap(
templatedYaml,
options.platformClient,
options.alwaysUseProxy,
);
const renderedYaml = renderTemplateData(templatedYaml, {
secrets,
@ -320,13 +324,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: Array<string | null> = [];
const rules: (Rule | null)[] = [];
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) {
try {
const blockConfigYaml = await resolveBlock(
decodeFullSlug(rule.uses),

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(),
@ -94,7 +104,7 @@ export const assistantUnrolledSchemaNonNullable = 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(),
});
@ -120,7 +130,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;
}
}

View file

@ -11,6 +11,33 @@ export const Gemini: ModelProvider = {
regex: /gemini-2\.0-flash/i,
recommendedFor: ["chat"]
},
{
model: "gemini-2.0-flash-lite",
displayName: "Gemini 2.0 Flash Lite",
contextLength: 1048576,
maxCompletionTokens: 8192,
mediaTypes: AllMediaTypes,
regex: /gemini-2\.0-flash-lite/i,
recommendedFor: ["chat"]
},
{
model: "gemini-2.0-flash-exp-image-generation",
displayName: "Gemini 2.0 Flash Image Generation",
contextLength: 32768,
maxCompletionTokens: 8192,
mediaTypes: AllMediaTypes,
regex: /gemini-2\.0-flash-exp-image-generation/i,
recommendedFor: ["chat"]
},
{
model: "gemini-2.5-pro-exp-03-25",
displayName: "Gemini 2.5 Pro Exp",
contextLength: 1048576,
maxCompletionTokens: 65536,
mediaTypes: AllMediaTypes,
regex: /gemini-2\.5-pro-exp-03-25/i,
recommendedFor: ["chat"]
},
{
model: "gemini-1.5-flash",
displayName: "Gemini 1.5 Flash",

View file

@ -11,6 +11,33 @@ export const Gemini: ModelProvider = {
regex: /gemini-2\.0-flash/i,
recommendedFor: ["chat"]
},
{
model: "gemini-2.0-flash-lite",
displayName: "Gemini 2.0 Flash Lite",
contextLength: 1048576,
maxCompletionTokens: 8192,
mediaTypes: AllMediaTypes,
regex: /gemini-2\.0-flash-lite/i,
recommendedFor: ["chat"]
},
{
model: "gemini-2.0-flash-exp-image-generation",
displayName: "Gemini 2.0 Flash Image Generation",
contextLength: 32768,
maxCompletionTokens: 8192,
mediaTypes: AllMediaTypes,
regex: /gemini-2\.0-flash-exp-image-generation/i,
recommendedFor: ["chat"]
},
{
model: "gemini-2.5-pro-exp-03-25",
displayName: "Gemini 2.5 Pro Exp",
contextLength: 1048576,
maxCompletionTokens: 65536,
mediaTypes: AllMediaTypes,
regex: /gemini-2\.5-pro-exp-03-25/i,
recommendedFor: ["chat"]
},
{
model: "gemini-1.5-flash",
displayName: "Gemini 1.5 Flash",

View file

@ -1,22 +1,22 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.0.12",
"version": "1.0.18",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/openai-adapters",
"version": "1.0.12",
"version": "1.0.18",
"license": "Apache-2.0",
"dependencies": {
"@azure/openai": "^1.0.0-beta.12",
"@continuedev/config-types": "^1.0.5",
"@continuedev/config-yaml": "^1.0.31",
"@continuedev/config-yaml": "^1.0.51",
"@continuedev/fetch": "^1.0.3",
"json-schema": "^0.4.0",
"node-fetch": "^3.3.2",
"openai": "^4.76.0",
"zod": "^3.23.8"
"zod": "^3.24.2"
},
"devDependencies": {
"@types/follow-redirects": "^1.14.4",
@ -712,13 +712,14 @@
}
},
"node_modules/@continuedev/config-yaml": {
"version": "1.0.31",
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.31.tgz",
"integrity": "sha512-HNj+z7UTTARgsJTI0A1buM09fS4HoWVnn6Hbl6kJ2tZmOOm1OgogbcKP68AzHb4fy5H18MWnKS7XuseZpHFzHQ==",
"version": "1.0.68",
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.68.tgz",
"integrity": "sha512-rCegSGkv7Ws7LLnYVVGwXsoVZFpNFJnG6b1dVrj/u+2ZsFdA2leQUNtFGoeE/ixyfhUfBpMlgjEyPrmmy7gLjw==",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
"yaml": "^2.6.1",
"zod": "^3.23.8"
"zod": "^3.24.2"
}
},
"node_modules/@continuedev/fetch": {
@ -4541,9 +4542,10 @@
}
},
"node_modules/zod": {
"version": "3.23.8",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz",
"integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==",
"version": "3.24.2",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.24.2.tgz",
"integrity": "sha512-lY7CDW43ECgW9u1TcT3IoXHflywfVqDYze4waEz812jR/bZ8FHDsl7pFQoSZTz5N+2NqRXs8GBwnAwo3ZNxqhQ==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}

View file

@ -1,5 +1,4 @@
import { streamSse } from "@continuedev/fetch";
import fetch from "node-fetch";
import { OpenAI } from "openai/index";
import {
ChatCompletion,
@ -14,7 +13,7 @@ import {
} from "openai/resources/index";
import { z } from "zod";
import { OpenAIConfigSchema } from "../types.js";
import { customFetch, maybeCustomFetch } from "../util.js";
import { customFetch } from "../util.js";
import {
BaseLlmApi,
CreateRerankResponse,
@ -36,8 +35,9 @@ export class OpenAIApi implements BaseLlmApi {
}
modifyChatBody<T extends ChatCompletionCreateParams>(body: T): T {
// o-series models
if (body.model.startsWith("o")) {
// o-series models - only apply for official OpenAI API
const isOfficialOpenAIAPI = this.apiBase === "https://api.openai.com/v1/";
if (isOfficialOpenAIAPI && body.model.startsWith("o")) {
// a) use max_completion_tokens instead of max_tokens
body.max_completion_tokens = body.max_tokens;
body.max_tokens = undefined;