Merge branch 'main' into nate/local-blocks

# Conflicts:
#	core/llm/countTokens.ts
This commit is contained in:
Nate 2025-04-24 11:56:14 -07:00
commit 4bd0c686ef
94 changed files with 1430 additions and 960 deletions

1
.idea/gradle.xml generated
View file

@ -5,6 +5,7 @@
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
<option name="gradleJvm" value="homebrew-17" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$/extensions/intellij" />

View file

@ -1 +1 @@
20.11.0
20.19.0

2
.nvmrc
View file

@ -1 +1 @@
v20.11.0
v20.19.0

View file

@ -102,7 +102,7 @@ We welcome contributions from developers of all experience levels - from first-t
#### Pre-requisites
You should have Node.js version 20.11.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
You should have Node.js version 20.19.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
```bash
nvm use

View file

@ -9,17 +9,20 @@ const {
autodetectPlatformAndArch,
} = require("../scripts/util");
// Clean slate
const bin = path.join(__dirname, "bin");
const out = path.join(__dirname, "out");
const build = path.join(__dirname, "build");
rimrafSync(bin);
rimrafSync(out);
rimrafSync(build);
rimrafSync(path.join(__dirname, "tmp"));
fs.mkdirSync(bin);
fs.mkdirSync(out);
fs.mkdirSync(build);
function cleanSlate() {
// Clean slate
rimrafSync(bin);
rimrafSync(out);
rimrafSync(build);
rimrafSync(path.join(__dirname, "tmp"));
fs.mkdirSync(bin);
fs.mkdirSync(out);
fs.mkdirSync(build);
}
const esbuildOutputFile = "out/index.js";
let targets = [
@ -56,6 +59,39 @@ const targetToLanceDb = {
"win32-arm64": "@lancedb/vectordb-win32-arm64-msvc",
};
// Bundles the extension into one file
async function buildWithEsbuild() {
console.log("[info] Building with esbuild...");
await esbuild.build({
entryPoints: ["src/index.ts"],
bundle: true,
outfile: esbuildOutputFile,
external: [
"esbuild",
"./xhr-sync-worker.js",
"llamaTokenizerWorkerPool.mjs",
"tiktokenWorkerPool.mjs",
"vscode",
"./index.node",
],
format: "cjs",
platform: "node",
sourcemap: true,
minify: true,
treeShaking: true,
loader: {
// eslint-disable-next-line @typescript-eslint/naming-convention
".node": "file",
},
// To allow import.meta.path for transformers.js
// https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483
inject: ["./importMetaUrl.js"],
define: { "import.meta.url": "importMetaUrl" },
});
}
async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
console.log(`Copying ${packageName} to ${toCopy}`);
// This is a way to install only one package without npm trying to install all the dependencies
@ -118,6 +154,13 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
}
(async () => {
if (esbuildOnly) {
await buildWithEsbuild();
return;
}
cleanSlate()
// Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
// This is only needed for our `pkg` command at build time
fs.writeFileSync(
@ -192,35 +235,7 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
fs.rmSync(assetPath, { force: true });
}
// Bundles the extension into one file
console.log("[info] Building with esbuild...");
await esbuild.build({
entryPoints: ["src/index.ts"],
bundle: true,
outfile: esbuildOutputFile,
external: [
"esbuild",
"./xhr-sync-worker.js",
"llamaTokenizerWorkerPool.mjs",
"tiktokenWorkerPool.mjs",
"vscode",
"./index.node",
],
format: "cjs",
platform: "node",
sourcemap: true,
minify: true,
treeShaking: true,
loader: {
// eslint-disable-next-line @typescript-eslint/naming-convention
".node": "file",
},
// To allow import.meta.path for transformers.js
// https://github.com/evanw/esbuild/issues/1492#issuecomment-893144483
inject: ["./importMetaUrl.js"],
define: { "import.meta.url": "importMetaUrl" },
});
await buildWithEsbuild();
// Copy over any worker files
fs.cpSync(
@ -233,10 +248,6 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
"out/llamaTokenizerWorkerPool.mjs",
);
if (esbuildOnly) {
return;
}
console.log("[info] Building binaries with pkg...");
for (const target of targets) {
const targetDir = `bin/${target}`;

View file

@ -140,7 +140,7 @@
"typescript": "^5.6.3"
},
"engines": {
"node": ">=20.11.0"
"node": ">=20.19.0"
}
},
"node_modules/@75lb/deep-merge": {

View file

@ -23,6 +23,7 @@
"scripts": {
"test": "jest",
"build": "node build.js",
"rebuild": "node build.js --esbuild-only",
"build:darwin-x64": "node build.js --os darwin-x64"
},
"license": "Apache-2.0",

View file

@ -13,7 +13,7 @@
"@typescript-eslint/semi": "off",
"eqeqeq": "error",
"complexity": ["error", { "max": 36 }],
"max-lines-per-function": ["error", { "max": 472 }],
"max-lines-per-function": ["error", { "max": 500 }],
"max-statements": ["error", { "max": 108 }],
"max-depth": ["error", { "max": 6 }],
"max-nested-callbacks": ["error", { "max": 4 }],

View file

@ -154,6 +154,10 @@ export class CompletionProvider {
return undefined;
}
if (llm.promptTemplates?.autocomplete) {
options.template = llm.promptTemplates.autocomplete as string;
}
const helper = await HelperVars.create(
input,
options,

View file

@ -403,6 +403,7 @@ declare global {
| "generated"
| "calling"
| "done"
| "errored"
| "canceled";
// Will exist only on "assistant" messages with tool calls

View file

@ -408,15 +408,21 @@ export class Core {
if (!config) {
return [];
}
const items = await config.contextProviders
?.find((provider) => provider.description.title === msg.data.title)
?.loadSubmenuItems({
config,
ide: this.ide,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
});
return items || [];
try {
const items = await config.contextProviders
?.find((provider) => provider.description.title === msg.data.title)
?.loadSubmenuItems({
config,
ide: this.ide,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
});
return items || [];
} catch (e) {
console.error(e);
return [];
}
});
on("context/getContextItems", this.getContextItems.bind(this));
@ -665,7 +671,7 @@ export class Core {
on("didChangeActiveTextEditor", async ({ data: { filepath } }) => {
try {
const ignore = shouldIgnore(filepath, this.ide);
const ignore = await shouldIgnore(filepath, this.ide);
if (!ignore) {
recentlyEditedFilesCache.set(filepath, filepath);
}
@ -676,59 +682,44 @@ export class Core {
}
});
on(
"tools/call",
async ({ data: { toolCall, selectedModelTitle }, messageId }) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
on("tools/call", async ({ data: { toolCall } }) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
throw new Error("Config not loaded");
}
const tool = config.tools.find(
(t) => t.function.name === toolCall.function.name,
);
const tool = config.tools.find(
(t) => t.function.name === toolCall.function.name,
);
if (!tool) {
throw new Error(`Tool ${toolCall.function.name} not found`);
}
if (!tool) {
throw new Error(`Tool ${toolCall.function.name} not found`);
}
if (!config.selectedModelByRole.chat) {
throw new Error("No chat model selected");
}
if (!config.selectedModelByRole.chat) {
throw new Error("No chat model selected");
}
// Define a callback for streaming output updates
const onPartialOutput = (params: {
toolCallId: string;
contextItems: ContextItem[];
}) => {
this.messenger.send("toolCallPartialOutput", params);
};
// Define a callback for streaming output updates
const onPartialOutput = (params: {
toolCallId: string;
contextItems: ContextItem[];
}) => {
this.messenger.send("toolCallPartialOutput", params);
};
const contextItems = await callTool(
tool,
JSON.parse(toolCall.function.arguments || "{}"),
{
ide: this.ide,
llm: config.selectedModelByRole.chat,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
tool,
toolCallId: toolCall.id,
onPartialOutput,
},
);
return await callTool(tool, toolCall.function.arguments, {
ide: this.ide,
llm: config.selectedModelByRole.chat,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
tool,
toolCallId: toolCall.id,
onPartialOutput,
});
});
if (tool.faviconUrl) {
contextItems.forEach((item) => {
item.icon = tool.faviconUrl;
});
}
return { contextItems };
},
);
on("isItemTooBig", async ({ data: { item, selectedModelTitle } }) => {
on("isItemTooBig", async ({ data: { item } }) => {
return this.isItemTooBig(item);
});
@ -927,7 +918,6 @@ export class Core {
query: string;
fullInput: string;
selectedCode: RangeInFile[];
selectedModelTitle: string;
}>,
) => {
const { config } = await this.configHandler.loadConfig();

View file

@ -41,4 +41,16 @@ describe("Test myers diff function", () => {
{ type: "same", line: "C" },
]);
});
test("should ignore single-line whitespace-only differences", () => {
const linesA = "A\n B\nC\n";
const linesB = "A\nB\nC";
const diffLines = myersDiff(linesA, linesB);
expect(diffLines).toEqual([
{ type: "same", line: "A" },
{ type: "same", line: " B" },
{ type: "same", line: "C" },
]);
});
});

View file

@ -30,8 +30,21 @@ export function myersDiff(oldContent: string, newContent: string): DiffLine[] {
const theirFormat = diffLines(oldContent, newContent, {
ignoreNewlineAtEof: true,
});
const ourFormat = theirFormat.flatMap(convertMyersChangeToDiffLines);
let ourFormat = theirFormat.flatMap(convertMyersChangeToDiffLines);
// Combine consecutive old/new pairs that are identical after trimming
for (let i = 0; i < ourFormat.length - 1; i++) {
if (
ourFormat[i]?.type === "old" &&
ourFormat[i + 1]?.type === "new" &&
ourFormat[i].line.trim() === ourFormat[i + 1].line.trim()
) {
ourFormat[i] = { type: "same", line: ourFormat[i].line };
ourFormat.splice(i + 1, 1);
}
}
// Remove trailing empty old lines
while (
ourFormat.length > 0 &&
ourFormat[ourFormat.length - 1].type === "old" &&

View file

@ -4,6 +4,7 @@ import {
ILLM,
Prediction,
RuleWithSource,
ToolResultChatMessage,
UserChatMessage,
} from "../";
import {
@ -104,15 +105,16 @@ export async function* streamDiffLines({
// Rules will be included with edit prompt
// If any rules are present this will result in using chat instead of legacy completion
const lastUserMessage: UserChatMessage | undefined =
const lastUserMessage =
typeof prompt === "string"
? {
? ({
role: "user",
content: prompt,
}
: (findLast(prompt, (msg) => msg.role === "user") as
| UserChatMessage
| undefined);
} as UserChatMessage)
: (findLast(
prompt,
(msg) => msg.role === "user" || msg.role === "tool",
) as UserChatMessage | ToolResultChatMessage | undefined);
const systemMessage = getSystemMessageWithRules({
currentModel: llm.model,
@ -123,11 +125,13 @@ export async function* streamDiffLines({
if (systemMessage) {
if (typeof prompt === "string") {
// Removed system prompt because it was causing it to be used for Apply
// We should bring it back only for Edit
prompt = [
{
role: "system",
content: systemMessage,
},
// {
// role: "system",
// content: systemMessage,
// },
{
role: "user",
content: prompt,
@ -138,10 +142,10 @@ export async function* streamDiffLines({
if (curSysMsg) {
curSysMsg.content = systemMessage + "\n\n" + curSysMsg.content;
} else {
prompt.unshift({
role: "system",
content: systemMessage,
});
// prompt.unshift({
// role: "system",
// content: systemMessage,
// });
}
}
}

5
core/index.d.ts vendored
View file

@ -1,4 +1,4 @@
import { DataDestination, ModelRole } from "@continuedev/config-yaml";
import { DataDestination, ModelRole, PromptTemplates } from "@continuedev/config-yaml";
import Parser from "web-tree-sitter";
import { LLMConfigurationStatuses } from "./llm/constants";
import { GetGhTokenArgs } from "./protocol/ide";
@ -428,6 +428,7 @@ export type ToolStatus =
| "generating"
| "generated"
| "calling"
| "errored"
| "done"
| "canceled";
@ -566,7 +567,7 @@ export interface LLMOptions {
completionOptions?: CompletionOptions;
requestOptions?: RequestOptions;
template?: TemplateType;
promptTemplates?: Record<string, PromptTemplate>;
promptTemplates?: Partial<Record<keyof PromptTemplates, PromptTemplate>>;
templateMessages?: (messages: ChatMessage[]) => string;
logger?: ILLMLogger;
llmRequestHook?: (model: string, prompt: string) => any;

View file

@ -7,26 +7,6 @@ const DEFAULT_ARGS = {
temperature: DEFAULT_TEMPERATURE,
};
const GPT_4_CTX_LEN = 128_000;
const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = {
"gpt-3.5-turbo": 4096,
"gpt-3.5-turbo-0613": 4096,
"gpt-3.5-turbo-16k": 16_384,
"gpt-35-turbo-16k": 16_384,
"gpt-35-turbo-0613": 4096,
"gpt-35-turbo": 4096,
"gpt-4": 4096,
"gpt-4-32k": 32_000,
"gpt-4-turbo-preview": 32_000,
"gpt-4o": GPT_4_CTX_LEN,
"gpt-4o-mini": GPT_4_CTX_LEN,
"gpt-4-vision": GPT_4_CTX_LEN,
"gpt-4-0125-preview": GPT_4_CTX_LEN,
"gpt-4-1106-preview": GPT_4_CTX_LEN,
};
const TOKEN_BUFFER_FOR_SAFETY = 350;
const PROXY_URL = "http://localhost:65433";
const DEFAULT_MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers)
@ -38,12 +18,10 @@ export enum LLMConfigurationStatuses {
}
export {
CONTEXT_LENGTH_FOR_MODEL,
DEFAULT_ARGS,
DEFAULT_CONTEXT_LENGTH,
DEFAULT_MAX_BATCH_SIZE,
DEFAULT_MAX_CHUNK_SIZE,
DEFAULT_MAX_TOKENS,
PROXY_URL,
TOKEN_BUFFER_FOR_SAFETY,
};

View file

@ -3,11 +3,12 @@ import {
ChatMessage,
RuleWithSource,
TextMessagePart,
ToolResultChatMessage,
UserChatMessage,
} from "../";
import { findLast } from "../util/findLast";
import { normalizeToMessageParts } from "../util/messageContent";
import { messageIsEmpty } from "./messages";
import { isUserOrToolMsg } from "./messages";
import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
@ -20,9 +21,9 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
When addressing code modification requests, present a concise code snippet that
emphasizes only the necessary changes and uses abbreviated placeholders for
unmodified sections. For instance:
unmodified sections. For example:
\`\`\`typescript /path/to/file
\`\`\`language /path/to/file
// ... rest of code here ...
{{ modified code here }}
@ -34,6 +35,22 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
// ... rest of code here ...
\`\`\`
In existing files, you should always restate the function or class that the snippet belongs to:
\`\`\`language /path/to/file
// ... rest of code here ...
function exampleFunction() {
// ... rest of code here ...
{{ modified code here }}
// ... rest of code here ...
}
// ... rest of code here ...
\`\`\`
Since users have access to their complete file, they prefer reading only the
relevant modifications. It's perfectly acceptable to omit unmodified portions
at the beginning, middle, or end of files using these "lazy" comments. Only
@ -76,24 +93,20 @@ export function constructMessages(
...historyItem.message,
content,
});
} else if (historyItem.toolCallState?.status === "canceled") {
// Canceled tool call
msgs.push({
...historyItem.message,
content: CANCELED_TOOL_CALL_MESSAGE,
});
} else {
msgs.push(historyItem.message);
}
}
const userMessage = findLast(msgs, (msg) => msg.role === "user") as
const lastUserMsg = findLast(msgs, isUserOrToolMsg) as
| UserChatMessage
| ToolResultChatMessage
| undefined;
const systemMessage = getSystemMessageWithRules({
baseSystemMessage: baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE,
rules,
userMessage,
userMessage: lastUserMsg,
currentModel: modelName,
});
if (systemMessage.trim()) {
@ -103,16 +116,6 @@ export function constructMessages(
});
}
// We dispatch an empty assistant chat message to the history on submission. Don't send it
const lastMessage = msgs.at(-1);
if (
lastMessage &&
lastMessage.role === "assistant" &&
messageIsEmpty(lastMessage)
) {
msgs.pop();
}
// Remove the "id" from all of the messages
return msgs.map((msg) => {
const { id, ...rest } = msg as any;

View file

@ -1,6 +1,6 @@
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
import { ChatMessage, MessageContent, MessagePart } from "../index.js";
import { ChatMessage, MessageContent, MessagePart, Tool } from "../index.js";
import { renderChatMessage } from "../util/messageContent.js";
import {
@ -9,13 +9,13 @@ import {
LlamaAsyncEncoder,
} from "./asyncEncoder.js";
import { autodetectTemplateType } from "./autodetect.js";
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js";
import llamaTokenizer from "./llamaTokenizer.js";
import {
addSpaceToAnyEmptyMessages,
chatMessageIsEmpty,
flattenMessages,
messageHasToolCalls,
isUserOrToolMsg,
messageHasToolCallId,
} from "./messages.js";
interface Encoding {
encode: Tiktoken["encode"];
@ -124,6 +124,51 @@ function countTokens(
}
}
// https://community.openai.com/t/how-to-calculate-the-tokens-when-using-function-call/266573/10
function countToolsTokens(tools: Tool[], modelName: string): number {
const count = (value: string) =>
encodingForModel(modelName).encode(value).length;
let numTokens = 12;
for (const tool of tools) {
let functionTokens = count(tool.function.name);
if (tool.function.description) {
functionTokens += count(tool.function.description);
}
const props = tool.function.parameters?.properties;
if (props) {
for (const key in props) {
functionTokens += count(key);
const fields = props[key];
if (fields) {
const fieldType = fields["type"];
const fieldDesc = fields["description"];
const fieldEnum = fields["enum"];
if (fieldType && typeof fieldType === "string") {
functionTokens += 2;
functionTokens += count(fieldType);
}
if (fieldDesc && typeof fieldDesc === "string") {
functionTokens += 2;
functionTokens += count(fieldDesc);
}
if (fieldEnum && Array.isArray(fieldEnum)) {
functionTokens -= 3;
for (const e of fieldEnum) {
functionTokens += 3;
functionTokens += typeof e === "string" ? count(e) : 5;
}
}
}
}
}
numTokens += functionTokens;
}
return numTokens + 12;
}
function countChatMessageTokens(
modelName: string,
chatMessage: ChatMessage,
@ -131,8 +176,38 @@ function countChatMessageTokens(
// Doing simpler, safer version of what is here:
// https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
// every message follows <|im_start|>{role/name}\n{content}<|end|>\n
const TOKENS_PER_MESSAGE: number = 4;
return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE;
const BASE_TOKENS = 4;
const TOOL_CALL_EXTRA_TOKENS = 10;
const TOOL_OUTPUT_EXTRA_TOKENS = 10;
let tokens = BASE_TOKENS;
if (chatMessage.content) {
tokens += countTokens(chatMessage.content, modelName);
}
if ("toolCalls" in chatMessage && chatMessage.toolCalls) {
for (const call of chatMessage.toolCalls) {
tokens += TOOL_CALL_EXTRA_TOKENS;
tokens += countTokens(JSON.stringify(call), modelName); // TODO hone this
}
}
if (chatMessage.role === "thinking") {
if (chatMessage.redactedThinking) {
tokens += countTokens(chatMessage.redactedThinking, modelName);
}
if (chatMessage.signature) {
tokens += countTokens(chatMessage.signature, modelName);
}
}
if (chatMessage.role === "tool") {
tokens += TOOL_OUTPUT_EXTRA_TOKENS; // safety
if (chatMessage.toolCallId) {
tokens += countTokens(chatMessage.toolCallId, modelName);
}
}
return tokens;
}
function pruneLinesFromTop(
@ -193,6 +268,20 @@ function pruneStringFromTop(
return encoding.decode(tokens.slice(tokens.length - maxTokens));
}
const MAX_TOKEN_SAFETY_BUFFER = 1000;
const TOKEN_SAFETY_PROPORTION = 0.02;
function getTokenCountingBufferSafety(contextLength: number) {
return Math.min(
MAX_TOKEN_SAFETY_BUFFER,
contextLength * TOKEN_SAFETY_PROPORTION,
);
}
const MIN_RESPONSE_TOKENS = 1000;
function getMinResponseTokens(maxTokens: number) {
return Math.min(MIN_RESPONSE_TOKENS, maxTokens);
}
function pruneRawPromptFromTop(
modelName: string,
contextLength: number,
@ -200,188 +289,36 @@ function pruneRawPromptFromTop(
tokensForCompletion: number,
): string {
const maxTokens =
contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY;
contextLength -
tokensForCompletion -
getTokenCountingBufferSafety(contextLength);
return pruneStringFromTop(modelName, maxTokens, prompt);
}
function pruneRawPromptFromBottom(
modelName: string,
contextLength: number,
prompt: string,
tokensForCompletion: number,
): string {
const maxTokens =
contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY;
return pruneStringFromBottom(modelName, maxTokens, prompt);
}
function summarize(message: ChatMessage): string {
return `${renderChatMessage(message).substring(0, 100)}...`;
}
function pruneChatHistory(
modelName: string,
msgs: ChatMessage[],
contextLength: number,
tokensForCompletion: number,
): ChatMessage[] {
// Move system message to 2nd to last to give it priority
const systemMessage = msgs.find((msg) => msg.role === "system");
const chatHistory: ChatMessage[] = msgs.filter(
(msg) => msg.role !== "system",
);
if (systemMessage) {
chatHistory.splice(-1, 0, systemMessage);
}
let totalTokens =
tokensForCompletion +
chatHistory.reduce((acc, message) => {
return acc + countChatMessageTokens(modelName, message);
}, 0);
// 0. Prune any messages that take up more than 1/3 of the context length
const zippedMessagesAndTokens: [ChatMessage, number][] = [];
// 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,
);
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++) {
// Prune line-by-line from the top
const message = longerThanOneThird[i];
const content = renderChatMessage(message);
const deltaNeeded = totalTokens - contextLength;
const delta = Math.min(deltaNeeded, distanceFromThird[i]);
message.content = pruneStringFromTop(
modelName,
countTokens(message.content, modelName) - delta,
content,
);
totalTokens -= delta;
}
// 1. Replace beyond last 5 messages with summary
let i = 0;
while (totalTokens > contextLength && i < chatHistory.length - 5) {
if (chatHistory[i].role !== "assistant") {
i++;
continue;
}
const message = chatHistory[i];
totalTokens -= countTokens(message.content, modelName);
totalTokens += countTokens(summarize(message), modelName);
message.content = summarize(message);
i++;
}
// 2. Remove entire messages until the last 5
while (chatHistory.length > 5 && totalTokens > contextLength) {
const message = chatHistory.shift()!;
totalTokens -= countTokens(message.content, modelName);
}
// 3. Truncate message in the last 5, except last 1
i = 0;
while (
totalTokens > contextLength &&
chatHistory.length > 0 &&
i < chatHistory.length - 1
) {
const message = chatHistory[i];
totalTokens -= countTokens(message.content, modelName);
totalTokens += countTokens(summarize(message), modelName);
message.content = summarize(message);
i++;
}
// 4. Remove entire messages in the last 5, except last 1
while (totalTokens > contextLength && chatHistory.length > 1) {
// If tool call/response detected prune both (can't have response with no call)
// TODO prune lines from tool response before pruning both messages
if (
chatHistory.length > 2 &&
messageHasToolCalls(chatHistory[0]) &&
chatHistory[1].role === "tool"
) {
const firstMessage = chatHistory.shift()!;
const secondMessage = chatHistory.shift()!;
totalTokens -= countTokens(firstMessage.content, modelName);
totalTokens -= countTokens(secondMessage.content, modelName);
} else {
const message = chatHistory.shift()!;
totalTokens -= countTokens(message.content, modelName);
}
}
// 5. Truncate last message
if (totalTokens > contextLength && chatHistory.length > 0) {
const message = chatHistory[0];
message.content = pruneRawPromptFromTop(
modelName,
contextLength,
renderChatMessage(message),
tokensForCompletion,
);
totalTokens = contextLength;
}
// put system message back if applicable
if (
chatHistory.length > 1 &&
chatHistory[chatHistory.length - 2].role === "system"
) {
const movedSystemMessage = chatHistory.splice(-2, 1)[0];
chatHistory.unshift(movedSystemMessage);
}
return chatHistory;
}
/*
Goal: reconcile chat messages with available context length
Guidelines:
- Always keep last user message, system message, and tools
- Never allow tool output without the corresponding tool call
- Remove older messages first
*/
function compileChatMessages({
modelName,
msgs,
contextLength,
maxTokens,
supportsImages,
tools,
}: {
modelName: string;
msgs: ChatMessage[];
contextLength: number;
maxTokens: number;
supportsImages: boolean;
tools?: Tool[];
}): ChatMessage[] {
let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m }));
msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg));
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
// If images not supported, convert MessagePart[] to string
if (!supportsImages) {
for (const msg of msgsCopy) {
@ -392,15 +329,118 @@ function compileChatMessages({
}
}
const history = pruneChatHistory(
modelName,
msgsCopy,
contextLength,
maxTokens + TOKEN_BUFFER_FOR_SAFETY,
);
// Extract system message
const systemMsg = msgsCopy.find((msg) => msg.role === "system");
msgsCopy = msgsCopy.filter((msg) => msg.role !== "system");
const flattenedHistory = flattenMessages(history);
// Remove any empty messages or non-user/tool trailing messages
msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg));
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
while (msgsCopy.length > 1) {
if (isUserOrToolMsg(msgsCopy.at(-1))) {
break;
}
msgsCopy.pop();
}
const lastUserOrToolMsg = msgsCopy.pop();
if (!lastUserOrToolMsg || !isUserOrToolMsg(lastUserOrToolMsg)) {
throw new Error("Error parsing chat history: no user/tool message found"); // should never happen
}
let lastToolCallsMsg: ChatMessage | undefined = undefined;
if (lastUserOrToolMsg.role === "tool") {
lastToolCallsMsg = msgsCopy.pop();
if (!messageHasToolCallId(lastToolCallsMsg, lastUserOrToolMsg.toolCallId)) {
throw new Error(
`Error parsing chat history: tool call found to match tool output for id ${lastUserOrToolMsg.toolCallId}`,
);
}
}
let lastMessagesTokens = countChatMessageTokens(modelName, lastUserOrToolMsg);
if (lastToolCallsMsg) {
lastMessagesTokens += countChatMessageTokens(modelName, lastToolCallsMsg);
}
// System message
let systemMsgTokens = 0;
if (systemMsg) {
systemMsgTokens = countChatMessageTokens(modelName, systemMsg);
}
// Tools
let toolTokens = 0;
if (tools) {
toolTokens = countToolsTokens(tools, modelName);
}
const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength);
const minOutputTokens = getMinResponseTokens(maxTokens);
let inputTokensAvailable = contextLength;
// Leave space for output/safety
inputTokensAvailable -= countingSafetyBuffer;
inputTokensAvailable -= minOutputTokens;
// Non-negotiable messages
inputTokensAvailable -= toolTokens;
inputTokensAvailable -= systemMsgTokens;
inputTokensAvailable -= lastMessagesTokens;
// Make sure there's enough context for the non-excludable items
if (inputTokensAvailable < 0) {
throw new Error(
`Not enough context available to include the system message, last user message, and tools.
There must be at least ${minOutputTokens} tokens remaining for output.
Request had the following token counts:
- contextLength: ${contextLength}
- counting safety buffer: ${countingSafetyBuffer}
- tools: ~${toolTokens}
- system message: ~${systemMsgTokens}
- last user or tool + tool call message tokens: ~${lastMessagesTokens}
- max output tokens: ${maxTokens}`,
);
}
// Now remove messages till we're under the limit
let currentTotal = 0;
const historyWithTokens = msgsCopy.map((message) => {
const tokens = countChatMessageTokens(modelName, message);
currentTotal += tokens;
return {
...message,
tokens,
};
});
while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) {
const message = historyWithTokens.shift()!;
currentTotal -= message.tokens;
// At this point make sure no latent tool response without corresponding call
while (historyWithTokens[0]?.role === "tool") {
const message = historyWithTokens.shift()!;
currentTotal -= message.tokens;
}
}
// Now reassemble
const reassembled: ChatMessage[] = [];
if (systemMsg) {
reassembled.push(systemMsg);
}
reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest));
if (lastToolCallsMsg) {
reassembled.push(lastToolCallsMsg);
}
reassembled.push(lastUserOrToolMsg);
// Flatten the messages (combines adjacent similar messages)
const flattenedHistory = flattenMessages(reassembled);
return flattenedHistory;
}
@ -408,7 +448,6 @@ export {
compileChatMessages,
countTokens,
countTokensAsync,
flattenMessages,
pruneLinesFromBottom,
pruneLinesFromTop,
pruneRawPromptFromTop,

View file

@ -40,7 +40,6 @@ import {
modelSupportsImages,
} from "./autodetect.js";
import {
CONTEXT_LENGTH_FOR_MODEL,
DEFAULT_ARGS,
DEFAULT_CONTEXT_LENGTH,
DEFAULT_MAX_BATCH_SIZE,
@ -281,28 +280,6 @@ export abstract class BaseLLM implements ILLM {
return Promise.resolve([]);
}
private _compileChatMessages(
options: CompletionOptions,
messages: ChatMessage[],
) {
let contextLength = this.contextLength;
if (
options.model !== this.model &&
options.model in CONTEXT_LENGTH_FOR_MODEL
) {
contextLength =
CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH;
}
return compileChatMessages({
modelName: options.model,
msgs: messages,
contextLength,
maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS,
supportsImages: this.supportsImages(),
});
}
private _templatePromptLikeMessages(prompt: string): string {
if (!this.templateMessages) {
return prompt;
@ -879,7 +856,14 @@ export abstract class BaseLLM implements ILLM {
completionOptions = this._modifyCompletionOptions(completionOptions);
const messages = this._compileChatMessages(completionOptions, _messages);
const messages = compileChatMessages({
modelName: completionOptions.model,
msgs: _messages,
contextLength: this.contextLength,
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
supportsImages: this.supportsImages(),
tools: options.tools,
});
const prompt = this.templateMessages
? this.templateMessages(messages)

View file

@ -102,7 +102,12 @@ class OpenAI extends BaseLLM {
}
protected supportsPrediction(model: string): boolean {
const SUPPORTED_MODELS = ["gpt-4o-mini", "gpt-4o", "mistral-large"];
const SUPPORTED_MODELS = [
"gpt-4o-mini",
"gpt-4o",
"mistral-large",
"Fast-Apply",
];
return SUPPORTED_MODELS.some((m) => model.includes(m));
}

View file

@ -11,6 +11,10 @@ export class Relace extends OpenAI {
};
protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = ["*"];
protected supportsPrediction(model: string): boolean {
return true;
}
getConfigurationStatus() {
if (!this.apiKey) {
return LLMConfigurationStatuses.MISSING_API_KEY;

View file

@ -1,5 +1,5 @@
import { ChatMessage } from "..";
import { flattenMessages } from "./countTokens";
import { flattenMessages } from "./messages";
describe("flattenMessages", () => {
it("should return an empty array when given an empty array", () => {

View file

@ -49,6 +49,31 @@ export function addSpaceToAnyEmptyMessages(
});
}
export function isUserOrToolMsg(msg: ChatMessage | undefined): boolean {
if (!msg) {
return false;
}
return msg.role === "user" || msg.role === "tool";
}
export function isToolMessageForId(
msg: ChatMessage | undefined,
toolCallId: string,
): boolean {
return !!msg && msg.role === "tool" && msg.toolCallId === toolCallId;
}
export function messageHasToolCallId(
msg: ChatMessage | undefined,
toolCallId: string,
): boolean {
return (
!!msg &&
msg.role === "assistant" &&
!!msg.toolCalls?.find((call) => call.id === toolCallId)
);
}
export function chatMessageIsEmpty(message: ChatMessage): boolean {
switch (message.role) {
case "system":

View file

@ -51,7 +51,7 @@ export function toChatMessage(
type: toolCall.type!,
function: {
name: toolCall.function?.name!,
arguments: toolCall.function?.arguments!,
arguments: toolCall.function?.arguments! || "{}",
},
}));
}

View file

@ -1,4 +1,4 @@
import { RuleWithSource, UserChatMessage } from "../..";
import { RuleWithSource, ToolResultChatMessage, UserChatMessage } from "../..";
import { renderChatMessage } from "../../util/messageContent";
import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
import { isRuleActive } from "./isRuleActive";
@ -10,7 +10,7 @@ export const getSystemMessageWithRules = ({
currentModel,
}: {
baseSystemMessage?: string;
userMessage: UserChatMessage | undefined;
userMessage: UserChatMessage | ToolResultChatMessage | undefined;
rules: RuleWithSource[];
currentModel: string;
}) => {

View file

@ -31,6 +31,13 @@ export const PROVIDER_TOOL_SUPPORT: Record<
return true;
}
},
azure: (model) => {
if (
model.toLowerCase().startsWith("gpt-4") ||
model.toLowerCase().startsWith("o3")
) return true;
return false;
},
openai: (model) => {
// https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling
if (

View file

@ -106,7 +106,7 @@
"typescript": "^5.6.3"
},
"engines": {
"node": ">=20.11.0"
"node": ">=20.19.0"
}
},
"../../../../../documents/code/continuedev/continue/packages/config-yaml": {

View file

@ -112,6 +112,6 @@
},
"engine-strict": true,
"engines": {
"node": ">=20.11.0"
"node": ">=20.19.0"
}
}

View file

@ -101,7 +101,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
query: string;
fullInput: string;
selectedCode: RangeInFile[];
selectedModelTitle: string;
},
ContextItemWithId[],
];
@ -156,7 +155,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
];
"chatDescriber/describe": [
{
selectedModelTitle: string;
text: string;
},
string | undefined,
@ -203,15 +201,12 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }];
"tools/call": [
{ toolCall: ToolCall; selectedModelTitle: string },
{ contextItems: ContextItem[] },
{ toolCall: ToolCall },
{ contextItems: ContextItem[]; errorMessage?: string },
];
"clipboardCache/add": [{ content: string }, void];
"controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void];
isItemTooBig: [
{ item: ContextItemWithId; selectedModelTitle: string | undefined },
boolean,
];
isItemTooBig: [{ item: ContextItemWithId }, boolean];
didChangeControlPlaneSessionInfo: [
{ sessionInfo: ControlPlaneSessionInfo | undefined },
void,

View file

@ -99,6 +99,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
ControlPlaneSessionInfo | undefined,
];
logoutOfControlPlane: [undefined, void];
closeSidebar: [undefined, void];
};
export type ToWebviewOrCoreFromIdeProtocol = {

View file

@ -17,3 +17,5 @@ export enum BuiltInToolNames {
}
export const BUILT_IN_GROUP_NAME = "Built-In";
export const CLIENT_TOOLS = [BuiltInToolNames.EditExistingFile];

View file

@ -130,40 +130,72 @@ async function callToolFromUri(
}
}
// Handles calls for core/non-client tools
// Returns an error context item if the tool call fails
// Note: Edit tool is handled on client
export async function callTool(
tool: Tool,
args: any,
callArgs: string,
extras: ToolExtras,
): Promise<ContextItem[]> {
): Promise<{
contextItems: ContextItem[];
errorMessage: string | undefined;
}> {
const args = JSON.parse(callArgs || "{}");
const uri = tool.uri ?? tool.function.name;
switch (uri) {
case BuiltInToolNames.ReadFile:
return await readFileImpl(args, extras);
// Note: Custom GUI handling for edit
case BuiltInToolNames.CreateNewFile:
return await createNewFileImpl(args, extras);
case BuiltInToolNames.GrepSearch:
return await grepSearchImpl(args, extras);
case BuiltInToolNames.FileGlobSearch:
return await fileGlobSearchImpl(args, extras);
case BuiltInToolNames.RunTerminalCommand:
return await runTerminalCommandImpl(args, extras);
case BuiltInToolNames.SearchWeb:
return await searchWebImpl(args, extras);
case BuiltInToolNames.ViewDiff:
return await viewDiffImpl(args, extras);
case BuiltInToolNames.LSTool:
return await lsToolImpl(args, extras);
case BuiltInToolNames.ReadCurrentlyOpenFile:
return await readCurrentlyOpenFileImpl(args, extras);
case BuiltInToolNames.CreateRuleBlock:
return await createRuleBlockImpl(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);
try {
let contextItems: ContextItem[] = [];
switch (uri) {
case BuiltInToolNames.ReadFile:
contextItems = await readFileImpl(args, extras);
break;
case BuiltInToolNames.CreateNewFile:
contextItems = await createNewFileImpl(args, extras);
break;
case BuiltInToolNames.GrepSearch:
contextItems = await grepSearchImpl(args, extras);
break;
case BuiltInToolNames.FileGlobSearch:
contextItems = await fileGlobSearchImpl(args, extras);
break;
case BuiltInToolNames.RunTerminalCommand:
contextItems = await runTerminalCommandImpl(args, extras);
break;
case BuiltInToolNames.SearchWeb:
contextItems = await searchWebImpl(args, extras);
break;
case BuiltInToolNames.ViewDiff:
contextItems = await viewDiffImpl(args, extras);
break;
case BuiltInToolNames.LSTool:
contextItems = await lsToolImpl(args, extras);
break;
case BuiltInToolNames.ReadCurrentlyOpenFile:
contextItems = await readCurrentlyOpenFileImpl(args, extras);
break;
case BuiltInToolNames.CreateRuleBlock:
contextItems = await createRuleBlockImpl(args, extras);
break;
default:
contextItems = await callToolFromUri(uri, args, extras);
}
if (tool.faviconUrl) {
contextItems.forEach((item) => {
item.icon = tool.faviconUrl;
});
}
return {
contextItems,
errorMessage: undefined,
};
} catch (e) {
let errorMessage = `${e}`;
if (e instanceof Error) {
errorMessage = e.message;
}
return {
contextItems: [],
errorMessage,
};
}
}

View file

@ -13,6 +13,6 @@
},
"engine-strict": true,
"engines": {
"node": ">=20.11.0"
"node": ">=20.19.0"
}
}

View file

@ -12,3 +12,30 @@ In Continue, autocomplete models are used to display inline [Autocomplete](../..
## Recommended Autocomplete models
Visit the [Autocomplete Deep Dive](../deep-dives/autocomplete.mdx) for recommended models and more details.
## Prompt templating
You can customize the prompt template used when autocomplete happens by setting the `promptTemplates.autocomplete` property in your model configuration. Continue uses [Handlebars syntax](https://handlebarsjs.com/guide/) for templating.
Available variables for the apply template:
- `{{{prefix}}}` - the code before your cursor
- `{{{suffix}}}` - the code after your cursor
- `{{{filename}}}` - the name of the file your cursor currently is
- `{{{reponame}}}` - the name of the folder where the codebase is
- `{{{language}}}` - the name of the programming language in full (ex. Typescript)
Example:
```yaml
models:
- name: My Custom Autocomplete Template
provider: ollama
model: qwen2.5-coder:1.5b
promptTemplates:
autocomplete: |
`
globalThis.importantFunc = importantFunc
<|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>
`
```

View file

@ -32,7 +32,7 @@ Assistants can either explicitly define blocks - see [Properties](#properties) b
### Using Blocks
Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization.
Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from https://hub.continue.dev.
Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type.
@ -167,7 +167,7 @@ The `models` section defines the language models used in your configuration. Mod
- `apiBase`: Can be used to override the default API base that is specified per model
- `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used.
- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`.
- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are [`edit`](./customize/model-roles/edit.mdx#prompt-templating) and [`apply`](./customize/model-roles/apply.mdx#prompt-templating).
- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [`apply`](./customize/model-roles/apply.mdx#prompt-templating) and [autocomplete](./customize/model-roles/autocomplete.md#prompt-templating)
- `chatOptions`: If the model includes role `chat`, these settings apply for Chat and Agent mode:
- `baseSystemMessage`: Can be used to override the default system prompt.
- `embedOptions`: If the model includes role `embed`, these settings apply for embeddings:

48
docs/package-lock.json generated
View file

@ -23,7 +23,7 @@
"nodemon": "^3.1.4"
},
"engines": {
"node": ">=20.11.0"
"node": ">=20.19.0"
}
},
"node_modules/@algolia/autocomplete-core": {
@ -566,23 +566,25 @@
}
},
"node_modules/@babel/helpers": {
"version": "7.26.0",
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.26.0.tgz",
"integrity": "sha512-tbhNuIxNcVb21pInl3ZSjksLCvgdZy9KwJ8brv993QtIVKJBBkYXz4q4ZbAv31GdnC+R90np23L5FbEBlthAEw==",
"version": "7.27.0",
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.27.0.tgz",
"integrity": "sha512-U5eyP/CTFPuNE3qk+WZMxFkp/4zUzdceQlfzf7DdGdhp+Fezd7HD+i8Y24ZuTMKX3wQBld449jijbGq6OdGNQg==",
"license": "MIT",
"dependencies": {
"@babel/template": "^7.25.9",
"@babel/types": "^7.26.0"
"@babel/template": "^7.27.0",
"@babel/types": "^7.27.0"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
"version": "7.26.3",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.3.tgz",
"integrity": "sha512-WJ/CvmY8Mea8iDXo6a7RK2wbmJITT5fN3BEkRuFlxVyNx8jOKIIhmC4fSkTcPcf8JyavbBwIe6OpiCOBXt/IcA==",
"version": "7.27.0",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.27.0.tgz",
"integrity": "sha512-iaepho73/2Pz7w2eMS0Q5f83+0RKI7i4xmiYeBmDzfRVbQtTOG7Ts0S4HzJVsTMGI9keU8rNfuZr8DKfSt7Yyg==",
"license": "MIT",
"dependencies": {
"@babel/types": "^7.26.3"
"@babel/types": "^7.27.0"
},
"bin": {
"parser": "bin/babel-parser.js"
@ -1781,13 +1783,14 @@
}
},
"node_modules/@babel/template": {
"version": "7.25.9",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.25.9.tgz",
"integrity": "sha512-9DGttpmPvIxBb/2uwpVo3dqJ+O6RooAFOS+lB+xDqoE2PVCE8nfoHMdZLpfCQRLwvohzXISPZcgxt80xLfsuwg==",
"version": "7.27.0",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.0.tgz",
"integrity": "sha512-2ncevenBqXI6qRMukPlXwHKHchC7RyMuu4xv5JBXRfOGVcTy1mXCD12qrp7Jsoxll1EV3+9sE4GugBVRjT2jFA==",
"license": "MIT",
"dependencies": {
"@babel/code-frame": "^7.25.9",
"@babel/parser": "^7.25.9",
"@babel/types": "^7.25.9"
"@babel/code-frame": "^7.26.2",
"@babel/parser": "^7.27.0",
"@babel/types": "^7.27.0"
},
"engines": {
"node": ">=6.9.0"
@ -1811,9 +1814,10 @@
}
},
"node_modules/@babel/types": {
"version": "7.26.3",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.3.tgz",
"integrity": "sha512-vN5p+1kl59GVKMvTHt55NzzmYVxprfJD+ql7U9NFIfKCBkYE55LYtS+WtPlaYOyzydrKI8Nezd+aZextrd+FMA==",
"version": "7.27.0",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.27.0.tgz",
"integrity": "sha512-H45s8fVLYjbhFH62dIJ3WtmJ6RSPt/3DRO0ZcT2SUiYiQyz3BLVb9ADEnLl91m74aQPS3AzzeajZHYOalWe3bg==",
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.25.9",
"@babel/helper-validator-identifier": "^7.25.9"
@ -9521,9 +9525,9 @@
}
},
"node_modules/http-proxy-middleware": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.7.tgz",
"integrity": "sha512-fgVY8AV7qU7z/MmXJ/rxwbrtQH4jBQ9m7kp3llF0liB7glmFeVZFBepQb32T3y8n8k2+AEYuMPCpinYW+/CuRA==",
"version": "2.0.9",
"resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.9.tgz",
"integrity": "sha512-c1IyJYLYppU574+YI7R4QyX2ystMtVXZwIdzazUIPIJsHuWNd+mho2j+bKoHftndicGj9yh+xjd+l0yj7VeT1Q==",
"license": "MIT",
"dependencies": {
"@types/http-proxy": "^1.17.8",

View file

@ -44,6 +44,6 @@
},
"engine-strict": true,
"engines": {
"node": ">=20.11.0"
"node": ">=20.19.0"
}
}

View file

@ -1,6 +1,6 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="IDE Logs" type="ShConfigurationType">
<option name="SCRIPT_TEXT" value="mkdir -p ./extensions/.continue-debug/logs &amp;&amp; touch ./extensions/.continue-debug/logs/prompt.log &amp;&amp; tail -f ./extensions/intellij/build/idea-sandbox/system/log/idea.log" />
<option name="SCRIPT_TEXT" value="mkdir -p ./extensions/intellij/build/idea-sandbox/system/log &amp;&amp; touch ./extensions/intellij/build/idea-sandbox/system/log/idea.log &amp;&amp; tail -f ./extensions/intellij/build/idea-sandbox/system/log/idea.log" />
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
<option name="SCRIPT_PATH" value="mkdir -p ./extensions/.continue-debug/logs &amp;&amp; touch ./extensions/.continue-debug/logs/prompt.log &amp;&amp; tail -f ./extensions/.continue-debug/logs/prompt.log" />
<option name="SCRIPT_OPTIONS" value="" />

View file

@ -4,6 +4,16 @@
<env name="CONTINUE_DEVELOPMENT" value="true" />
<env name="CONTINUE_GLOBAL_DIR" value="$PROJECT_DIR$/extensions/.continue-debug" />
</envs>
<method v="2" />
<method v="2">
<option name="NpmBeforeRunTask" enabled="true">
<package-json value="$PROJECT_DIR$/binary/package.json" />
<command value="run" />
<scripts>
<script value="rebuild" />
</scripts>
<node-interpreter value="project" />
<envs />
</option>
</method>
</configuration>
</component>

View file

@ -52,7 +52,7 @@ notes below).
### Node.js Requirements
This project requires Node.js version 20.11.0 (LTS) or higher. You have two options for installation:
This project requires Node.js version 20.19.0 (LTS) or higher. You have two options for installation:
1. Download and install directly from [nodejs.org](https://nodejs.org/en/download).
2. If you're using NVM (Node Version Manager), set the correct Node.js version for this project by running `nvm use` in

View file

@ -3,12 +3,13 @@ pluginGroup=com.github.continuedev.continueintellijextension
pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion=1.0.13
pluginVersion=1.0.14
# 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
platformType=IC
platformVersion=2022.3.3
#org.gradle.java.home=/opt/homebrew/opt/openjdk@17
#platformVersion = LATEST-EAP-SNAPSHOT
# Plugin Dependencies -> https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html
# Example: platformPlugins = com.intellij.java, com.jetbrains.php:203.4449.22

View file

@ -5,3 +5,4 @@ networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#org.gradle.java.home=/opt/homebrew/opt/openjdk@17

View file

@ -126,3 +126,16 @@ class OpenConfigAction : AnAction() {
continuePluginService.sendToWebview("navigateTo", params)
}
}
class OpenLogsAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val logFile = java.io.File(System.getProperty("user.home") + "/.continue/logs/core.log")
if (logFile.exists()) {
val virtualFile = com.intellij.openapi.vfs.LocalFileSystem.getInstance().findFileByIoFile(logFile)
if (virtualFile != null) {
com.intellij.openapi.fileEditor.FileEditorManager.getInstance(project).openFile(virtualFile, true)
}
}
}
}

View file

@ -1,4 +1,5 @@
package com.github.continuedev.continueintellijextension.activities
import IntelliJIDE
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.github.continuedev.continueintellijextension.auth.AuthListener
@ -153,11 +154,13 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
val connection = ApplicationManager.getApplication().messageBus.connect()
connection.subscribe(SettingsListener.TOPIC, object : SettingsListener {
override fun settingsUpdated(settings: ContinueExtensionSettings.ContinueState) {
continuePluginService.coreMessenger?.request("config/ideSettingsUpdate", mapOf(
"remoteConfigServerUrl" to settings.remoteConfigServerUrl,
"remoteConfigSyncPeriod" to settings.remoteConfigSyncPeriod,
"userToken" to settings.userToken,
), null) { _ -> }
continuePluginService.coreMessenger?.request(
"config/ideSettingsUpdate", mapOf(
"remoteConfigServerUrl" to settings.remoteConfigServerUrl,
"remoteConfigSyncPeriod" to settings.remoteConfigSyncPeriod,
"userToken" to settings.userToken,
), null
) { _ -> }
}
})
@ -205,6 +208,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
continuePluginService.coreMessenger?.request("files/closed", data, null) { _ -> }
}
}
override fun fileOpened(source: FileEditorManager, file: VirtualFile) {
file.toUriOrNull()?.let { uri ->
val data = mapOf("uris" to listOf(uri))
@ -214,7 +218,6 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
})
// Listen for theme changes
connection.subscribe(LafManagerListener.TOPIC, LafManagerListener {
val colors = GetTheme().getTheme();

View file

@ -3,12 +3,17 @@ package com.github.continuedev.continueintellijextension.auth
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBTextField
import com.intellij.ui.HyperlinkLabel
import javax.swing.JComponent
import javax.swing.JPanel
import java.awt.BorderLayout
import javax.swing.BoxLayout
class ContinueAuthDialog(private val useOnboarding: Boolean, private val onTokenEntered: (String) -> Unit) :
DialogWrapper(true) {
class ContinueAuthDialog(
private val useOnboarding: Boolean,
private val authUrl: String? = null,
private val onTokenEntered: (String) -> Unit,
) : DialogWrapper(true) {
private val tokenField = JBTextField()
init {
@ -18,9 +23,22 @@ class ContinueAuthDialog(private val useOnboarding: Boolean, private val onToken
override fun createCenterPanel(): JComponent {
val panel = JPanel(BorderLayout())
val topPanel = JPanel()
topPanel.layout = BoxLayout(topPanel, BoxLayout.Y_AXIS)
val message =
if (useOnboarding) "After onboarding you will be shown an authentication token. Please enter it here:" else "Please enter your Continue authentication token:"
panel.add(JBLabel(message), BorderLayout.NORTH)
topPanel.add(JBLabel(message))
topPanel.add(javax.swing.Box.createVerticalStrut(10))
if (authUrl != null) {
val linkLabel = HyperlinkLabel("Open authentication page")
linkLabel.setHyperlinkTarget(authUrl)
topPanel.add(linkLabel)
topPanel.add(javax.swing.Box.createVerticalStrut(10))
}
panel.add(topPanel, BorderLayout.NORTH)
panel.add(tokenField, BorderLayout.CENTER)
return panel
}

View file

@ -53,11 +53,11 @@ class ContinueAuthService {
fun startAuthFlow(project: Project, useOnboarding: Boolean) {
// Open login page
openSignInPage(project, useOnboarding)
val url = openSignInPage(project, useOnboarding)
// Open a dialog where the user should paste their sign-in token
ApplicationManager.getApplication().invokeLater {
val dialog = ContinueAuthDialog(useOnboarding) { token ->
val dialog = ContinueAuthDialog(useOnboarding, url) { token ->
// Store the token
updateRefreshToken(token)
}
@ -144,18 +144,31 @@ class ContinueAuthService {
}
private fun openSignInPage(project: Project, useOnboarding: Boolean) {
private fun openSignInPage(project: Project, useOnboarding: Boolean): String? {
var authUrl: String? = null
val coreMessenger = project.service<ContinuePluginService>().coreMessenger
// Use a blocking approach to get the URL
val latch = java.util.concurrent.CountDownLatch(1)
coreMessenger?.request(
"auth/getAuthUrl", mapOf(
"useOnboarding" to useOnboarding
), null
) { response ->
val authUrl = ((response as? Map<*, *>)?.get("content") as? Map<*, *>)?.get("url") as? String
if (authUrl != null) {
Desktop.browse(java.net.URI(authUrl))
}
authUrl = ((response as? Map<*, *>)?.get("content") as? Map<*, *>)?.get("url") as? String
latch.countDown()
}
// Wait for the response with a reasonable timeout
latch.await(5, java.util.concurrent.TimeUnit.SECONDS)
// Still open the URL in the browser (keeping existing behavior)
if (authUrl != null) {
Desktop.browse(java.net.URI(authUrl))
}
return authUrl
}
private fun retrieveSecret(key: String): String? {

View file

@ -56,27 +56,34 @@ class CoreMessengerManager(
}
private fun setupCoreMessenger(continueCorePath: String) {
coreMessenger = CoreMessenger(project, continueCorePath, ideProtocolClient, coroutineScope)
try {
coreMessenger = CoreMessenger(project, continueCorePath, ideProtocolClient, coroutineScope)
coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
val responseObject = response as Map<*, *>
val responseContent = responseObject["content"] as Map<*, *>
val result = responseContent["result"] as Map<*, *>
val config = result["config"] as Map<String, Any>
coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
val responseObject = response as Map<*, *>
val responseContent = responseObject["content"] as Map<*, *>
val result = responseContent["result"] as Map<*, *>
val config = result["config"] as Map<String, Any>
val allowAnonymousTelemetry = config?.get("allowAnonymousTelemetry") as? Boolean
val telemetryService = service<TelemetryService>()
if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) {
telemetryService.setup(getMachineUniqueID())
val allowAnonymousTelemetry = config?.get("allowAnonymousTelemetry") as? Boolean
val telemetryService = service<TelemetryService>()
if (allowAnonymousTelemetry == true || allowAnonymousTelemetry == null) {
telemetryService.setup(getMachineUniqueID())
}
}
}
// On exit, use exponential backoff to create another CoreMessenger
coreMessenger?.onDidExit {
lastBackoffInterval *= 2
println("CoreMessenger exited, retrying in $lastBackoffInterval seconds")
Thread.sleep((lastBackoffInterval * 1000).toLong())
setupCoreMessenger(continueCorePath)
// On exit, use exponential backoff to create another CoreMessenger
coreMessenger?.onDidExit {
lastBackoffInterval *= 2
println("CoreMessenger exited, retrying in $lastBackoffInterval seconds")
Thread.sleep((lastBackoffInterval * 1000).toLong())
setupCoreMessenger(continueCorePath)
}
} catch (err: Throwable) {
val telemetryService = service<TelemetryService>()
telemetryService.capture("jetbrains_core_start_error", mapOf("error" to err))
err.printStackTrace()
}
}
}

View file

@ -24,6 +24,7 @@ import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.wm.ToolWindowManager
import kotlinx.coroutines.*
import java.awt.Toolkit
import java.awt.datatransfer.StringSelection
@ -334,6 +335,14 @@ class IdeProtocolClient(
respond(result)
}
"closeSidebar" -> {
ApplicationManager.getApplication().invokeLater {
val toolWindowManager = ToolWindowManager.getInstance(project)
val toolWindow = toolWindowManager.getToolWindow("Continue")
toolWindow?.hide()
}
}
"getSearchResults" -> {
val params = Gson().fromJson(
dataElement.toString(),
@ -430,24 +439,28 @@ class IdeProtocolClient(
)
val filepath = params.filepath
continuePluginService.sendToWebview("updateApplyState", mapOf(
"streamId" to params.streamId,
"status" to "streaming",
"fileContent" to params.text,
"toolCallId" to params.toolCallId,
"filepath" to filepath
))
fun closeStream () {
continuePluginService.sendToWebview("updateApplyState", mapOf(
"numDiffs" to 0,
continuePluginService.sendToWebview(
"updateApplyState", mapOf(
"streamId" to params.streamId,
"status" to "closed",
"status" to "streaming",
"fileContent" to params.text,
"toolCallId" to params.toolCallId,
"filepath" to filepath
))
)
)
fun closeStream() {
continuePluginService.sendToWebview(
"updateApplyState", mapOf(
"numDiffs" to 0,
"streamId" to params.streamId,
"status" to "closed",
"fileContent" to params.text,
"toolCallId" to params.toolCallId,
"filepath" to filepath
)
)
}
var editor: Editor? = null;
@ -493,7 +506,7 @@ class IdeProtocolClient(
val selectedModels = config["selectedModelByRole"] as? Map<*, *>
var applyCodeBlockModel = selectedModels?.get("apply") as? Map<*, *>
// If "apply" role model is not found, try "chat" role
if (applyCodeBlockModel == null) {
applyCodeBlockModel = selectedModels?.get("chat") as? Map<*, *>
@ -555,8 +568,8 @@ class IdeProtocolClient(
editor,
rif?.range?.start?.line ?: 0,
rif?.range?.end?.line ?: (editor.document.lineCount - 1),
{},
{},
{},
{},
params.streamId,
params.toolCallId
)

View file

@ -133,8 +133,9 @@ fun openInlineEdit(project: Project?, editor: Editor) {
val content = (response as Map<String, Any>)["content"] as Map<String, Any>
val result = content["result"] as Map<String, Any>
val config = result["config"] as Map<String, Any>
val models = config["models"] as List<Map<String, Any>>
modelTitles.addAll(models.map { it["title"] as String })
val models = config["modelsByRole"] as Map<String, Any>
val editModels = models["edit"] as List<Map<String, Any>>
modelTitles.addAll(editModels.map { it["title"] as String })
}
// This is a hacky way to not complicate getting model titles with coroutines

View file

@ -13,12 +13,16 @@ import com.intellij.openapi.project.DumbAware
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlin.properties.Delegates
@Service(Service.Level.PROJECT)
class ContinuePluginService : Disposable, DumbAware {
private val coroutineScope = CoroutineScope(Dispatchers.Main)
var continuePluginWindow: ContinuePluginToolWindowFactory.ContinuePluginWindow? = null
var ideProtocolClient: IdeProtocolClient? = null
var listener: (() -> Unit)? = null
var ideProtocolClient: IdeProtocolClient? by Delegates.observable(null) { _, _, _ ->
synchronized(this) { listener?.also { listener = null }?.invoke() }
}
var coreMessengerManager: CoreMessengerManager? = null
val coreMessenger: CoreMessenger?
get() = coreMessengerManager?.coreMessenger
@ -42,6 +46,25 @@ class ContinuePluginService : Disposable, DumbAware {
continuePluginWindow?.browser?.sendToWebview(messageType, data, messageId)
}
/**
* Add a listener for protocolClient initialization.
* Currently, only one needs to be processed. If there are more than one,
* we can use an array to add listeners to ensure that the message is processed.
*/
fun onProtocolClientInitialized(listener: () -> Unit) {
if (ideProtocolClient == null) {
synchronized(this) {
if (ideProtocolClient == null) {
this.listener = listener
} else {
listener()
}
}
} else {
listener()
}
}
fun updateLastFileSaveTimestamp() {
ideProtocolClient?.updateLastFileSaveTimestamp()
}

View file

@ -1,7 +1,6 @@
package com.github.continuedev.continueintellijextension.toolWindow
import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable
import com.github.continuedev.continueintellijextension.constants.MessageTypes
import com.github.continuedev.continueintellijextension.constants.MessageTypes.Companion.PASS_THROUGH_TO_CORE
import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
@ -10,11 +9,11 @@ import com.github.continuedev.continueintellijextension.utils.uuid
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.ui.jcef.*
import com.intellij.ui.jcef.JBCefClient.Properties
import com.intellij.util.application
import org.cef.CefApp
import org.cef.browser.CefBrowser
import org.cef.handler.CefLoadHandlerAdapter
@ -30,8 +29,10 @@ class ContinueBrowser(val project: Project, url: String) {
val browser: JBCefBrowser
val continuePluginService: ContinuePluginService = project.getService(ContinuePluginService::class.java)
init {
val isOSREnabled = ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR
val isOSREnabled = application.getService(ContinueExtensionSettings::class.java).continueState.enableOSR
this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(isOSREnabled).build().apply {
// To avoid using System.setProperty to affect other plugins,
@ -42,7 +43,6 @@ class ContinueBrowser(val project: Project, url: String) {
}
registerAppSchemeHandler()
browser.loadURL(url)
Disposer.register(ContinuePluginDisposable.getInstance(project), browser)
// Listen for events sent from browser
@ -55,11 +55,6 @@ class ContinueBrowser(val project: Project, url: String) {
val data = json.get("data")
val messageId = json.get("messageId")?.asString
val continuePluginService = ServiceManager.getService(
project,
ContinuePluginService::class.java
)
val respond = fun(data: Any?) {
sendToWebview(messageType, data, messageId ?: uuid())
}
@ -101,6 +96,13 @@ class ContinueBrowser(val project: Project, url: String) {
}
}, browser.cefBrowser)
// Load the url only after the protocolClient is initialized,
// otherwise some messages will be lost, which are some configurations when the page is loaded.
// Moreover, we should add LoadHandler before loading the url.
continuePluginService.onProtocolClientInitialized {
browser.loadURL(url)
}
}
fun executeJavaScript(browser: CefBrowser?, myJSQueryOpenInBrowser: JBCefJSQuery) {

View file

@ -140,6 +140,14 @@
<override-text place="GoToAction" text="Continue Config"/>
</action>
<action id="continue.openLogs"
class="com.github.continuedev.continueintellijextension.actions.OpenLogsAction"
icon="AllIcons.General.ShowInfos"
text="Open Logs"
description="Open Continue Logs">
<override-text place="GoToAction" text="Open Continue Logs"/>
</action>
<group id="ContinueSidebarActionsGroup">
<reference ref="continue.newContinueSession"/>
<reference ref="continue.viewHistory"/>

View file

@ -3,7 +3,6 @@ node_modules/
out/
.vscode-test/
data/
src/.buildTimestamp.ts
src/client
.continue
@ -26,5 +25,5 @@ e2e/test-continue/*
!e2e/test-continue/config.json
e2e/test-continue-yaml/*
!e2e/test-continue-yaml/config.yaml
config-yaml-schema.json
config-yaml-schema.json
src/.buildTimestamp.ts

View file

@ -93,7 +93,7 @@
"vscode-extension-tester": "^8.10.0"
},
"engines": {
"node": ">=20.11.0",
"node": ">=20.19.0",
"vscode": "^1.70.0"
}
},
@ -199,7 +199,7 @@
"typescript": "^5.6.3"
},
"engines": {
"node": ">=20.11.0"
"node": ">=20.19.0"
}
},
"node_modules/@75lb/deep-merge": {
@ -495,9 +495,10 @@
}
},
"node_modules/@babel/runtime": {
"version": "7.26.0",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.0.tgz",
"integrity": "sha512-FDSOghenHTiToteC/QRlv2q3DhPZ/oOXTBoirfWNx1Cx3TMVcGWQtMMmQcSvb/JjpNeGzx8Pq/b4fKEJuWm1sw==",
"version": "7.27.0",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.27.0.tgz",
"integrity": "sha512-VtPOkrdPHZsKc/clNqyi9WUA8TINkZ4cGk63UUE3u4pmB2k+ZMQRDuIOagv8UVd6j7k0T3+RRIb7beKTebNbcw==",
"license": "MIT",
"dependencies": {
"regenerator-runtime": "^0.14.0"
},

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.24",
"version": "1.1.25",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -24,7 +24,7 @@
"publisher": "Continue",
"engines": {
"vscode": "^1.70.0",
"node": ">=20.11.0"
"node": ">=20.19.0"
},
"engine-strict": true,
"galleryBanner": {

View file

@ -576,7 +576,7 @@ const getCommandsMap: (
const range =
args?.range ?? new vscode.Range(startFromCharZero, endAtCharLast);
editDecorationManager.setDecoration(editor, range);
editDecorationManager.addDecorations(editor, [range]);
const rangeInFileWithContents = getRangeInFileWithContents(true, range);
@ -905,7 +905,7 @@ const getCommandsMap: (
quickPick.items = [
{
label: "$(question) Open help center",
label: "$(gear) Open settings",
},
{
label: "$(comment) Open chat",
@ -960,7 +960,10 @@ const getCommandsMap: (
vscode.commands.executeCommand("continue.focusContinueInput");
} else if (selectedOption === "$(screen-full) Open full screen chat") {
vscode.commands.executeCommand("continue.toggleFullScreen");
} else if (selectedOption === "$(gear) Open settings") {
vscode.commands.executeCommand("continue.navigateTo", "/config");
}
quickPick.dispose();
});
quickPick.show();

View file

@ -2,6 +2,7 @@ import vscode from "vscode";
class EditDecorationManager {
private _lastEditor: vscode.TextEditor | undefined;
private decorationType: vscode.TextEditorDecorationType;
private activeRangesMap: Map<string, vscode.Range> = new Map(); // Store unique active ranges
constructor(context: vscode.ExtensionContext) {
this.decorationType = vscode.window.createTextEditorDecorationType({
@ -23,18 +24,55 @@ class EditDecorationManager {
);
}
setDecoration(editor: vscode.TextEditor, range: vscode.Range) {
if (this._lastEditor) {
this._lastEditor.setDecorations(this.decorationType, []);
// Converts each range to a unique string for storing in the map
private rangeToString(range: vscode.Range): string {
return `(${range.start.line},${range.start.character})-(${range.end.line},${range.end.character})`;
}
// Checks if two ranges are adjacent or overlapping
private rangesCoincide(range1: vscode.Range, range2: vscode.Range): boolean {
return range1.start.isEqual(range2.start)
|| range1.end.isEqual(range2.start)
|| range2.end.isEqual(range1.start)
|| !!range1.intersection(range2);
}
// Merges new range with existing ranges in the map
private mergeNewRange(newRange: vscode.Range): void {
let mergedRange = newRange;
const rangesToPrune: string[] = [];
for (const [key, existingRange] of this.activeRangesMap.entries()) {
if (!this.rangesCoincide(mergedRange, existingRange)) continue;
mergedRange = mergedRange.union(existingRange);
rangesToPrune.push(key);
}
for (const key of rangesToPrune) this.activeRangesMap.delete(key);
this.activeRangesMap.set(this.rangeToString(mergedRange), mergedRange);
}
// Adds a new decoration to the editor and merges it with existing ranges
addDecorations(editor: vscode.TextEditor, ranges: vscode.Range[]): void {
if (this._lastEditor?.document !== editor.document) {
this.clear(); // Clear previous decorations if editor has changed
}
editor.setDecorations(this.decorationType, [range]);
this._lastEditor = editor;
for (const range of ranges) this.mergeNewRange(range);
const activeRanges = Array.from(this.activeRangesMap.values());
if (activeRanges.length === 0) return; // No ranges to highlight
// Update active ranges and apply decorations
editor.setDecorations(this.decorationType, activeRanges);
this.updateInEditMode(true);
}
clear() {
if (this._lastEditor) {
this._lastEditor.setDecorations(this.decorationType, []);
this.activeRangesMap.clear();
this._lastEditor = undefined;
this.updateInEditMode(false);
}

4
gui/package-lock.json generated
View file

@ -97,7 +97,7 @@
"vitest": "^2.1.3"
},
"engines": {
"node": ">=20.11.0"
"node": ">=20.19.0"
}
},
"../core": {
@ -202,7 +202,7 @@
"typescript": "^5.6.3"
},
"engines": {
"node": ">=20.11.0"
"node": ">=20.19.0"
}
},
"../packages/config-yaml": {

View file

@ -106,6 +106,6 @@
},
"engine-strict": true,
"engines": {
"node": ">=20.11.0"
"node": ">=20.19.0"
}
}

View file

@ -39,6 +39,17 @@ export default function AddFileCombobox({
}
}, []);
useEffect(() => {
// update selectedFiles showing only the files that are in codeToEdit
setSelectedFiles(
(prevSelectedFiles) =>
prevSelectedFiles.filter(
(file) =>
codeToEdit.findIndex((code) => code.filepath === file.id) !== -1,
),
);
}, [codeToEdit]);
const filteredFiles =
query === ""
? remainingFiles
@ -55,12 +66,14 @@ export default function AddFileCombobox({
setSelectedFiles(files);
void onSelect(files.map((file) => file.id));
buttonRef.current?.click();
setQuery("");
}}
>
{({ open }) => (
<div className="relative">
<ComboboxButton className="hidden" ref={buttonRef} />
<ComboboxInput
value={query}
ref={inputRef}
onClick={() => {
if (!open) {

View file

@ -50,7 +50,7 @@ export function ApplyActions(props: ApplyActionsProps) {
switch (props.applyState ? props.applyState.status : null) {
case "streaming":
return (
<div className="flex items-center rounded bg-zinc-700 pl-2 pr-1">
<div className="flex select-none items-center rounded bg-zinc-700 pl-2 pr-1">
<span className="text-lightgray inline-flex w-min items-center gap-2 text-center text-xs">
Applying
<Spinner />
@ -59,7 +59,7 @@ export function ApplyActions(props: ApplyActionsProps) {
);
case "done":
return (
<div className="flex items-center rounded bg-zinc-700 px-1.5 sm:gap-1">
<div className="flex select-none items-center rounded bg-zinc-700 px-1.5 sm:gap-1">
<span className="max-xs:hidden text-lightgray text-center text-xs">
{`${props.applyState?.numDiffs === 1 ? "1 diff" : `${props.applyState?.numDiffs} diffs`}`}
</span>
@ -87,7 +87,7 @@ export function ApplyActions(props: ApplyActionsProps) {
if (!hasRejected && props.applyState?.numDiffs === 0) {
if (showApplied) {
return (
<span className="flex items-center rounded bg-zinc-700 text-slate-400 max-sm:px-0.5 sm:pl-2">
<span className="flex select-none items-center rounded bg-zinc-700 text-slate-400 max-sm:px-0.5 sm:pl-2">
<span className="max-sm:hidden">Applied</span>
<CheckIcon className="h-3.5 w-3.5 hover:brightness-125 sm:px-1" />
</span>

View file

@ -15,7 +15,9 @@ export function CreateFileButton({ onClick }: CreateFileButtonProps) {
>
<div className="flex items-center gap-1">
<DocumentPlusIcon className="h-3.5 w-3.5 shrink-0" />
<span className="line-clamp-1 break-all">Create file</span>
<span className="line-clamp-1 select-none break-all">
Create file
</span>
</div>
</button>
</>

View file

@ -25,8 +25,6 @@ import {
vscQuickInputBackground,
} from "../..";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useAppSelector } from "../../../redux/hooks";
import { selectSelectedChatModel } from "../../../redux/slices/configSlice";
import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice";
import { fontSize } from "../../../util";
import FileIcon from "../../FileIcon";
@ -162,8 +160,6 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
const ideMessenger = useContext(IdeMessengerContext);
const selectedModelTitle = useAppSelector(selectSelectedChatModel);
const [selectedIndex, setSelectedIndex] = useState(0);
const [subMenuTitle, setSubMenuTitle] = useState<string | undefined>(
@ -191,7 +187,6 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
query,
fullInput: "",
selectedCode,
selectedModelTitle: selectedModelTitle?.title ?? "",
},
);
@ -204,7 +199,6 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
// Check if the context item exceeds the context length of the selected model
const result = await ideMessenger.request("isItemTooBig", {
item,
selectedModelTitle: selectedModelTitle?.title,
});
if (result.status === "error") {
@ -515,7 +509,7 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
) : (
<DropdownIcon item={item} className="mr-2" />
)}
<span title={item.id}>{item.title}</span>
<span title={item.id} className="whitespace-nowrap">{item.title}</span>
{" "}
</div>
<span
@ -562,7 +556,7 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
);
})
) : (
<ItemDiv className="item">No results</ItemDiv>
<ItemDiv className="item whitespace-nowrap">No results</ItemDiv>
)}
</>
)}

View file

@ -100,7 +100,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
const historyKey = props.isEditMode ? "edit" : "chat";
const placeholder = props.isEditMode
? "Describe how to modify the code - use '#' to add files"
? "Describe changes, '#' to add files"
: undefined;
const toolbarOptions: ToolbarOptions = props.isEditMode

View file

@ -2,8 +2,6 @@ import { AtSymbolIcon, PhotoIcon } from "@heroicons/react/24/outline";
import { InputModifiers } from "core";
import { modelSupportsImages, modelSupportsTools } from "core/llm/autodetect";
import { useRef } from "react";
import styled from "styled-components";
import { vscInputBackground } from "..";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectUseActiveFile } from "../../redux/selectors";
import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall";
@ -16,7 +14,6 @@ import { exitEditMode } from "../../redux/thunks";
import { loadLastSession } from "../../redux/thunks/session";
import {
getAltKeyLabel,
getFontSize,
getMetaKeyLabel,
isMetaEquivalentKeyPressed,
} from "../../util";
@ -27,23 +24,6 @@ import { useFontSize } from "../ui/font";
import { EnterButton } from "./InputToolbar/EnterButton";
import HoverItem from "./InputToolbar/HoverItem";
const StyledDiv = styled.div<{ isHidden?: boolean }>`
padding-top: 4px;
justify-content: space-between;
gap: 1px;
background-color: ${vscInputBackground};
align-items: center;
font-size: ${getFontSize() - 2}px;
cursor: ${(props) => (props.isHidden ? "default" : "text")};
opacity: ${(props) => (props.isHidden ? 0 : 1)};
pointer-events: ${(props) => (props.isHidden ? "none" : "auto")};
user-select: none;
& > * {
flex: 0 0 auto;
}
`;
export interface ToolbarOptions {
hideUseCodebase?: boolean;
hideImageUpload?: boolean;

View file

@ -24,6 +24,6 @@ export const EnterButton = styled.button<{ isPrimary?: boolean }>`
cursor: pointer;
:disabled {
cursor: wait;
cursor: not-allowed;
}
`;

View file

@ -5,9 +5,9 @@ import { AnimatedEllipsis } from "../..";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import { selectCurrentToolCall } from "../../../redux/selectors/selectCurrentToolCall";
import { callTool } from "../../../redux/thunks/callTool";
import { callCurrentTool } from "../../../redux/thunks/callCurrentTool";
import { cancelCurrentToolCall } from "../../../redux/thunks/cancelCurrentToolCall";
import { cancelStream } from "../../../redux/thunks/cancelStream";
import { cancelTool } from "../../../redux/thunks/cancelTool";
import { getFontSize, getMetaKeyLabel } from "../../../util";
import { EnterButton } from "../InputToolbar/EnterButton";
import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar";
@ -50,11 +50,11 @@ export function LumpToolbar() {
if (metaKey && event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
dispatch(callTool());
dispatch(callCurrentTool());
} else if (metaKey && event.key === "Backspace") {
event.preventDefault();
event.stopPropagation();
dispatch(cancelTool());
dispatch(cancelCurrentToolCall());
}
}
};
@ -106,7 +106,7 @@ export function LumpToolbar() {
<div className="flex gap-2 pb-0.5">
<StopButton
className="text-gray-400"
onClick={() => dispatch(cancelTool())}
onClick={() => dispatch(cancelCurrentToolCall())}
data-testid="reject-tool-call-button"
>
{getMetaKeyLabel()} ⌫ Cancel
@ -114,7 +114,7 @@ export function LumpToolbar() {
<EnterButton
isPrimary={true}
className="text-gray-400"
onClick={() => dispatch(callTool())}
onClick={() => dispatch(callCurrentTool())}
data-testid="accept-tool-call-button"
>
{getMetaKeyLabel()} ⏎ Continue

View file

@ -181,7 +181,7 @@ export function RulesSection() {
}
}
// Add a displayed rule for the base system chat message when in chat mode
if (mode === "chat") {
if (mode === "chat" || mode === "agent") {
const baseMessage =
config.selectedModelByRole.chat?.baseChatSystemMessage;
if (baseMessage) {

View file

@ -30,7 +30,7 @@ import {
import { AppDispatch } from "../../../../redux/store";
import { exitEditMode } from "../../../../redux/thunks";
import { loadLastSession } from "../../../../redux/thunks/session";
import { getFontSize } from "../../../../util";
import { getFontSize, isJetBrains } from "../../../../util";
import * as ContinueExtensions from "../extensions";
import { TipTapEditorProps } from "../TipTapEditor";
import { handleImageFile } from "./imageUtils";
@ -267,6 +267,12 @@ export function createEditorConfig(options: {
return false;
},
Escape: () => {
// In JetBrains, this is how we close the sidebar when the input box is focused
if (isJetBrains()) {
ideMessenger.post("closeSidebar", undefined);
return true;
}
if (inDropdownRef.current || !isInEditModeRef.current) {
ideMessenger.post("focusEditor", undefined);
return true;

View file

@ -33,7 +33,6 @@ interface ResolveEditorContentInput {
ideMessenger: IIdeMessenger;
defaultContextProviders: DefaultContextProvider[];
availableSlashCommands: SlashCommandDescription[];
selectedModelTitle: string;
dispatch: Dispatch;
}
@ -60,7 +59,6 @@ export async function resolveEditorContent({
ideMessenger,
defaultContextProviders,
availableSlashCommands,
selectedModelTitle,
dispatch,
}: ResolveEditorContentInput): Promise<ResolveEditorContentOutput> {
const { parts, contextItemAttrs, selectedCode, slashCommandName } =
@ -84,7 +82,6 @@ export async function resolveEditorContent({
defaultContextProviders,
parts,
selectedCode,
selectedModelTitle,
});
if (shouldGatherContext) {
@ -236,7 +233,6 @@ async function gatherContextItems({
defaultContextProviders,
parts,
selectedCode,
selectedModelTitle,
}: {
contextItemAttrs: MentionAttrs[];
modifiers: InputModifiers;
@ -244,7 +240,6 @@ async function gatherContextItems({
defaultContextProviders: DefaultContextProvider[];
parts: MessagePart[];
selectedCode: RangeInFile[];
selectedModelTitle: string;
}): Promise<ContextItemWithId[]> {
let contextItems: ContextItemWithId[] = [];
@ -255,7 +250,6 @@ async function gatherContextItems({
query: item.query ?? "",
fullInput: stripImages(parts),
selectedCode,
selectedModelTitle,
});
if (result.status === "success") {
contextItems.push(...result.content);
@ -269,7 +263,6 @@ async function gatherContextItems({
query: "",
fullInput: stripImages(parts),
selectedCode,
selectedModelTitle,
});
if (result.status === "success") {
@ -285,7 +278,6 @@ async function gatherContextItems({
query: provider.query ?? "",
fullInput: stripImages(parts),
selectedCode,
selectedModelTitle,
});
if (result.status === "success") {
return result.content;

View file

@ -12,7 +12,9 @@ import { useAuth } from "../../context/Auth";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import AddModelForm from "../../forms/AddModelForm";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import {
selectIsInEditMode,
} from "../../redux/slices/sessionSlice";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import { updateSelectedModelByRole } from "../../redux/thunks";
import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
@ -120,10 +122,23 @@ function ModelOption({
function ModelSelect() {
const dispatch = useAppDispatch();
const selectedChatModel = useAppSelector(selectSelectedChatModel);
const allChatModels = useAppSelector(
(state) => state.config.config.modelsByRole.chat,
);
const isInEditMode = useAppSelector(selectIsInEditMode);
const config = useAppSelector((state) => state.config.config);
let selectedModel = null;
let allModels = null;
if (isInEditMode) {
allModels = config.modelsByRole.edit;
selectedModel = config.selectedModelByRole.edit;
}
if (!selectedModel) {
selectedModel = config.selectedModelByRole.chat;
}
if (!allModels || allModels.length === 0) {
allModels = config.modelsByRole.chat;
}
const buttonRef = useRef<HTMLButtonElement>(null);
const [options, setOptions] = useState<Option[]>([]);
const [sortedOptions, setSortedOptions] = useState<Option[]>([]);
@ -141,9 +156,7 @@ function ModelSelect() {
useEffect(() => {
setOptions(
allChatModels
.filter((m) => !m.roles || m.roles.includes("chat"))
.map((model) => {
allModels.map((model) => {
return {
value: model.title,
title: modelSelectTitle(model),
@ -151,7 +164,7 @@ function ModelSelect() {
};
}),
);
}, [allChatModels]);
}, [isInEditMode, config]);
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
@ -162,7 +175,7 @@ function ModelSelect() {
const direction = event.shiftKey ? -1 : 1;
const currentIndex = options.findIndex(
(option) => option.value === selectedChatModel?.title,
(option) => option.value === selectedModel?.title,
);
let nextIndex = (currentIndex + 1 * direction) % options.length;
if (nextIndex < 0) nextIndex = options.length - 1;
@ -182,7 +195,7 @@ function ModelSelect() {
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [options, selectedChatModel]);
}, [options, selectedModel]);
function onClickAddModel(e: MouseEvent) {
e.stopPropagation();
@ -207,11 +220,11 @@ function ModelSelect() {
return (
<Listbox
onChange={async (val: string) => {
if (val === selectedChatModel?.title) return;
if (val === selectedModel?.title) return;
dispatch(
updateSelectedModelByRole({
selectedProfile,
role: "chat",
role: isInEditMode ? "edit" : "chat",
modelTitle: val,
}),
);
@ -224,7 +237,7 @@ function ModelSelect() {
className="h-[18px] gap-1 border-none text-gray-400"
>
<span className="line-clamp-1 break-all hover:brightness-110">
{modelSelectTitle(selectedChatModel) || "Select model"}
{modelSelectTitle(selectedModel) || "Select model"}
</span>
<ChevronDownIcon
className="h-2 w-2 flex-shrink-0 hover:brightness-110"
@ -239,7 +252,7 @@ function ModelSelect() {
idx={idx}
key={idx}
showMissingApiKeyMsg={option.apiKey === ""}
isSelected={option.value === selectedChatModel?.title}
isSelected={option.value === selectedModel?.title}
/>
))}
</div>

View file

@ -18,12 +18,11 @@ import { updateIndexingStatus } from "../redux/slices/indexingSlice";
import {
acceptToolCall,
addContextItemsAtIndex,
setInactive,
setToolCallOutput,
updateApplyState,
} from "../redux/slices/sessionSlice";
import { setTTSActive } from "../redux/slices/uiSlice";
import { streamResponseAfterToolCall } from "../redux/thunks";
import { cancelStream } from "../redux/thunks/cancelStream";
import { refreshSessionMetadata } from "../redux/thunks/session";
import { streamResponseThunk } from "../redux/thunks/streamResponse";
import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols";
@ -138,7 +137,7 @@ function useSetup() {
// ON LOAD
useEffect(() => {
// Override persisted state
dispatch(setInactive());
dispatch(cancelStream());
const jetbrains = isJetBrains();
for (const colorVar of VSC_THEME_COLOR_VARS) {
@ -223,7 +222,7 @@ function useSetup() {
);
useWebviewListener("setInactive", async () => {
dispatch(setInactive());
dispatch(cancelStream());
});
useWebviewListener("setTTSActive", async (status) => {
@ -260,27 +259,34 @@ function useSetup() {
"updateApplyState",
async (state) => {
dispatch(updateApplyState(state));
const lastHistoryMsg = history.at(-1);
const [streamId, toolCallId] = activeToolStreamId ?? [];
if (
activeToolStreamId &&
state.streamId === activeToolStreamId[0] &&
state.status === "closed"
toolCallId &&
state.status === "closed" &&
lastHistoryMsg?.toolCallState?.toolCallId === toolCallId
) {
// const output: ContextItem = {
// name: "Edit tool output",
// content: "Completed edit",
// description: "",
// };
dispatch(acceptToolCall());
dispatch(setToolCallOutput([]));
dispatch(
streamResponseAfterToolCall({
toolCallId: activeToolStreamId[1],
toolOutput: [],
}),
);
if (state.streamId === streamId) {
// const output: ContextItem = {
// name: "Edit tool output",
// content: "Completed edit",
// description: "",
// };
dispatch(
acceptToolCall({
toolCallId,
}),
);
// dispatch(setToolCallOutput([]));
dispatch(
streamResponseAfterToolCall({
toolCallId,
}),
);
}
}
},
[activeToolStreamId],
[activeToolStreamId, history],
);
}

View file

@ -246,7 +246,6 @@ export function Chat() {
defaultContextProviders: [],
availableSlashCommands: [],
dispatch,
selectedModelTitle: selectedChatModel.title,
});
const prompt = [
@ -340,10 +339,7 @@ export function Chat() {
inputId={item.message.id}
/>
</>
) : item.message.role === "tool" ? null : // <ToolOutput
// contextItems={item.contextItems}
// toolCallId={item.message.toolCallId}
// />
) : item.message.role === "tool" ? null : // /> // toolCallId={item.message.toolCallId} // contextItems={item.contextItems} // <ToolOutput
item.message.role === "assistant" &&
item.message.toolCalls &&
item.toolCallState ? (

View file

@ -62,7 +62,10 @@ export function getToolCallStatusMessage(
<span>calling the</span> {defaultToolDescription}
</>
);
} else if (toolCallState.status === "canceled") {
} else if (
toolCallState.status === "canceled" ||
toolCallState.status === "errored"
) {
intro = "tried to";
message = futureMessage;
}

View file

@ -56,6 +56,7 @@ export function ToolCallDiv(props: ToolCallDivProps) {
case "done":
return <CheckIcon className="text-green-500" />;
case "canceled":
case "errored":
return <XMarkIcon className="text-red-500" />;
}
}
@ -74,6 +75,7 @@ export function ToolCallDiv(props: ToolCallDivProps) {
const icon =
props.toolCall.function?.name &&
toolCallIcons[props.toolCall.function?.name];
if (icon && props.toolCall.id) {
return (
<div className="ml-4 mt-2">

View file

@ -29,7 +29,7 @@ import { findUriInDirs, getUriPathBasename } from "core/util/uri";
import { v4 as uuidv4 } from "uuid";
import { RootState } from "../store";
import { streamResponseThunk } from "../thunks/streamResponse";
import { findCurrentToolCall } from "../util";
import { findCurrentToolCall, findToolCall } from "../util";
// We need this to handle reorderings (e.g. a mid-array deletion) of the messages array.
// The proper fix is adding a UUID to all chat messages, but this is the temp workaround.
@ -624,54 +624,100 @@ export const sessionSlice = createSlice({
clearCodeToEdit: (state) => {
state.codeToEdit = [];
},
// Related to currentToolCallState
setToolGenerated: (state) => {
const toolCallState = findCurrentToolCall(state.history);
if (!toolCallState) return;
toolCallState.status = "generated";
},
setToolCallOutput: (state, action: PayloadAction<ContextItem[]>) => {
const toolCallState = findCurrentToolCall(state.history);
if (!toolCallState) return;
toolCallState.output = action.payload;
// TOOL CALL STATE
setToolGenerated: (
state,
action: PayloadAction<{
toolCallId: string;
}>,
) => {
const toolCallState = findToolCall(
state.history,
action.payload.toolCallId,
);
if (toolCallState) {
toolCallState.status = "generated";
}
},
updateToolCallOutput: (
state,
action: PayloadAction<{ toolCallId: string; contextItems: ContextItem[] }>,
action: PayloadAction<{
toolCallId: string;
contextItems: ContextItem[];
}>,
) => {
// Find the tool call with the given ID and update its output
const { toolCallId, contextItems } = action.payload;
// Find the history item containing the tool call
const historyItem = state.history.find(
(item) =>
item.toolCallState?.toolCallId === toolCallId
const toolCallState = findToolCall(
state.history,
action.payload.toolCallId,
);
if (historyItem && historyItem.toolCallState) {
historyItem.toolCallState.output = contextItems;
if (toolCallState) {
toolCallState.output = action.payload.contextItems;
}
},
cancelToolCall: (state) => {
const toolCallState = findCurrentToolCall(state.history);
if (!toolCallState) return;
toolCallState.status = "canceled";
cancelToolCall: (
state,
action: PayloadAction<{
toolCallId: string;
}>,
) => {
if (action.payload.toolCallId === state.activeToolStreamId?.[1]) {
state.activeToolStreamId = undefined;
}
const toolCallState = findToolCall(
state.history,
action.payload.toolCallId,
);
if (toolCallState) {
toolCallState.status = "canceled";
}
},
acceptToolCall: (state) => {
state.activeToolStreamId = undefined;
const toolCallState = findCurrentToolCall(state.history);
if (!toolCallState) return;
toolCallState.status = "done";
errorToolCall: (
state,
action: PayloadAction<{
toolCallId: string;
}>,
) => {
if (action.payload.toolCallId === state.activeToolStreamId?.[1]) {
state.activeToolStreamId = undefined;
}
const toolCallState = findToolCall(
state.history,
action.payload.toolCallId,
);
if (toolCallState) {
toolCallState.status = "errored";
}
},
setCalling: (state) => {
const toolCallState = findCurrentToolCall(state.history);
if (!toolCallState) return;
toolCallState.status = "calling";
acceptToolCall: (
state,
action: PayloadAction<{
toolCallId: string;
}>,
) => {
if (action.payload.toolCallId === state.activeToolStreamId?.[1]) {
state.activeToolStreamId = undefined;
}
const toolCallState = findToolCall(
state.history,
action.payload.toolCallId,
);
if (toolCallState) {
toolCallState.status = "done";
}
},
setToolCallCalling: (
state,
action: PayloadAction<{
toolCallId: string;
}>,
) => {
const toolCallState = findToolCall(
state.history,
action.payload.toolCallId,
);
if (toolCallState) {
toolCallState.status = "calling";
}
},
setMode: (state, action: PayloadAction<MessageModes>) => {
state.mode = action.payload;
@ -785,11 +831,11 @@ export const {
clearCodeToEdit,
addCodeToEdit,
removeCodeToEdit,
setCalling,
setToolCallCalling,
cancelToolCall,
errorToolCall,
acceptToolCall,
setToolGenerated,
setToolCallOutput,
updateToolCallOutput,
setMode,
setAllSessionMetadata,

View file

@ -1,4 +1,9 @@
import { combineReducers, configureStore } from "@reduxjs/toolkit";
import {
combineReducers,
configureStore,
ThunkDispatch,
UnknownAction,
} from "@reduxjs/toolkit";
import { createLogger } from "redux-logger";
import {
createMigrate,
@ -130,11 +135,19 @@ export function setupStore() {
});
}
export type ThunkExtrasType = { ideMessenger: IIdeMessenger };
export type ThunkApiType = {
state: RootState;
extra: { ideMessenger: IIdeMessenger };
extra: ThunkExtrasType;
};
export type AppThunkDispatch = ThunkDispatch<
RootState,
ThunkExtrasType,
UnknownAction
>;
export const store = setupStore();
export type RootState = ReturnType<typeof rootReducer>;

View file

@ -0,0 +1,133 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ContextItem } from "core";
import { CLIENT_TOOLS } from "core/tools/builtIn";
import { callClientTool } from "../../util/clientTools/callClientTool";
import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
import { selectSelectedChatModel } from "../slices/configSlice";
import {
acceptToolCall,
errorToolCall,
setToolCallCalling,
updateToolCallOutput,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
export const callCurrentTool = createAsyncThunk<void, undefined, ThunkApiType>(
"chat/callTool",
async (_, { dispatch, extra, getState }) => {
const state = getState();
const toolCallState = selectCurrentToolCall(state);
if (!toolCallState) {
return;
}
if (toolCallState.status !== "generated") {
return;
}
const selectedChatModel = selectSelectedChatModel(state);
if (!selectedChatModel) {
throw new Error("No model selected");
}
const { toolCallId } = toolCallState;
dispatch(
setToolCallCalling({
toolCallId,
}),
);
let output: ContextItem[] | undefined = undefined;
let errorMessage: string | undefined = undefined;
let streamResponse: boolean;
// IMPORTANT:
// Errors that occur while calling tool call implementations
// Are caught and passed in output as context items
// Errors that occur outside specifically calling the tool
// Should not be caught here - should be handled as normal stream errors
if (
CLIENT_TOOLS.find(
(toolName) => toolName === toolCallState.toolCall.function.name,
)
) {
// Tool is called on client side
const {
output: clientToolOuput,
respondImmediately,
errorMessage: clientToolError,
} = await callClientTool(toolCallState.toolCall, {
dispatch,
ideMessenger: extra.ideMessenger,
activeToolStreamId: state.session.activeToolStreamId?.[0],
});
output = clientToolOuput;
errorMessage = clientToolError;
streamResponse = respondImmediately;
} else {
// Tool is called on core side
const result = await extra.ideMessenger.request("tools/call", {
toolCall: toolCallState.toolCall,
});
if (result.status === "error") {
throw new Error(result.error);
} else {
output = result.content.contextItems;
errorMessage = result.content.errorMessage;
}
streamResponse = true;
}
if (errorMessage) {
dispatch(
updateToolCallOutput({
toolCallId,
contextItems: [
{
icon: "problems",
name: "Tool Call Error",
description: "Tool Call Failed",
content: `${toolCallState.toolCall.function.name} failed with the message: ${errorMessage}\n\nPlease try something else or request further instructions.`,
hidden: false,
},
],
}),
);
} else if (output?.length) {
dispatch(
updateToolCallOutput({
toolCallId,
contextItems: output,
}),
);
}
if (streamResponse) {
if (errorMessage) {
dispatch(
errorToolCall({
toolCallId,
}),
);
} else {
dispatch(
acceptToolCall({
toolCallId,
}),
);
}
// Send to the LLM to continue the conversation
const wrapped = await dispatch(
streamResponseAfterToolCall({
toolCallId,
}),
);
unwrapResult(wrapped);
}
},
);

View file

@ -1,146 +0,0 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ContextItem } from "core";
import { BuiltInToolNames } from "core/tools/builtIn";
import { EditToolArgs } from "core/tools/definitions/editFile";
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { IIdeMessenger } from "../../context/IdeMessenger";
import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
import { selectSelectedChatModel } from "../slices/configSlice";
import {
acceptToolCall,
cancelToolCall,
setCalling,
setToolCallOutput,
updateApplyState,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
export const callTool = createAsyncThunk<void, undefined, ThunkApiType>(
"chat/callTool",
async (_, { dispatch, extra, getState }) => {
const state = getState();
const toolCallState = selectCurrentToolCall(state);
if (!toolCallState) {
return;
}
if (toolCallState.status !== "generated") {
return;
}
const selectedChatModel = selectSelectedChatModel(state);
if (!selectedChatModel) {
throw new Error("No model selected");
}
dispatch(setCalling());
let errorMessage = "";
let output: ContextItem[] | undefined = undefined;
if (
toolCallState.toolCall.function.name === BuiltInToolNames.EditExistingFile
) {
const args = JSON.parse(
toolCallState.toolCall.function.arguments || "{}",
);
try {
if (!state.session.activeToolStreamId) {
throw new Error("Invalid apply state");
}
await customGuiEditImpl(
args,
extra.ideMessenger,
state.session.activeToolStreamId[0],
toolCallState.toolCallId,
);
} catch (e) {
errorMessage = "Failed to call edit tool";
if (e instanceof Error) {
errorMessage = e.message;
}
if (state.session.activeToolStreamId?.[0]) {
dispatch(
updateApplyState({
streamId: state.session.activeToolStreamId[0],
status: "closed",
toolCallId: toolCallState.toolCallId,
numDiffs: 0,
filepath: args.filepath,
}),
);
}
}
} else {
const result = await extra.ideMessenger.request("tools/call", {
toolCall: toolCallState.toolCall,
selectedModelTitle: selectedChatModel.title,
});
if (result.status === "error") {
errorMessage = result.error;
} else {
output = result.content.contextItems;
}
}
if (errorMessage) {
dispatch(cancelToolCall());
const wrapped = await dispatch(
streamResponseAfterToolCall({
toolCallId: toolCallState.toolCallId,
toolOutput: [
{
icon: "problems",
name: "Tool Call Error",
description: "Tool Call Failed",
content: `${toolCallState.toolCall.function.name} failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`,
hidden: false,
},
],
}),
);
unwrapResult(wrapped);
} else if (output) {
dispatch(setToolCallOutput(output));
dispatch(acceptToolCall());
// Send to the LLM to continue the conversation
const wrapped = await dispatch(
streamResponseAfterToolCall({
toolCallId: toolCallState.toolCall.id,
toolOutput: output,
}),
);
unwrapResult(wrapped);
}
// okay for a tool to have no output and need some GUI trigger or other to trigger response e.g. edit tool
},
);
async function customGuiEditImpl(
args: EditToolArgs,
ideMessenger: IIdeMessenger,
streamId: string,
toolCallId: string,
) {
const firstUriMatch = await resolveRelativePathInDir(
args.filepath,
ideMessenger.ide,
);
if (!firstUriMatch) {
throw new Error(`${args.filepath} does not exist`);
}
const apply = await ideMessenger.request("applyToFile", {
streamId,
text: args.new_contents,
toolCallId,
filepath: firstUriMatch,
});
if (apply.status === "error") {
throw new Error(apply.error);
}
}

View file

@ -0,0 +1,50 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
import { cancelToolCall, updateToolCallOutput } from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
export const cancelCurrentToolCall = createAsyncThunk<
void,
undefined,
ThunkApiType
>("chat/cancelTool", async (_, { dispatch, extra, getState }) => {
const state = getState();
const toolCallState = selectCurrentToolCall(state);
if (!toolCallState) {
return;
}
if (toolCallState.status !== "generated") {
return;
}
const { toolCallId } = toolCallState;
dispatch(
cancelToolCall({
toolCallId,
}),
);
dispatch(
updateToolCallOutput({
toolCallId,
contextItems: [
{
name: "Tool Cancelled",
description: "Tool Cancelled",
content:
"The tool call was cancelled by the user. Please try something else or request further instructions.",
hidden: true,
},
],
}),
);
const output = await dispatch(
streamResponseAfterToolCall({
toolCallId,
}),
);
unwrapResult(output);
});

View file

@ -12,8 +12,9 @@ export const cancelStream = createAsyncThunk<void, undefined, ThunkApiType>(
dispatch(setInactive());
dispatch(abortStream());
// In the case tool calls were being generated,
// Replace them with
// If the assistant message is empty, then remove it and the user message, placing the user input in the main text box
// TODO: Waiting until next release
dispatch(clearLastEmptyResponse());
},
);

View file

@ -1,39 +0,0 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
import { cancelToolCall } from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
export const cancelTool = createAsyncThunk<void, undefined, ThunkApiType>(
"chat/cancelTool",
async (_, { dispatch, extra, getState }) => {
const state = getState();
const toolCallState = selectCurrentToolCall(state);
if (!toolCallState) {
return;
}
if (toolCallState.status !== "generated") {
return;
}
dispatch(cancelToolCall());
const output = await dispatch(
streamResponseAfterToolCall({
toolCallId: toolCallState.toolCallId,
toolOutput: [
{
name: "Tool Cancelled",
description: "Tool Cancelled",
content:
"The tool call was cancelled by the user. Please try something else or request further instructions.",
hidden: true,
},
],
}),
);
unwrapResult(output);
},
);

View file

@ -58,7 +58,6 @@ export const gatherContext = createAsyncThunk<
defaultContextProviders,
availableSlashCommands: state.config.config.slashCommands,
dispatch,
selectedModelTitle: selectedChatModel.title,
});
// Automatically use currently open file
@ -72,7 +71,6 @@ export const gatherContext = createAsyncThunk<
query: "non-mention-usage",
fullInput: "",
selectedCode: [],
selectedModelTitle: selectedChatModel.title,
},
);
if (currentFileResponse.status === "success") {

View file

@ -1,6 +1,10 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import { ContextItem } from "core";
import { abortStream, acceptToolCall, updateToolCallOutput } from "../slices/sessionSlice";
import {
abortStream,
acceptToolCall,
updateToolCallOutput,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
@ -15,54 +19,64 @@ export const moveTerminalProcessToBackground = createAsyncThunk<
void,
{ toolCallId: string },
ThunkApiType
>("chat/moveTerminalProcessToBackground", async ({ toolCallId }, { dispatch, getState, extra }) => {
// Find the current tool call
const state = getState();
const toolCalls = state.session.history.filter(
(item) => item.toolCallState?.toolCallId === toolCallId
);
>(
"chat/moveTerminalProcessToBackground",
async ({ toolCallId }, { dispatch, getState, extra }) => {
// Find the current tool call
const state = getState();
const toolCalls = state.session.history.filter(
(item) => item.toolCallState?.toolCallId === toolCallId,
);
if (toolCalls.length === 0) {
console.error("Could not find tool call with ID:", toolCallId);
return;
}
const toolCall = toolCalls[0].toolCallState;
if (!toolCall) {
console.error("Tool call state is missing");
return;
}
const status = "Command moved to background. Further output will be ignored."
const contextItems: ContextItem[] = [
{
name: "Terminal",
description: "Terminal command output",
content: "\n" + status,
status: status,
if (toolCalls.length === 0) {
console.error("Could not find tool call with ID:", toolCallId);
return;
}
];
// Abort any existing stream for this tool call
dispatch(abortStream());
const toolCall = toolCalls[0].toolCallState;
if (!toolCall) {
console.error("Tool call state is missing");
return;
}
// Update the tool call output
dispatch(updateToolCallOutput({
toolCallId,
contextItems
}));
const status =
"Command moved to background. Further output will be ignored.";
// Mark the process as backgrounded so we ignore future events
await extra.ideMessenger.request("process/markAsBackgrounded", { toolCallId });
const contextItems: ContextItem[] = [
{
name: "Terminal",
description: "Terminal command output",
content: "\n" + status,
status: status,
},
];
// Mark the tool call as "done" in the UI
// This will set isRunning to false in RunTerminalCommand.tsx
dispatch(acceptToolCall());
// Abort any existing stream for this tool call
dispatch(abortStream());
// Trigger an LLM response about the command being moved to background
dispatch(streamResponseAfterToolCall({
toolCallId,
toolOutput: contextItems
}));
});
// Update the tool call output
dispatch(
updateToolCallOutput({
toolCallId,
contextItems,
}),
);
// Mark the process as backgrounded so we ignore future events
await extra.ideMessenger.request("process/markAsBackgrounded", {
toolCallId,
});
// Mark the tool call as "done" in the UI
// This will set isRunning to false in RunTerminalCommand.tsx
dispatch(acceptToolCall({ toolCallId }));
// Trigger an LLM response about the command being moved to background
dispatch(updateToolCallOutput({ toolCallId, contextItems }));
dispatch(
streamResponseAfterToolCall({
toolCallId,
}),
);
},
);

View file

@ -180,7 +180,6 @@ export const saveCurrentSession = createAsyncThunk<
"chatDescriber/describe",
{
text: assistantResponse,
selectedModelTitle: selectedChatModel.title,
},
);
if (result.status === "success" && result.content) {

View file

@ -12,7 +12,7 @@ import {
streamUpdate,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { callTool } from "./callTool";
import { callCurrentTool } from "./callCurrentTool";
export const streamNormalInput = createAsyncThunk<
void,
@ -107,13 +107,17 @@ export const streamNormalInput = createAsyncThunk<
// If it's a tool call that is automatically accepted, we should call it
const toolCallState = selectCurrentToolCall(getState());
if (toolCallState) {
dispatch(setToolGenerated());
dispatch(
setToolGenerated({
toolCallId: toolCallState.toolCallId,
}),
);
if (
toolSettings[toolCallState.toolCall.function.name] ===
"allowedWithoutPermission"
) {
const response = await dispatch(callTool());
const response = await dispatch(callCurrentTool());
unwrapResult(response);
}
}

View file

@ -1,5 +1,5 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ChatMessage, ContextItem } from "core";
import { ChatMessage } from "core";
import { constructMessages } from "core/llm/constructMessages";
import { renderContextItems } from "core/util/messageContent";
import { selectSelectedChatModel } from "../slices/configSlice";
@ -9,20 +9,18 @@ import {
streamUpdate,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { findToolCall } from "../util";
import { resetStateForNewMessage } from "./resetStateForNewMessage";
import { streamNormalInput } from "./streamNormalInput";
import { streamThunkWrapper } from "./streamThunkWrapper";
export const streamResponseAfterToolCall = createAsyncThunk<
void,
{
toolCallId: string;
toolOutput: ContextItem[];
},
{ toolCallId: string },
ThunkApiType
>(
"chat/streamAfterToolCall",
async ({ toolCallId, toolOutput }, { dispatch, getState }) => {
async ({ toolCallId }, { dispatch, getState }) => {
await dispatch(
streamThunkWrapper(async () => {
const state = getState();
@ -33,6 +31,14 @@ export const streamResponseAfterToolCall = createAsyncThunk<
throw new Error("No model selected");
}
const toolCallState = findToolCall(state.session.history, toolCallId);
if (!toolCallState) {
throw new Error("Tool call not found");
}
const toolOutput = toolCallState.output ?? [];
resetStateForNewMessage();
await new Promise((resolve) => setTimeout(resolve, 0));

View file

@ -1,8 +1,9 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import StreamErrorDialog from "../../pages/gui/StreamError";
import { clearLastEmptyResponse, setInactive } from "../slices/sessionSlice";
import { setInactive } from "../slices/sessionSlice";
import { setDialogMessage, setShowDialog } from "../slices/uiSlice";
import { ThunkApiType } from "../store";
import { cancelStream } from "./cancelStream";
import { saveCurrentSession } from "./session";
export const streamThunkWrapper = createAsyncThunk<
@ -12,14 +13,8 @@ export const streamThunkWrapper = createAsyncThunk<
>("chat/streamWrapper", async (runStream, { dispatch, extra, getState }) => {
try {
await runStream();
} catch (e: unknown) {
dispatch(clearLastEmptyResponse());
dispatch(setDialogMessage(<StreamErrorDialog error={e} />));
dispatch(setShowDialog(true));
} finally {
dispatch(setInactive());
const state = getState();
if (state.session.mode === "chat") {
if (state.session.mode === "chat" || state.session.mode === "agent") {
await dispatch(
saveCurrentSession({
openNewSession: false,
@ -27,5 +22,10 @@ export const streamThunkWrapper = createAsyncThunk<
}),
);
}
dispatch(setInactive());
} catch (e) {
dispatch(cancelStream());
dispatch(setDialogMessage(<StreamErrorDialog error={e} />));
dispatch(setShowDialog(true));
}
});

View file

@ -2,7 +2,16 @@ import { ToolCallState } from "core";
import { RootState } from "../store";
export function findCurrentToolCall(
state: RootState["session"]["history"],
chatHistory: RootState["session"]["history"],
): ToolCallState | undefined {
return state[state.length - 1]?.toolCallState;
return chatHistory[chatHistory.length - 1]?.toolCallState;
}
export function findToolCall(
chatHistory: RootState["session"]["history"],
toolCallId: string,
): ToolCallState | undefined {
return chatHistory.find(
(item) => item.toolCallState?.toolCallId === toolCallId,
)?.toolCallState;
}

View file

@ -0,0 +1,57 @@
import { ContextItem, ToolCall } from "core";
import { BuiltInToolNames } from "core/tools/builtIn";
import { IIdeMessenger } from "../../context/IdeMessenger";
import { AppThunkDispatch } from "../../redux/store";
import { editToolImpl } from "./editImpl";
export interface ClientToolExtras {
dispatch: AppThunkDispatch;
ideMessenger: IIdeMessenger;
activeToolStreamId?: string;
}
export interface ClientToolOutput {
output: ContextItem[] | undefined;
respondImmediately: boolean;
}
export interface ClientToolResult extends ClientToolOutput {
errorMessage: string | undefined;
}
export type ClientToolImpl = (
args: any,
toolCallId: string,
extras: ClientToolExtras,
) => Promise<ClientToolOutput>;
export async function callClientTool(
toolCall: ToolCall,
extras: ClientToolExtras,
): Promise<ClientToolResult> {
const args = JSON.parse(toolCall.function.arguments || "{}");
try {
let output: ClientToolOutput;
switch (toolCall.function.name) {
case BuiltInToolNames.EditExistingFile:
output = await editToolImpl(args, toolCall.id, extras);
break;
default:
throw new Error(`Invalid client tool name ${toolCall.function.name}`);
}
return {
...output,
errorMessage: undefined,
};
} catch (e) {
let errorMessage = `${e}`;
if (e instanceof Error) {
errorMessage = e.message;
}
return {
respondImmediately: true,
errorMessage,
output: undefined,
};
}
}

View file

@ -0,0 +1,44 @@
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { updateApplyState } from "../../redux/slices/sessionSlice";
import { ClientToolImpl } from "./callClientTool";
export const editToolImpl: ClientToolImpl = async (
args,
toolCallId,
extras,
) => {
if (!extras.activeToolStreamId) {
throw new Error("Invalid apply state");
}
const firstUriMatch = await resolveRelativePathInDir(
args.filepath,
extras.ideMessenger.ide,
);
if (!firstUriMatch) {
throw new Error(`${args.filepath} does not exist`);
}
const apply = await extras.ideMessenger.request("applyToFile", {
streamId: extras.activeToolStreamId,
text: args.new_contents,
toolCallId,
filepath: firstUriMatch,
});
if (apply.status === "error") {
throw new Error(apply.error);
}
if (extras.activeToolStreamId) {
extras.dispatch(
updateApplyState({
streamId: extras.activeToolStreamId,
status: "closed",
toolCallId,
numDiffs: 0,
filepath: args.filepath,
}),
);
}
return {
respondImmediately: false,
output: undefined, // No immediate output.
};
};

View file

@ -65,6 +65,7 @@ export type ChatOptions = z.infer<typeof chatOptionsSchema>;
const promptTemplatesSchema = z.object({
apply: z.string().optional(),
edit: z.string().optional(),
autocomplete: z.string().optional()
});
export type PromptTemplates = z.infer<typeof promptTemplatesSchema>;

View file

@ -8,6 +8,12 @@ export const OpenAi: ModelProvider = {
contextLength: 16385,
maxCompletionTokens: 4096,
},
{
model: "gpt-3.5-turbo-0613",
displayName: "GPT-3.5 Turbo",
contextLength: 16385,
maxCompletionTokens: 4096,
},
{
model: "gpt-3.5-turbo-16k",
displayName: "GPT-3.5 Turbo 16K",

View file

@ -5,58 +5,27 @@
# - Debug -> Extension
set -e
# Set the correct Node version at the start of the script
setup_node_version() {
# Get required node version from .node-version or .nvmrc
if [ -f .node-version ]; then
required_node_version=$(cat .node-version)
elif [ -f .nvmrc ]; then
# Check if node version matches .nvmrc
if [ -f .nvmrc ]; then
required_node_version=$(cat .nvmrc)
else
echo "No .node-version or .nvmrc file found. Skipping Node.js version check."
return
fi
current_node_version=$(node -v)
# Remove 'v' prefix from versions for comparison
required_version=${required_node_version#v}
current_version=${current_node_version#v}
# Remove 'v' prefix if present
required_version=${required_node_version#v}
# Try fnm first
if command -v fnm &> /dev/null; then
echo "📦 Using fnm to set Node.js version to $required_version..."
# Capture output to avoid duplicate messages
eval "$(fnm env --use-on-cd)" &> /dev/null
fnm use "$required_version" &> /dev/null || fnm use &> /dev/null
# Then try nvm
elif command -v nvm &> /dev/null || [ -s "$NVM_DIR/nvm.sh" ]; then
echo "📦 Using nvm to set Node.js version to $required_version..."
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # Load nvm
nvm use "$required_version" &> /dev/null || nvm use &> /dev/null
# Fall back to version check only
else
echo "Neither fnm nor nvm found. Proceeding with current Node.js version."
fi
# Verify the current Node.js version after our attempt to set it
current_node_version=$(node -v)
current_version=${current_node_version#v}
if [ "$required_version" != "$current_version" ]; then
echo "⚠️ Warning: Your Node.js version ($current_node_version) does not match the required version (v$required_version)"
echo "Even after attempting to use version managers, the correct version couldn't be activated."
if [ -t 0 ]; then
read -p "Press Enter to continue with installation anyway..."
else
echo "Continuing with installation anyway..."
if [ "$required_version" != "$current_version" ]; then
echo "⚠️ Warning: Your Node.js version ($current_node_version) does not match the required version ($required_node_version)"
echo "Please consider switching to the correct version using: nvm use"
if [ -t 0 ]; then
read -p "Press Enter to continue with installation anyway..."
else
echo "Continuing with installation anyway..."
fi
echo
fi
echo
else
echo "✅ Using Node.js $current_node_version as required."
fi
}
# Run the node version setup
setup_node_version
fi
echo "Installing root-level dependencies..."
npm install