Merge branch 'main' of https://github.com/continuedev/continue into dallin/stringify-fetch-error

This commit is contained in:
Dallin Romney 2025-07-02 15:23:35 -07:00
commit cf39abdfb6
71 changed files with 2128 additions and 894 deletions

View file

@ -26,5 +26,6 @@ jobs:
path-to-signatures: "signatures/version1/cla.json"
path-to-document: "https://github.com/continuedev/continue/blob/main/docs/docs/CLA.md"
branch: cla-signatures
allowlist: dependabot[bot]
# Bots and CLAs signed outside of GitHub
allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline
signed-commit-message: "CLA signed in $pullRequestNo"

View file

@ -167,20 +167,8 @@ jobs:
path: gui/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build and check config-yaml
run: |
cd ../../packages/config-yaml
npm i
npx tsc --noEmit
# Tests are currently failing, commenting out for now
# npm test
npm run build
- name: Build packages (Unix)
run: ./scripts/build-packages.sh
# npm install core
- name: Install core node_modules

View file

@ -10,7 +10,7 @@ import {
JSONModelDescription,
PromptTemplate,
} from "../";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages";
import { GlobalContext } from "../util/GlobalContext";
import { editConfigFile } from "../util/paths";

View file

@ -1,5 +1,6 @@
import { BaseContextProvider } from "../";
import { ContextProviderName } from "../../";
import { Telemetry } from "../../util/posthog";
import ClipboardContextProvider from "./ClipboardContextProvider";
import CodebaseContextProvider from "./CodebaseContextProvider";
@ -75,5 +76,12 @@ export const Providers: (typeof BaseContextProvider)[] = [
export function contextProviderClassFromName(
name: ContextProviderName,
): typeof BaseContextProvider | undefined {
return Providers.find((cls) => cls.description.title === name);
const provider = Providers.find((cls) => cls.description.title === name);
void Telemetry.capture("context_provider_load", {
providerName: name,
found: !!provider, // also capture those which user expected to be present
});
return provider;
}

View file

@ -872,7 +872,7 @@ export class Core {
this.messenger.send("toolCallPartialOutput", params);
};
return await callTool(tool, toolCall, {
const result = await callTool(tool, toolCall, {
config,
ide: this.ide,
llm: config.selectedModelByRole.chat,
@ -883,6 +883,8 @@ export class Core {
onPartialOutput,
codeBaseIndexer: this.codeBaseIndexer,
});
return result;
}
private async isItemTooBig(item: ContextItemWithId) {
@ -1105,6 +1107,10 @@ export class Core {
itemId: uuidv4(),
};
void Telemetry.capture("context_provider_get_context_items", {
name: provider.description.title,
});
const items = await provider.getContextItems(query, {
config,
llm,

View file

@ -112,7 +112,7 @@ export async function* streamDiffLines({
// If any rules are present this will result in using chat instead of legacy completion
const systemMessage = rulesToInclude
? getSystemMessageWithRules({
rules: rulesToInclude,
availableRules: rulesToInclude,
userMessage:
typeof prompt === "string"
? ({
@ -125,7 +125,7 @@ export async function* streamDiffLines({
) as UserChatMessage | ToolResultChatMessage | undefined),
baseSystemMessage: undefined,
contextItems: [],
})
}).systemMessage
: undefined;
if (systemMessage) {

View file

@ -981,17 +981,11 @@ export default class DocsService {
// Otherwise sync the index based on config changes
const oldConfigDocs = oldConfig?.docs || [];
const newConfigDocs = newConfig.docs || [];
const newConfigStartUrls = newConfigDocs.map((doc) => doc.startUrl);
// NOTE since listMetadata filters by embeddings provider id embedding model changes are accounted for here
const currentlyIndexedDocs = await this.listMetadata();
const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl);
// Anything found in sqlite but not in new config should be deleted
const deletedDocs = currentlyIndexedDocs.filter(
(doc) => !newConfigStartUrls.includes(doc.startUrl),
);
// Anything found in old config, new config, AND sqlite that doesn't match should be reindexed
// TODO if only favicon and title change, only update, don't embed
// Otherwise anything found in new config that isn't in sqlite should be added/indexed
@ -1038,10 +1032,6 @@ export default class DocsService {
...changedDocs.map((doc) => this.indexAndAdd(doc, true)),
...addedDocs.map((doc) => this.indexAndAdd(doc)),
]);
for (const doc of deletedDocs) {
await this.deleteIndexes(doc.startUrl);
}
} catch (e) {
console.error("Error syncing docs index on config update", e);
} finally {

View file

@ -1,187 +0,0 @@
import {
ChatHistoryItem,
ChatMessage,
ContextItemWithId,
RuleWithSource,
TextMessagePart,
ToolResultChatMessage,
UserChatMessage,
} from "../";
import { findLast } from "../util/findLast";
import { normalizeToMessageParts } from "../util/messageContent";
import { isUserOrToolMsg } from "./messages";
import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
import { RulePolicies } from "./rules/types";
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL =
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\
Always include the language and file name in the info string when you write code blocks.
If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
`;
export const EDIT_CODE_INSTRUCTIONS = `\
When addressing code modification requests, present a concise code snippet that
emphasizes only the necessary changes and uses abbreviated placeholders for
unmodified sections. For example:
\`\`\`language /path/to/file
// ... existing code ...
{{ modified code here }}
// ... existing code ...
{{ another modification }}
// ... rest of code ...
\`\`\`
In existing files, you should always restate the function or class that the snippet belongs to:
\`\`\`language /path/to/file
// ... existing code ...
function exampleFunction() {
// ... existing code ...
{{ modified code here }}
// ... rest of function ...
}
// ... rest of code ...
\`\`\`
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
provide the complete file when explicitly requested. Include a concise explanation
of changes unless the user specifically asks for code only.
`;
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
<important_rules>
You are in chat mode.
If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically.
If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
${EDIT_CODE_INSTRUCTIONS}
</important_rules>`;
export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
<important_rules>
You are in agent mode.
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
</important_rules>`;
/**
* Helper function to get the context items for a user message
*/
function getUserContextItems(
userMsg: UserChatMessage | ToolResultChatMessage | undefined,
history: ChatHistoryItem[],
): ContextItemWithId[] {
if (!userMsg) return [];
// Find the history item that contains the userMsg
const historyItem = history.find((item) => {
// Check if the message ID matches
if ("id" in userMsg && "id" in item.message) {
return (item.message as any).id === (userMsg as any).id;
}
// Fallback to content comparison
return (
item.message.content === userMsg.content &&
item.message.role === userMsg.role
);
});
return historyItem?.contextItems || [];
}
export function constructMessages(
messageMode: string,
history: ChatHistoryItem[],
baseChatOrAgentSystemMessage: string | undefined,
rules: RuleWithSource[],
rulePolicies?: RulePolicies,
): ChatMessage[] {
const filteredHistory = history.filter(
(item) => item.message.role !== "system",
);
const msgs: ChatMessage[] = [];
for (let i = 0; i < filteredHistory.length; i++) {
const historyItem = filteredHistory[i];
if (messageMode === "chat") {
const toolMessage: ToolResultChatMessage =
historyItem.message as ToolResultChatMessage;
if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) {
// remove all tool calls from the history
continue;
}
}
if (historyItem.message.role === "user") {
// Gather context items for user messages
let content = normalizeToMessageParts(historyItem.message);
const ctxItems = historyItem.contextItems
.map((ctxItem) => {
return {
type: "text",
text: `${ctxItem.content}\n`,
} as TextMessagePart;
})
.filter((part) => !!part.text.trim());
content = [...ctxItems, ...content];
msgs.push({
...historyItem.message,
content,
});
} else {
msgs.push(historyItem.message);
}
}
const lastUserMsg = findLast(msgs, isUserOrToolMsg) as
| UserChatMessage
| ToolResultChatMessage
| undefined;
// Get context items for the last user message
const lastUserContextItems = getUserContextItems(
lastUserMsg,
filteredHistory,
);
const systemMessage = getSystemMessageWithRules({
baseSystemMessage: baseChatOrAgentSystemMessage,
rules,
userMessage: lastUserMsg,
contextItems: lastUserContextItems,
rulePolicies,
});
if (systemMessage.trim()) {
msgs.unshift({
role: "system",
content: systemMessage,
});
}
// Remove the "id" from all of the messages
return msgs.map((msg) => {
const { id, ...rest } = msg as any;
return rest;
});
}

View file

@ -0,0 +1,68 @@
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
"https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts";
export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL =
"https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts";
export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\
Always include the language and file name in the info string when you write code blocks.
If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
`;
export const EDIT_CODE_INSTRUCTIONS = `\
When addressing code modification requests, present a concise code snippet that
emphasizes only the necessary changes and uses abbreviated placeholders for
unmodified sections. For example:
\`\`\`language /path/to/file
// ... existing code ...
{{ modified code here }}
// ... existing code ...
{{ another modification }}
// ... rest of code ...
\`\`\`
In existing files, you should always restate the function or class that the snippet belongs to:
\`\`\`language /path/to/file
// ... existing code ...
function exampleFunction() {
// ... existing code ...
{{ modified code here }}
// ... rest of function ...
}
// ... rest of code ...
\`\`\`
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
provide the complete file when explicitly requested. Include a concise explanation
of changes unless the user specifically asks for code only.
`;
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
<important_rules>
You are in chat mode.
If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically.
If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
${EDIT_CODE_INSTRUCTIONS}
</important_rules>`;
export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
<important_rules>
You are in agent mode.
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
</important_rules>`;

View file

@ -1,12 +1,10 @@
import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
import Bedrock from "./Bedrock.js";
import {
ChatMessage,
Chunk,
CompletionOptions,
UserChatMessage,
} from "../../index.js";
import Bedrock from "./Bedrock.js";
// Mock AWS SDK
jest.mock("@aws-sdk/client-bedrock-runtime", () => ({
@ -317,96 +315,266 @@ describe("Bedrock", () => {
});
});
it("should convert text messages correctly", () => {
const message: ChatMessage = {
role: "user",
content: "Hello",
} as UserChatMessage;
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
role: "user",
content: [{ text: "Hello" }],
});
it("should convert simple user and assistant messages correctly", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Hello" } as UserChatMessage,
{ role: "assistant", content: "Hi there" },
];
const availableTools = new Set<string>();
const converted = bedrock["_convertMessages"](messages, availableTools);
expect(converted).toEqual([
{ role: "user", content: [{ text: "Hello" }] },
{ role: "assistant", content: [{ text: "Hi there" }] },
]);
});
it("should convert tool responses correctly", () => {
const message: ChatMessage = {
role: "tool",
content: "Tool result",
toolCallId: "tool-1",
};
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
role: "user",
content: [
{
toolResult: {
toolUseId: "tool-1",
content: [{ text: "Tool result" }],
},
},
],
});
});
it("should convert tool calls correctly", () => {
const message: ChatMessage = {
role: "assistant",
content: "",
toolCalls: [
{
id: "tool-1",
type: "function" as const,
function: {
name: "test_tool",
arguments: '{"arg":"value"}',
},
},
],
};
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
role: "assistant",
content: [
{
toolUse: {
toolUseId: "tool-1",
name: "test_tool",
input: { arg: "value" },
},
},
],
});
});
it("should handle multimodal content correctly", () => {
const message: ChatMessage = {
role: "user",
content: [
{ type: "text", text: "Look at this image:" },
{
type: "imageUrl",
imageUrl: {
url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==",
},
},
],
} as UserChatMessage;
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
role: "user",
content: [
{ text: "Look at this image:" },
{
image: {
format: "jpeg",
source: {
bytes: Buffer.from("/9j/4AAQSkZJRg==", "base64"),
it("should handle tool responses correctly", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Use a tool" } as UserChatMessage,
{
role: "assistant",
content: "",
toolCalls: [
{
id: "tool-1",
type: "function",
function: {
name: "test_tool",
arguments: '{"arg":"value"}',
},
},
},
],
],
},
{
role: "tool",
content: "Tool result",
toolCallId: "tool-1",
},
];
const availableTools = new Set(["test_tool"]);
const converted = bedrock["_convertMessages"](messages, availableTools);
expect(converted).toEqual([
{ role: "user", content: [{ text: "Use a tool" }] },
{
role: "assistant",
content: [
{
toolUse: {
toolUseId: "tool-1",
name: "test_tool",
input: { arg: "value" },
},
},
],
},
{
role: "user",
content: [
{
toolResult: {
toolUseId: "tool-1",
content: [{ text: "Tool result" }],
},
},
],
},
]);
});
it("should handle tool calls with unavailable tools as text", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Use a tool" } as UserChatMessage,
{
role: "assistant",
content: "",
toolCalls: [
{
id: "tool-1",
type: "function",
function: {
name: "unavailable_tool",
arguments: '{"arg":"value"}',
},
},
],
},
];
// Empty set means no tools are available
const availableTools = new Set<string>();
const converted = bedrock["_convertMessages"](messages, availableTools);
expect(converted).toEqual([
{ role: "user", content: [{ text: "Use a tool" }] },
{
role: "assistant",
content: [
{
text: expect.stringContaining("Assistant tool call:"),
},
],
},
]);
});
it("should handle thinking messages correctly", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Think about this" } as UserChatMessage,
{ role: "thinking", content: "I am thinking about the solution" },
{ role: "assistant", content: "Here's my answer" },
];
const availableTools = new Set<string>();
const converted = bedrock["_convertMessages"](messages, availableTools);
expect(converted).toEqual([
{ role: "user", content: [{ text: "Think about this" }] },
{
role: "assistant",
content: [
{
reasoningContent: {
reasoningText: {
text: "I am thinking about the solution",
signature: undefined,
},
},
},
{ text: "Here's my answer" },
],
},
]);
});
it("should handle redacted thinking messages", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Think about this" } as UserChatMessage,
{
role: "thinking",
content: "",
redactedThinking: "redacted-content-bytes",
},
{ role: "assistant", content: "Here's my answer" },
];
const availableTools = new Set<string>();
const converted = bedrock["_convertMessages"](messages, availableTools);
expect(converted).toEqual([
{ role: "user", content: [{ text: "Think about this" }] },
{
role: "assistant",
content: [
{
reasoningContent: {
redactedContent: expect.any(Uint8Array),
},
},
{ text: "Here's my answer" },
],
},
]);
// Check that the Uint8Array contains the expected bytes
const redactedContent =
converted[1].content?.[0].reasoningContent?.redactedContent;
expect(redactedContent).toBeInstanceOf(Uint8Array);
expect(Buffer.from(redactedContent!).toString()).toBe(
"redacted-content-bytes",
);
});
it("should convert multimodal content correctly", () => {
const messages: ChatMessage[] = [
{
role: "user",
content: [
{ type: "text", text: "Look at this image:" },
{
type: "imageUrl",
imageUrl: {
url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==",
},
},
],
} as UserChatMessage,
];
const availableTools = new Set<string>();
const converted = bedrock["_convertMessages"](messages, availableTools);
expect(converted).toEqual([
{
role: "user",
content: [
{ text: "Look at this image:" },
{
image: {
format: "jpeg",
source: {
bytes: expect.any(Uint8Array),
},
},
},
],
},
]);
// Check that the image bytes were processed correctly
const imageBytes = converted[0].content?.[1].image?.source?.bytes;
expect(imageBytes).toBeInstanceOf(Uint8Array);
expect(Buffer.from(imageBytes!).toString("base64")).toBe(
"/9j/4AAQSkZJRg==",
);
});
it("should add cache points for prompt caching when needed", () => {
// Create a test instance with caching behavior enabled
const bedrockWithCaching = new TestBedrock({
apiKey: "test-key",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
region: "us-east-1",
});
// Set caching behavior
bedrockWithCaching.cacheBehavior = {
cacheConversation: true,
cacheSystemMessage: true,
};
const messages: ChatMessage[] = [
{ role: "system", content: "You are a helpful assistant" },
{ role: "user", content: "First message" } as UserChatMessage,
{ role: "assistant", content: "First response" },
{ role: "user", content: "Second message" } as UserChatMessage,
];
const availableTools = new Set<string>();
const converted = bedrockWithCaching["_convertMessages"](
messages,
availableTools,
);
// The last two user messages should have cache points
// But we're not testing the system message here since it's handled separately
expect(converted.length).toBe(3);
expect(converted[0].role).toBe("user");
expect(converted[0].content?.some((block) => block.cachePoint)).toBe(
true,
);
expect(converted[1].role).toBe("assistant");
expect(converted[2].role).toBe("user");
expect(converted[2].content?.some((block) => block.cachePoint)).toBe(
true,
);
// Verify that text content includes a cache ID suffix
const userMessageText = converted[0].content?.[0].text;
expect(userMessageText).toMatch(/First message.+/);
});
});
});

View file

@ -1,8 +1,10 @@
import {
BedrockRuntimeClient,
ContentBlock,
ConversationRole,
ConverseStreamCommand,
ConverseStreamCommandOutput,
ImageFormat,
InvokeModelCommand,
Message,
ToolConfiguration,
@ -14,6 +16,7 @@ import {
Chunk,
CompletionOptions,
LLMOptions,
MessageContent,
} from "../../index.js";
import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
@ -289,8 +292,8 @@ class Bedrock extends BaseLLM {
const systemMessage = stripImages(
messages.find((m) => m.role === "system")?.content ?? "",
);
const convertedMessages = this._convertMessages(messages);
// Prompt and system message caching settings
const shouldCacheSystemMessage =
(!!systemMessage && this.cacheBehavior?.cacheSystemMessage) ||
this.completionOptions.promptCaching;
@ -298,9 +301,7 @@ class Bedrock extends BaseLLM {
shouldCacheSystemMessage ||
this.cacheBehavior?.cacheConversation ||
this.completionOptions.promptCaching;
const shouldCacheToolsConfig = this.completionOptions.promptCaching;
// Add header for prompt caching
if (enablePromptCaching) {
this.requestOptions.headers = {
...this.requestOptions.headers,
@ -308,30 +309,37 @@ class Bedrock extends BaseLLM {
};
}
// First get tools
const supportsTools =
(this.capabilities?.tools ||
PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ??
false;
let toolConfig =
supportsTools && options.tools
? ({
tools: options.tools.map((tool) => ({
toolSpec: {
name: tool.function.name,
description: tool.function.description,
inputSchema: {
json: tool.function.parameters,
},
},
})),
} as ToolConfiguration)
: undefined;
if (toolConfig?.tools && shouldCacheToolsConfig) {
toolConfig.tools.push({ cachePoint: { type: "default" } });
let toolConfig: undefined | ToolConfiguration = undefined;
const availableTools = new Set<string>();
if (supportsTools && options.tools && options.tools.length > 0) {
toolConfig = {
tools: options.tools.map((tool) => ({
toolSpec: {
name: tool.function.name,
description: tool.function.description,
inputSchema: {
json: tool.function.parameters,
},
},
})),
} as ToolConfiguration;
const shouldCacheToolsConfig = this.completionOptions.promptCaching;
if (shouldCacheToolsConfig) {
toolConfig.tools!.push({ cachePoint: { type: "default" } });
}
options.tools.forEach((tool) => {
availableTools.add(tool.function.name);
});
}
const convertedMessages = this._convertMessages(messages, availableTools);
return {
modelId: options.model,
system: systemMessage
@ -368,167 +376,236 @@ class Bedrock extends BaseLLM {
};
}
private _convertMessage(
message: ChatMessage,
addCaching: boolean = false,
): Message | null {
// Handle system messages explicitly
if (message.role === "system") {
return null;
}
/*
Converts the messages to the format expected by the Bedrock API.
*/
private _convertMessages(
messages: ChatMessage[],
availableTools: Set<string>,
): Message[] {
let currentRole: "user" | "assistant" = "user";
let currentBlocks: ContentBlock[] = [];
const cachePoint = addCaching
? { cachePoint: { type: "default" } }
: undefined;
// Tool response handling
if (message.role === "tool") {
return {
role: "user",
content: [
{
toolResult: {
toolUseId: message.toolCallId,
content: [
{
text: message.content || "",
},
],
},
},
],
};
}
// Tool calls handling
if (message.role === "assistant" && message.toolCalls) {
return {
role: "assistant",
content: message.toolCalls.map((toolCall) => ({
toolUse: {
toolUseId: toolCall.id,
name: toolCall.function?.name,
input: safeParseToolCallArgs(toolCall),
},
})),
};
}
if (message.role === "thinking") {
if (message.redactedThinking) {
const content: ContentBlock.ReasoningContentMember = {
reasoningContent: {
redactedContent: new Uint8Array(
Buffer.from(message.redactedThinking),
),
},
};
return {
role: "assistant",
content: [content],
};
} else {
const content: ContentBlock.ReasoningContentMember = {
reasoningContent: {
reasoningText: {
text: (message.content as string) || "",
signature: message.signature,
},
},
};
return {
role: "assistant",
content: [content],
};
const converted: Message[] = [];
const pushCurrentMessage = () => {
if (currentBlocks.length === 0 && converted.length > 1) {
throw new Error(
`Bedrock: no content in ${currentRole} message before conversational turn change`,
);
}
}
// Standard text message
if (typeof message.content === "string") {
if (addCaching) {
message.content += getSecureID();
if (currentBlocks.length > 0) {
converted.push({
role: currentRole,
content: currentBlocks,
});
}
const content: any[] = [{ text: message.content }];
if (addCaching) {
content.push({ cachePoint: { type: "default" } });
}
return {
role: message.role,
content,
};
}
currentBlocks = [];
};
// Improved multimodal content handling
if (Array.isArray(message.content)) {
const content: any[] = [];
const nonSystemMessages = messages.filter((m) => m.role !== "system");
const hasAddedToolCallIds = new Set<string>();
// Process all parts first
message.content.forEach((part) => {
if (part.type === "text") {
if (addCaching) {
part.text += getSecureID();
for (let idx = 0; idx < nonSystemMessages.length; idx++) {
const message = nonSystemMessages[idx];
if (message.role === "user" || message.role === "tool") {
// Detect conversational turn change
if (currentRole !== ConversationRole.USER) {
pushCurrentMessage();
currentRole = ConversationRole.USER;
}
// USER messages:
// Non-empty user message content is converted to "text" and "image" blocks
// If ANY user message part is cached, we add a single cache point block when we push the message
if (message.role === "user") {
const trimmedContent =
typeof message.content === "string"
? message.content.trim()
: message.content;
if (trimmedContent) {
currentBlocks.push(
...this._convertMessageContentToBlocks(trimmedContent),
);
}
content.push({ text: part.text });
}
// TOOL messages:
// Tool messages are represented by "toolResult" blocks
// toolResult blocks must follow valid toolUse blocks (which also verifies that the tool name is present in toolConfig)
// If it doesn't, we convert it to a text block
else if (message.role === "tool") {
const trimmedContent = message.content.trim() || "No tool output";
if (hasAddedToolCallIds.has(message.toolCallId)) {
currentBlocks.push({
toolResult: {
toolUseId: message.toolCallId,
content: [
{
text: trimmedContent,
},
],
},
});
} else {
currentBlocks.push({
text: `Tool call output for Tool Call ID ${message.toolCallId}:\n\n${trimmedContent}`,
});
}
}
} else if (message.role === "assistant" || message.role === "thinking") {
// Detect conversational turn change
if (currentRole !== ConversationRole.ASSISTANT) {
pushCurrentMessage();
currentRole = ConversationRole.ASSISTANT;
}
// ASSISTANT messages:
// Non-empty assistant message content is converted to "text" and "image" blocks
if (message.role === "assistant") {
const trimmedContent =
typeof message.content === "string"
? message.content.trim()
: message.content;
if (trimmedContent) {
currentBlocks.push(
...this._convertMessageContentToBlocks(trimmedContent),
);
}
// TOOL CALLS:
// Tool calls are represented by "toolUse" blocks
// Each tool call must have an id and a function name
// The function name must match one of the available tools
// Otherwise, we will convert it to a text block (e.g. Chat mode will pass no tools)
if (message.toolCalls) {
for (const toolCall of message.toolCalls) {
if (toolCall.id && toolCall.function?.name) {
if (availableTools.has(toolCall.function.name)) {
currentBlocks.push({
toolUse: {
toolUseId: toolCall.id,
name: toolCall.function.name,
input: safeParseToolCallArgs(toolCall),
},
});
hasAddedToolCallIds.add(toolCall.id);
} else {
const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`;
currentBlocks.push({
text: toolCallText,
});
}
} else {
console.warn(
`Bedrock: tool call missing id or name, skipping tool call: ${JSON.stringify(toolCall)}`,
);
continue;
}
}
}
} else if (message.role === "thinking") {
// THINKING:
// Thinking messages are represented by "reasoningContent" blocks which can have redacted content or reasoning content
if (message.redactedThinking) {
const block: ContentBlock.ReasoningContentMember = {
reasoningContent: {
redactedContent: new Uint8Array(
Buffer.from(message.redactedThinking),
),
},
};
currentBlocks.push(block);
} else {
const block: ContentBlock.ReasoningContentMember = {
reasoningContent: {
reasoningText: {
text: (message.content as string) || "",
signature: message.signature,
},
},
};
currentBlocks.push(block);
}
}
}
}
if (currentBlocks.length > 0) {
pushCurrentMessage();
}
// If caching is enabled, we add cache_control parameter to the last two user messages
// The second-to-last because it retrieves potentially already cached contents,
// The last one because we want it cached for later retrieval.
// See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
if (this.cacheBehavior?.cacheConversation) {
this._addCachingToLastTwoUserMessages(converted);
}
return converted;
}
private _addCachingToLastTwoUserMessages(converted: Message[]) {
let numCached = 0;
for (let i = converted.length - 1; i >= 0; i--) {
const message = converted[i];
if (message.role === "user") {
message.content?.forEach((block) => {
if (block.text) {
block.text += getSecureID();
}
});
message.content?.push({ cachePoint: { type: "default" } });
numCached++;
}
if (numCached === 2) {
break;
}
}
}
// Converts Continue message content (string/parts) to Bedrock ContentBlock format.
// Unsupported/problematic image formats are skipped with a warning.
private _convertMessageContentToBlocks(
content: MessageContent,
): ContentBlock[] {
const blocks: ContentBlock[] = [];
if (typeof content === "string") {
blocks.push({ text: content });
} else {
for (const part of content) {
if (part.type === "text") {
blocks.push({ text: part.text });
} else if (part.type === "imageUrl" && part.imageUrl) {
try {
const [mimeType, base64Data] = part.imageUrl.url.split(",");
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
content.push({
image: {
format,
source: {
bytes: Buffer.from(base64Data, "base64"),
if (
format === ImageFormat.JPEG ||
format === ImageFormat.PNG ||
format === ImageFormat.WEBP ||
format === ImageFormat.GIF
) {
blocks.push({
image: {
format,
source: {
bytes: Uint8Array.from(Buffer.from(base64Data, "base64")),
},
},
},
});
});
} else {
console.warn(
`Bedrock: skipping unsupported image part format: ${format}`,
part,
);
}
} catch (error) {
console.warn(`Failed to process image: ${error}`);
console.warn("Bedrock: failed to process image part", error, part);
}
}
});
// Add cache point as a separate block at the end if needed
if (addCaching && content.length > 0) {
content.push({ cachePoint: { type: "default" } });
}
return {
role: message.role,
content,
} as Message;
}
return null;
}
private _convertMessages(messages: ChatMessage[]): any[] {
const filteredmessages = messages.filter(
(m) => m.role !== "system" && !!m.content,
);
const lastTwoUserMsgIndices = filteredmessages
.map((msg, index) => (msg.role === "user" ? index : -1))
.filter((index) => index !== -1)
.slice(-2);
const converted = filteredmessages
.map((message, filteredMsgIdx) => {
// Add cache_control parameter to the last two user messages
// The second-to-last because it retrieves potentially already cached contents,
// The last one because we want it cached for later retrieval.
// See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
const addCaching =
this.cacheBehavior?.cacheConversation &&
lastTwoUserMsgIndices.includes(filteredMsgIdx);
try {
return this._convertMessage(message, addCaching);
} catch (error) {
console.error(`Failed to convert message: ${error}`);
return null;
}
})
.filter(Boolean);
return converted;
return blocks;
}
private async _getCredentials() {

View file

@ -8,7 +8,7 @@ import {
LLMOptions,
} from "../..";
import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../defaultSystemMessages";
import { BaseLLM } from "../index";
import Anthropic from "./Anthropic";
import Asksage from "./Asksage";

View file

@ -327,27 +327,36 @@ export const getApplicableRules = (
export const getSystemMessageWithRules = ({
baseSystemMessage,
userMessage,
rules,
availableRules,
contextItems,
rulePolicies = {},
}: {
baseSystemMessage?: string;
userMessage: UserChatMessage | ToolResultChatMessage | undefined;
rules: RuleWithSource[];
availableRules: RuleWithSource[];
contextItems: ContextItemWithId[];
rulePolicies?: RulePolicies;
}) => {
const applicableRules = getApplicableRules(
}): {
systemMessage: string;
appliedRules: RuleWithSource[];
} => {
const appliedRules = getApplicableRules(
userMessage,
rules,
availableRules,
contextItems,
rulePolicies,
);
let systemMessage = baseSystemMessage ?? "";
for (const rule of applicableRules) {
systemMessage += `\n\n${rule.rule}`;
for (const rule of appliedRules) {
if (systemMessage) {
systemMessage += "\n\n";
}
systemMessage += rule.rule;
}
return systemMessage;
return {
systemMessage,
appliedRules,
};
};

View file

@ -22,6 +22,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"gpt-4",
"o3",
"gemini",
"claude-opus-4",
].some((part) => model.toLowerCase().startsWith(part));
},
anthropic: (model) => {
@ -32,6 +33,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"claude-3-7",
"claude-3.7",
"claude-sonnet-4",
"claude-opus-4",
].some((part) => model.toLowerCase().startsWith(part))
) {
return true;
@ -86,15 +88,14 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
);
},
bedrock: (model) => {
// For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7
if (
model.toLowerCase().includes("sonnet") &&
[
"claude-3-5",
"claude-3.5",
"claude-3-7",
"claude-3.7",
"claude-3-5-sonnet",
"claude-3.5-sonnet",
"claude-3-7-sonnet",
"claude-3.7-sonnet",
"claude-sonnet-4",
"claude-opus-4",
].some((part) => model.toLowerCase().includes(part))
) {
return true;
@ -179,7 +180,9 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
return false;
},
deepseek: (model) => {
if (model !== "deepseek-reasoner") {
// https://api-docs.deepseek.com/quick_start/pricing
// https://api-docs.deepseek.com/guides/function_calling
if (model === "deepseek-reasoner" || model === "deepseek-chat") {
return true;
}

View file

@ -1,9 +1,86 @@
import { DEFAULT_PROMPTS_FOLDER_V1, DEFAULT_PROMPTS_FOLDER_V2 } from ".";
import { DEFAULT_PROMPTS_FOLDER_V1 } from ".";
import { IDE } from "..";
import { walkDir } from "../indexing/walkDir";
import { readAllGlobalPromptFiles } from "../util/paths";
import { joinPathsToUri } from "../util/uri";
// The hardcoded init prompt content
const INIT_PROMPT_CONTENT = `name: Init
description: Initialize Codebase
---
You are an expert development assistant. Your task is to create a comprehensive CONTINUE.md project guide for the user's codebase to help them and their team better understand and work with the project.
## Step 1: Check Required Tools
First, verify that you have access to the necessary tools:
- builtin_file_glob_search: To discover project files
- builtin_read_file: To analyze file contents
- builtin_ls: To explore directory structure
- builtin_create_new_file: To generate the CONTINUE.md file
If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding.
## Step 2: Project Analysis
Analyze the project structure and key files to understand:
- The programming languages and frameworks used
- The overall architecture and organization
- Key components and their responsibilities
- Important configuration files
- Build/deployment system
## Step 3: Generate CONTINUE.md
Create a comprehensive CONTINUE.md file in the .continue/rules/ directory with the following sections:
1. **Project Overview**
- Brief description of the project's purpose
- Key technologies used
- High-level architecture
2. **Getting Started**
- Prerequisites (required software, dependencies)
- Installation instructions
- Basic usage examples
- Running tests
3. **Project Structure**
- Overview of main directories and their purpose
- Key files and their roles
- Important configuration files
4. **Development Workflow**
- Coding standards or conventions
- Testing approach
- Build and deployment process
- Contribution guidelines
5. **Key Concepts**
- Domain-specific terminology
- Core abstractions
- Design patterns used
6. **Common Tasks**
- Step-by-step guides for frequent development tasks
- Examples of common operations
7. **Troubleshooting**
- Common issues and their solutions
- Debugging tips
8. **References**
- Links to relevant documentation
- Important resources
Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification.
## Step 4: Finalize
After creating the .continue/rules/CONTINUE.md file, provide a summary of what you've created and remind the user to:
1. Review and edit the file as needed
2. Commit it to their repository to share with their team
3. Explain that Continue will automatically load this file into context when working with the project
Also inform the user that they can create additional rules.md files in subdirectories for more specific documentation related to those components.`;
export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
export async function getPromptFilesFromDir(
ide: IDE,
dir: string,
@ -57,8 +134,17 @@ export async function getAllPromptFiles(
// Also read from ~/.continue/.prompts
promptFiles.push(...readAllGlobalPromptFiles());
// Add hardcoded init prompt
promptFiles.push({
path: "builtin:/init.prompt",
content: INIT_PROMPT_CONTENT,
});
return await Promise.all(
promptFiles.map(async (file) => {
if (file.path.startsWith("builtin:")) {
return file;
}
const content = await ide.readFile(file.path);
return { path: file.path, content };
}),

View file

@ -1,23 +1,23 @@
export enum BuiltInToolNames {
ReadFile = "builtin_read_file",
EditExistingFile = "builtin_edit_existing_file",
SearchAndReplaceInFile = "builtin_search_and_replace_in_file",
ReadCurrentlyOpenFile = "builtin_read_currently_open_file",
CreateNewFile = "builtin_create_new_file",
RunTerminalCommand = "builtin_run_terminal_command",
GrepSearch = "builtin_grep_search",
FileGlobSearch = "builtin_file_glob_search",
SearchWeb = "builtin_search_web",
ViewDiff = "builtin_view_diff",
LSTool = "builtin_ls",
CreateRuleBlock = "builtin_create_rule_block",
RequestRule = "builtin_request_rule",
FetchUrlContent = "builtin_fetch_url_content",
CodebaseTool = "builtin_codebase",
ReadFile = "read_file",
EditExistingFile = "edit_existing_file",
SearchAndReplaceInFile = "search_and_replace_in_file",
ReadCurrentlyOpenFile = "read_currently_open_file",
CreateNewFile = "create_new_file",
RunTerminalCommand = "run_terminal_command",
GrepSearch = "grep_search",
FileGlobSearch = "file_glob_search",
SearchWeb = "search_web",
ViewDiff = "view_diff",
LSTool = "ls",
CreateRuleBlock = "create_rule_block",
RequestRule = "request_rule",
FetchUrlContent = "fetch_url_content",
CodebaseTool = "codebase",
// excluded from allTools for now
ViewRepoMap = "builtin_view_repo_map",
ViewSubdirectory = "builtin_view_subdirectory",
ViewRepoMap = "view_repo_map",
ViewSubdirectory = "view_subdirectory",
}
export const BUILT_IN_GROUP_NAME = "Built-In";

View file

@ -1,5 +1,6 @@
import { ContextItem, Tool, ToolCall, ToolExtras } from "..";
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
import { DataLogger } from "../data/log";
import { canParseUrl } from "../util/url";
import { BuiltInToolNames } from "./builtIn";
@ -172,6 +173,26 @@ async function callBuiltInTool(
}
}
function logToolUsage(
toolCall: ToolCall,
args: Record<string, any>,
contextItems: ContextItem[],
success: boolean,
) {
void DataLogger.getInstance().logDevData({
name: "toolUsage",
data: {
toolCallId: toolCall.id,
functionName: toolCall.function.name,
functionArgs: toolCall.function.arguments,
toolCallArgs: args,
parsedArgs: args,
output: contextItems,
succeeded: success,
},
});
}
// Handles calls for core/non-client tools
// Returns an error context item if the tool call fails
// Note: Edit tool is handled on client
@ -193,6 +214,7 @@ export async function callTool(
item.icon = tool.faviconUrl;
});
}
logToolUsage(toolCall, args, contextItems, true);
return {
contextItems,
errorMessage: undefined,
@ -202,6 +224,7 @@ export async function callTool(
if (e instanceof Error) {
errorMessage = e.message;
}
logToolUsage(toolCall, {}, [], false);
return {
contextItems: [],
errorMessage,

View file

@ -1,5 +1,5 @@
import { Tool } from "../..";
import { EDIT_CODE_INSTRUCTIONS } from "../../llm/constructMessages";
import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export interface EditToolArgs {

View file

@ -1,6 +1,6 @@
export function findLastIndex(
arr: any[],
criterion: (item: any) => boolean,
export function findLastIndex<T = any>(
arr: T[],
criterion: (item: T) => boolean,
): number {
let lastIndex = -1;

View file

@ -28,14 +28,12 @@ In [Chat mode](../chat/how-to-use-it.md), tools are **not** included in the requ
Continue includes several built-in tools which provide the model access to IDE functionality:
- **Read file** (`builtin_read_file`): read the contents of a file within the project
- **Read currently open file** (`builtin_read_currently_open_file`): read the contents of the currently open file
- **Create new file** (`builtin_create_new_file`): Create a new file within the project, with path and contents specified by the model
- **Exact search** (`builtin_exact_search`): perform a `ripgrep` search within the project
- **Glob search** (`builtin_file_glob_search`): perform a glob search on files in the project. Currently limits to 100 output and warns the Agent if limit reached.
- **Run terminal command** (`builtin_run_terminal_command`): run a terminal command from the workspace root
- **Search web** (`builtin_search_web`): Perform a web search to get top results
- **View diff** (`builtin_view_diff`): View the current working git diff
- **View repo map** (`builtin_view_repo_map`): request a copy of the repository map—same as the [Repo Map Context Provider](../customize/context-providers.mdx#repository-map)
- **View subdirectory** (`builtin_view_subdirectory`): request a copy of a repo map for a specific directory within the project
- **Create Rule Block** (`builtin_create_rule_block`): creates a new rule block in `.continue/rules` based on the contents of the conversation
- **Read file** (`read_file`): read the contents of a file within the project
- **Read currently open file** (`read_currently_open_file`): read the contents of the currently open file
- **Create new file** (`create_new_file`): Create a new file within the project, with path and contents specified by the model
- **Exact search** (`exact_search`): perform a `ripgrep` search within the project
- **Glob search** (`file_glob_search`): perform a glob search on files in the project. Currently limits to 100 output and warns the Agent if limit reached.
- **Run terminal command** (`run_terminal_command`): run a terminal command from the workspace root
- **Search web** (`search_web`): Perform a web search to get top results
- **View diff** (`view_diff`): View the current working git diff
- **Create Rule Block** (`create_rule_block`): creates a new rule block in `.continue/rules` based on the contents of the conversation

View file

@ -48,7 +48,7 @@ Rules can be added locally using the "Add Rules" button while viewing the Local
![add local rules button](/img/add-local-rules.png)
:::info Automatically create local rule blocks
When in Agent mode, you can prompt the agent to create a rule for you using the `builtin_create_rule_block` tool if enabled.
When in Agent mode, you can prompt the agent to create a rule for you using the `create_rule_block` tool if enabled.
For example, you can say "Create a rule for this", and a rule will be created for you in `.continue/rules` based on your conversation.
:::

View file

@ -192,11 +192,8 @@ tasks {
}
runIde {
// Open the `manual-testing-sandbox` directory and the specific file on start
args = listOf(
"${rootProject.projectDir.parentFile.parentFile}/manual-testing-sandbox",
"${rootProject.projectDir.parentFile.parentFile}/manual-testing-sandbox/test.kt"
).map { file(it).absolutePath }
val dir = "${rootProject.projectDir.parentFile.parentFile.absolutePath}/manual-testing-sandbox"
args = listOf(dir, "$dir/test.kt")
}
test {

View file

@ -0,0 +1,10 @@
package com.github.continuedev.continueintellijextension
import com.intellij.openapi.util.IconLoader
object Icons {
@JvmField
val Continue = IconLoader.getIcon("/icons/continue.svg", javaClass)
@JvmField
val Close = IconLoader.getIcon("/icons/close.svg", javaClass)
}

View file

@ -1,26 +0,0 @@
package com.github.continuedev.continueintellijextension
import com.intellij.DynamicBundle
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
@NonNls
private const val BUNDLE = "messages.MyBundle"
object MyBundle : DynamicBundle(BUNDLE) {
@JvmStatic
fun message(
@PropertyKey(resourceBundle = BUNDLE) key: String,
vararg params: Any
) =
getMessage(key, *params)
@Suppress("unused")
@JvmStatic
fun messagePointer(
@PropertyKey(resourceBundle = BUNDLE) key: String,
vararg params: Any
) =
getLazyMessage(key, *params)
}

View file

@ -1,5 +1,6 @@
package com.github.continuedev.continueintellijextension.autocomplete
import com.github.continuedev.continueintellijextension.Icons
import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.intellij.openapi.Disposable
@ -50,7 +51,7 @@ class AutocompleteSpinnerWidget(project: Project) : EditorBasedWidget(project),
}
override fun getIcon(): Icon = if (isLoading) animatedIcon else
IconLoader.getIcon("/icons/continue.svg", javaClass)
Icons.Continue
fun setLoading(loading: Boolean) {
isLoading = loading

View file

@ -41,11 +41,12 @@ class MessageTypes {
"getTerminalContents",
"showToast",
"openUrl",
"isWorkspaceRemote",
// These only come from the GUI for now but should be here to prevent confusion
"toggleDevTools",
"showTutorial",
// These are jetbrains only and only come from the GUI for now
// But again including for consistency
"copyText",

View file

@ -43,7 +43,9 @@ class CoreMessenger(
val message =
gson.toJson(mapOf("messageId" to id, "messageType" to messageType, "data" to data))
responseListeners[id] = onResponse
write(message)
coroutineScope.launch(Dispatchers.IO) {
write(message)
}
}
private fun handleMessage(json: String) {

View file

@ -202,6 +202,11 @@ class IdeProtocolClient(
respond(contents)
}
"isWorkspaceRemote" -> {
val isRemote = ide.isWorkspaceRemote()
respond(isRemote)
}
"saveFile" -> {
val params = Gson().fromJson(
dataElement.toString(),
@ -475,7 +480,7 @@ class IdeProtocolClient(
val editor = EditorUtils.getEditor(project)
val rif = editor?.getHighlightedRIF() ?: return
val serializedRif = com.github.continuedev.continueintellijextension.RangeInFileWithContents(
val serializedRif = com.github.continuedev.continueintellijextension.RangeInFileWithContents(
filepath = rif.filepath,
range = rif.range,
contents = rif.contents

View file

@ -18,6 +18,7 @@ import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.EDT
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.impl.DocumentMarkupModel
import com.intellij.openapi.extensions.PluginId
@ -294,23 +295,26 @@ class IntelliJIDE(
continuePluginService.diffManager?.showDiff(filepath, newContents, stepIndex)
}
override suspend fun getOpenFiles(): List<String> {
val fileEditorManager = FileEditorManager.getInstance(project)
return fileEditorManager.openFiles.mapNotNull { it.toUriOrNull() }.toList()
}
override suspend fun getCurrentFile(): Map<String, Any>? {
val fileEditorManager = FileEditorManager.getInstance(project)
val editor = fileEditorManager.selectedTextEditor
val virtualFile = editor?.document?.let { FileDocumentManager.getInstance().getFile(it) }
return virtualFile?.toUriOrNull()?.let {
mapOf(
"path" to it,
"contents" to editor.document.text,
"isUntitled" to false
)
override suspend fun getOpenFiles(): List<String> =
withContext(Dispatchers.EDT) {
FileEditorManager.getInstance(project).openFiles
.mapNotNull { it.toUriOrNull() }
.toList()
}
override suspend fun getCurrentFile(): Map<String, Any>? =
withContext(Dispatchers.EDT) {
val fileEditorManager = FileEditorManager.getInstance(project)
val document = fileEditorManager.selectedTextEditor?.document
val virtualFile = document?.let { FileDocumentManager.getInstance().getFile(it) }
virtualFile?.toUriOrNull()?.let {
mapOf(
"path" to it,
"contents" to document.text,
"isUntitled" to false
)
}
}
}
override suspend fun getPinnedFiles(): List<String> {
// Returning open files for now as per existing code
@ -525,10 +529,9 @@ class IntelliJIDE(
}
val deferred = CompletableDeferred<String?>()
val icon = IconLoader.getIcon("/icons/continue.svg", javaClass)
val notification = NotificationGroupManager.getInstance().getNotificationGroup("Continue")
.createNotification(message, notificationType).setIcon(icon)
.createNotification(message, notificationType).setIcon(Icons.Continue)
val buttonTexts = otherParams.filterIsInstance<String>().toTypedArray()
buttonTexts.forEach { buttonText ->

View file

@ -1,5 +1,6 @@
package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.Icons
import com.github.continuedev.continueintellijextension.`continue`.GetTheme
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
@ -357,8 +358,7 @@ class CustomPanel(
}
private fun createCloseButton(): JComponent {
val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass)
return JLabel(closeIcon).apply {
return JLabel(Icons.Close).apply {
background = Color(0, 0, 0, 0)
border = JBUI.Borders.empty(2, 6, 2, 0)
toolTipText = "`esc` to cancel"

View file

@ -19,7 +19,7 @@
<extensions defaultExtensionNs="com.intellij">
<editorFactoryListener
implementation="com.github.continuedev.continueintellijextension.autocomplete.AutocompleteEditorListener"/>
<toolWindow id="Continue" anchor="right" icon="/tool-window-icon.svg"
<toolWindow id="Continue" anchor="right" icon="com.github.continuedev.continueintellijextension.Icons.Continue"
factoryClass="com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory"/>
<projectService id="ContinuePluginService"
serviceImplementation="com.github.continuedev.continueintellijextension.services.ContinuePluginService"/>
@ -37,11 +37,6 @@
<actionPromoter order="last"
implementation="com.github.continuedev.continueintellijextension.actions.ContinueActionPromote"/>
<errorHandler implementation="com.github.continuedev.continueintellijextension.error.ContinueErrorSubmitter"/>
</extensions>
<resource-bundle>messages.MyBundle</resource-bundle>
<extensions defaultExtensionNs="com.intellij">
<postStartupActivity
implementation="com.github.continuedev.continueintellijextension.activities.ContinuePluginStartupActivity"/>
<applicationConfigurable

View file

@ -0,0 +1,4 @@
<svg width="13" height="13" viewBox="0 0 13 13" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.4742 1.6668L9.77141 2.88516L11.5477 5.95951C11.5607 5.98283 11.5685 6.01135 11.5685 6.03728C11.5685 6.0632 11.5607 6.09172 11.5477 6.11505L9.77141 9.19199L10.4742 10.4104L13 6.03728L10.4742 1.66421V1.6668ZM9.4991 2.72702L10.2019 1.50867H8.79634L8.09357 2.72702H9.5017H9.4991ZM8.09097 3.0433L9.73249 5.88173H11.138L9.4991 3.0433H8.09097ZM9.4991 9.03645L11.138 6.19542H9.73249L8.09097 9.03645H9.4991ZM8.09097 9.35273L8.79374 10.5659H10.1993L9.4965 9.35273H8.08837H8.09097ZM3.32716 10.8666C3.29864 10.8666 3.27271 10.8588 3.24939 10.8458C3.22599 10.8329 3.20527 10.8122 3.19227 10.7889L1.41332 7.71183H0.00777705L2.53362 12.0824H7.58267L6.87991 10.8666H3.32976H3.32716ZM7.15222 10.7085L7.85498 11.9242L8.55775 10.7059L7.85498 9.48755L7.15222 10.7059V10.7085ZM7.58267 9.33201H4.30484L3.60207 10.5503H6.87991L7.58267 9.33201ZM4.02992 9.17647L2.38841 6.33536L1.68562 7.55376L3.32716 10.3948L4.02992 9.17647ZM0.00518489 7.39562H1.41073L2.1135 6.17729H0.71055L0.00518489 7.39562ZM3.18454 1.29611C3.19746 1.27278 3.21826 1.25205 3.24159 1.23908C3.26491 1.22612 3.29344 1.21834 3.31936 1.21834H6.87471L7.57747 0H2.52582L0 4.37305H1.40555L3.17934 1.29871L3.18454 1.29611ZM2.1135 5.90506L1.41073 4.68673H0.00518489L0.707957 5.90506H2.1135ZM3.32196 1.69013L1.68303 4.52859L2.38581 5.74699L4.02472 2.90848L3.32196 1.69013ZM6.87731 1.532H3.59427L4.29704 2.75034H7.58007L6.87731 1.532ZM7.85498 2.5922L8.55515 1.37647L7.85498 0.158126L7.15222 1.37388L7.85498 2.5922Z"
fill="#CED0D6"/>
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

View file

@ -1,3 +0,0 @@
projectService=Project service: {0}
randomLabel=The random number is: {0}
shuffle=Shuffle

View file

@ -1,3 +0,0 @@
<svg width="13" height="13" viewBox="0 0 13 13" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.4742 1.6668L9.77141 2.88516L11.5477 5.95951C11.5607 5.98283 11.5685 6.01135 11.5685 6.03728C11.5685 6.0632 11.5607 6.09172 11.5477 6.11505L9.77141 9.19199L10.4742 10.4104L13 6.03728L10.4742 1.66421V1.6668ZM9.4991 2.72702L10.2019 1.50867H8.79634L8.09357 2.72702H9.5017H9.4991ZM8.09097 3.0433L9.73249 5.88173H11.138L9.4991 3.0433H8.09097ZM9.4991 9.03645L11.138 6.19542H9.73249L8.09097 9.03645H9.4991ZM8.09097 9.35273L8.79374 10.5659H10.1993L9.4965 9.35273H8.08837H8.09097ZM3.32716 10.8666C3.29864 10.8666 3.27271 10.8588 3.24939 10.8458C3.22599 10.8329 3.20527 10.8122 3.19227 10.7889L1.41332 7.71183H0.00777705L2.53362 12.0824H7.58267L6.87991 10.8666H3.32976H3.32716ZM7.15222 10.7085L7.85498 11.9242L8.55775 10.7059L7.85498 9.48755L7.15222 10.7059V10.7085ZM7.58267 9.33201H4.30484L3.60207 10.5503H6.87991L7.58267 9.33201ZM4.02992 9.17647L2.38841 6.33536L1.68562 7.55376L3.32716 10.3948L4.02992 9.17647ZM0.00518489 7.39562H1.41073L2.1135 6.17729H0.71055L0.00518489 7.39562ZM3.18454 1.29611C3.19746 1.27278 3.21826 1.25205 3.24159 1.23908C3.26491 1.22612 3.29344 1.21834 3.31936 1.21834H6.87471L7.57747 0H2.52582L0 4.37305H1.40555L3.17934 1.29871L3.18454 1.29611ZM2.1135 5.90506L1.41073 4.68673H0.00518489L0.707957 5.90506H2.1135ZM3.32196 1.69013L1.68303 4.52859L2.38581 5.74699L4.02472 2.90848L3.32196 1.69013ZM6.87731 1.532H3.59427L4.29704 2.75034H7.58007L6.87731 1.532ZM7.85498 2.5922L8.55515 1.37647L7.85498 0.158126L7.15222 1.37388L7.85498 2.5922Z" fill="#6C707E"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

View file

@ -1,3 +0,0 @@
<svg width="13" height="13" viewBox="0 0 13 13" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M10.4742 1.6668L9.77141 2.88516L11.5477 5.95951C11.5607 5.98283 11.5685 6.01135 11.5685 6.03728C11.5685 6.0632 11.5607 6.09172 11.5477 6.11505L9.77141 9.19199L10.4742 10.4104L13 6.03728L10.4742 1.66421V1.6668ZM9.4991 2.72702L10.2019 1.50867H8.79634L8.09357 2.72702H9.5017H9.4991ZM8.09097 3.0433L9.73249 5.88173H11.138L9.4991 3.0433H8.09097ZM9.4991 9.03645L11.138 6.19542H9.73249L8.09097 9.03645H9.4991ZM8.09097 9.35273L8.79374 10.5659H10.1993L9.4965 9.35273H8.08837H8.09097ZM3.32716 10.8666C3.29864 10.8666 3.27271 10.8588 3.24939 10.8458C3.22599 10.8329 3.20527 10.8122 3.19227 10.7889L1.41332 7.71183H0.00777705L2.53362 12.0824H7.58267L6.87991 10.8666H3.32976H3.32716ZM7.15222 10.7085L7.85498 11.9242L8.55775 10.7059L7.85498 9.48755L7.15222 10.7059V10.7085ZM7.58267 9.33201H4.30484L3.60207 10.5503H6.87991L7.58267 9.33201ZM4.02992 9.17647L2.38841 6.33536L1.68562 7.55376L3.32716 10.3948L4.02992 9.17647ZM0.00518489 7.39562H1.41073L2.1135 6.17729H0.71055L0.00518489 7.39562ZM3.18454 1.29611C3.19746 1.27278 3.21826 1.25205 3.24159 1.23908C3.26491 1.22612 3.29344 1.21834 3.31936 1.21834H6.87471L7.57747 0H2.52582L0 4.37305H1.40555L3.17934 1.29871L3.18454 1.29611ZM2.1135 5.90506L1.41073 4.68673H0.00518489L0.707957 5.90506H2.1135ZM3.32196 1.69013L1.68303 4.52859L2.38581 5.74699L4.02472 2.90848L3.32196 1.69013ZM6.87731 1.532H3.59427L4.29704 2.75034H7.58007L6.87731 1.532ZM7.85498 2.5922L8.55515 1.37647L7.85498 0.158126L7.15222 1.37388L7.85498 2.5922Z" fill="#CED0D6"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

View file

@ -37,7 +37,7 @@ models:
- id: test_id
type: function
function:
name: builtin_view_diff
name: view_diff
- REPEAT_LAST_MSG
roles:
- chat

View file

@ -36,7 +36,7 @@
"id": "test_id",
"type": "function",
"function": {
"name": "builtin_view_diff"
"name": "view_diff"
}
}
]

View file

@ -304,7 +304,7 @@ describe("GUI Test", () => {
}).timeout(DEFAULT_TIMEOUT.MD * 100);
it("should call tool after approval", async () => {
await GUIActions.toggleToolPolicy(view, "builtin_view_diff", 2);
await GUIActions.toggleToolPolicy(view, "view_diff", 2);
const [messageInput] = await GUISelectors.getMessageInputFields(view);
await messageInput.sendKeys("Hello");
@ -325,7 +325,7 @@ describe("GUI Test", () => {
}).timeout(DEFAULT_TIMEOUT.XL);
it("should cancel tool", async () => {
await GUIActions.toggleToolPolicy(view, "builtin_view_diff", 2);
await GUIActions.toggleToolPolicy(view, "view_diff", 2);
const [messageInput] = await GUISelectors.getMessageInputFields(view);
await messageInput.sendKeys("Hello");

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "1.1.52",
"version": "1.1.54",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.52",
"version": "1.1.54",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.53",
"version": "1.1.54",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -355,10 +355,10 @@ const getCommandsMap: (
"continue.writeDocstringForCode": async () => {
captureCommandTelemetry("writeDocstringForCode");
streamInlineEdit(
void streamInlineEdit(
"docstring",
"Write a docstring for this code. Do not change anything about the code itself.",
true,
false,
);
},
"continue.fixCode": async () => {

2
gui/package-lock.json generated
View file

@ -116,7 +116,7 @@
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.14",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@continuedev/openai-adapters": "1.0.42",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",

View file

@ -2,6 +2,9 @@ import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { ApplyState } from "core";
import { useContext } from "react";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall";
import { cancelToolCall } from "../redux/slices/sessionSlice";
import { getMetaKeyLabel } from "../util";
import { ToolTip } from "./gui/Tooltip";
@ -20,8 +23,21 @@ export default function AcceptRejectAllButtons({
(state) => state.status === "done",
);
const ideMessenger = useContext(IdeMessengerContext);
const currentToolCallApplyState = useAppSelector(
selectCurrentToolCallApplyState,
);
const dispatch = useAppDispatch();
async function handleAcceptOrReject(status: AcceptOrRejectOutcome) {
if (
status === "rejectDiff" &&
currentToolCallApplyState?.status === "done"
) {
dispatch(
cancelToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
}
for (const { filepath = "", streamId } of pendingApplyStates) {
ideMessenger.post(status, {
filepath,

View file

@ -9,10 +9,6 @@ import { useContext, useRef } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectUseActiveFile } from "../../redux/selectors";
import {
selectCurrentToolCall,
selectCurrentToolCallApplyState,
} from "../../redux/selectors/selectCurrentToolCall";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import { setHasReasoningEnabled } from "../../redux/slices/sessionSlice";
import { exitEdit } from "../../redux/thunks/edit";
@ -53,20 +49,12 @@ function InputToolbar(props: InputToolbarProps) {
const useActiveFile = useAppSelector(selectUseActiveFile);
const isInEdit = useAppSelector((store) => store.session.isInEdit);
const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit);
const toolCallState = useAppSelector(selectCurrentToolCall);
const currentToolCallApplyState = useAppSelector(
selectCurrentToolCallApplyState,
);
const hasReasoningEnabled = useAppSelector(
(store) => store.session.hasReasoningEnabled,
);
const isEnterDisabled =
props.disabled ||
(isInEdit && codeToEdit.length === 0) ||
toolCallState?.status === "generated" ||
(currentToolCallApplyState &&
currentToolCallApplyState.status !== "closed");
props.disabled || (isInEdit && codeToEdit.length === 0);
const toolsSupported = defaultModel && modelSupportsTools(defaultModel);
@ -167,7 +155,9 @@ function InputToolbar(props: InputToolbarProps) {
/>
<ToolTip id="model-reasoning-tooltip" place="top">
Use Model Reasoning
{hasReasoningEnabled
? "Disable model reasoning"
: "Enable model reasoning"}
</ToolTip>
</HoverItem>
)}

View file

@ -2,8 +2,8 @@ import { useEffect } from "react";
import { useSelector } from "react-redux";
import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall";
import { cancelToolCall } from "../../../../redux/slices/sessionSlice";
import { callCurrentTool } from "../../../../redux/thunks/callCurrentTool";
import { cancelCurrentToolCall } from "../../../../redux/thunks/cancelCurrentToolCall";
import { isJetBrains } from "../../../../util";
import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar";
import { EditOutcomeToolbar } from "./EditOutcomeToolbar";
@ -50,7 +50,11 @@ export function LumpToolbar() {
} else if ((jetbrains ? altKey : metaKey) && event.key === "Backspace") {
event.preventDefault();
event.stopPropagation();
void dispatch(cancelCurrentToolCall());
void dispatch(
cancelToolCall({
toolCallId: toolCallState.toolCallId,
}),
);
}
};

View file

@ -1,7 +1,8 @@
import styled from "styled-components";
import { useAppDispatch } from "../../../../redux/hooks";
import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall";
import { cancelToolCall } from "../../../../redux/slices/sessionSlice";
import { callCurrentTool } from "../../../../redux/thunks/callCurrentTool";
import { cancelCurrentToolCall } from "../../../../redux/thunks/cancelCurrentToolCall";
import {
getAltKeyLabel,
getFontSize,
@ -27,6 +28,7 @@ const StopButton = styled.div`
export function PendingToolCallToolbar() {
const dispatch = useAppDispatch();
const jetbrains = isJetBrains();
const currentToolCall = useAppSelector(selectCurrentToolCall);
return (
<Container>
@ -37,7 +39,17 @@ export function PendingToolCallToolbar() {
<div className="flex gap-2 pb-0.5">
<StopButton
className="text-description"
onClick={() => dispatch(cancelCurrentToolCall())}
onClick={
currentToolCall
? () => {
dispatch(
cancelToolCall({
toolCallId: currentToolCall.toolCallId,
}),
);
}
: undefined
}
data-testid="reject-tool-call-button"
>
{/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}

View file

@ -10,7 +10,7 @@ import {
DEFAULT_AGENT_SYSTEM_MESSAGE_URL,
DEFAULT_CHAT_SYSTEM_MESSAGE,
DEFAULT_CHAT_SYSTEM_MESSAGE_URL,
} from "core/llm/constructMessages";
} from "core/llm/defaultSystemMessages";
import { useContext, useMemo } from "react";
import { useAuth } from "../../../../context/Auth";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";

View file

@ -155,22 +155,24 @@ export function createEditorConfig(options: {
for (const item of items) {
const file = item.getAsFile();
file &&
void modelSupportsImages(
modelSupportsImages(
model.provider,
model.model,
model.title,
model.capabilities,
) &&
handleImageFile(ideMessenger, file).then((resp) => {
if (!resp) return;
const [img, dataUrl] = resp;
const { schema } = view.state;
const node = schema.nodes.image.create({
src: dataUrl,
});
const tr = view.state.tr.insert(0, node);
view.dispatch(tr);
});
void handleImageFile(ideMessenger, file).then(
(resp) => {
if (!resp) return;
const [img, dataUrl] = resp;
const { schema } = view.state;
const node = schema.nodes.image.create({
src: dataUrl,
});
const tr = view.state.tr.insert(0, node);
view.dispatch(tr);
},
);
}
}
},

View file

@ -37,6 +37,7 @@ function resolveParagraph(p: JSONContent): [string, GetContextRequest[]] {
contextRequests.push({
provider:
attrs.itemType === "contextProvider" ? attrs.id : attrs.itemType!,
query: attrs.query,
});
return child.attrs?.renderInlineAs ?? child.attrs?.label;

View file

@ -123,40 +123,35 @@ export function ContextItemsPeekItem({
return (
<div
onClick={() => openContextItem(contextItem, ideMessenger)}
className="group mr-2 flex cursor-pointer items-center overflow-hidden text-ellipsis whitespace-nowrap rounded px-1.5 py-1 text-xs hover:bg-white/10"
className="mr-2 flex cursor-pointer flex-row items-center gap-1.5 whitespace-nowrap rounded px-1.5 py-1 text-xs hover:bg-white/10"
data-testid="context-items-peek-item"
>
<div className="flex w-full items-center">
{getContextItemIcon()}
<div className="flex min-w-0 flex-1 gap-2 text-xs">
<div
className={`max-w-[50%] flex-shrink-0 truncate ${isUrl ? "hover:underline" : ""}`}
>
{contextItem.name}
</div>
<div
className={`min-w-0 flex-1 overflow-hidden truncate whitespace-nowrap text-xs text-gray-400 ${isUrl ? "hover:underline" : ""}`}
onClick={
isUrl
? (e) => {
if (contextItem.uri?.value) {
e.stopPropagation();
ideMessenger.post("openUrl", contextItem.uri.value);
} else {
console.error("Couldn't open url", contextItem.uri);
}
}
: undefined
}
>
{contextItem.uri?.type === "file"
? getUriPathBasename(contextItem.description)
: contextItem.description}
</div>
</div>
{getContextItemIcon()}
<span className={`line-clamp-1 max-w-[130px] flex-shrink-0`}>
{contextItem.name}
</span>
<div
className={`group flex flex-row items-center gap-1.5 pr-1.5 text-xs text-gray-400 ${isUrl ? "hover:underline" : ""}`}
onClick={
isUrl
? (e) => {
if (contextItem.uri?.value) {
e.stopPropagation();
ideMessenger.post("openUrl", contextItem.uri.value);
} else {
console.error("Couldn't open url", contextItem.uri);
}
}
: undefined
}
>
<span className={`line-clamp-1 flex-1 break-all`}>
{contextItem.uri?.type === "file"
? getUriPathBasename(contextItem.description)
: contextItem.description}
</span>
{isUrl && (
<ArrowTopRightOnSquareIcon className="mx-2 h-4 w-4 flex-shrink-0 text-gray-400 opacity-0 group-hover:opacity-100" />
<ArrowTopRightOnSquareIcon className="h-3 w-3 flex-shrink-0 text-gray-400 opacity-80 group-hover:opacity-100" />
)}
</div>
</div>

View file

@ -38,6 +38,7 @@ import {
} from "../styles/theme";
import { isJetBrains } from "../util";
import { setLocalStorage } from "../util/localStorage";
import { migrateLocalStorage } from "../util/migrateLocalStorage";
import { useWebviewListener } from "./useWebviewListener";
function ParallelListeners() {
@ -268,7 +269,6 @@ function ParallelListeners() {
currentToolCallApplyState.streamId === state.streamId
) {
if (state.status === "done" && autoAcceptEditToolDiffs) {
console.log("AUTO ACCEPTED");
ideMessenger.post("acceptDiff", {
streamId: state.streamId,
filepath: state.filepath,
@ -281,6 +281,11 @@ function ParallelListeners() {
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
void dispatch(
streamResponseAfterToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
}
// const output: ContextItem = {
// name: "Edit tool output",
@ -288,11 +293,6 @@ function ParallelListeners() {
// description: "",
// };
// dispatch(setToolCallOutput([]));
void dispatch(
streamResponseAfterToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
}
}
}
@ -311,6 +311,10 @@ function ParallelListeners() {
}
}, [isInEdit, history]);
useEffect(() => {
migrateLocalStorage(dispatch);
}, []);
return <></>;
}

View file

@ -46,9 +46,9 @@ const toolCallIcons: Record<string, ComponentType> = {
[BuiltInToolNames.ViewRepoMap]: MapIcon,
[BuiltInToolNames.ViewSubdirectory]: FolderOpenIcon,
[BuiltInToolNames.CreateRuleBlock]: PencilIcon,
// EditExistingFile = "builtin_edit_existing_file",
// CreateNewFile = "builtin_create_new_file",
// RunTerminalCommand = "builtin_run_terminal_command",
// EditExistingFile
// CreateNewFile
// RunTerminalCommand
};
function getStatusIcon(state: ToolStatus) {

View file

@ -0,0 +1,27 @@
import { ContextItem, ContextItemWithId, ToolCallState } from "core";
export function toolCallStateToContextItems(
toolCallState: ToolCallState | undefined,
): ContextItemWithId[] {
if (!toolCallState) {
return [];
}
return (
toolCallState.output?.map((ctxItem) =>
toolCallCtxItemToCtxItemWithId(ctxItem, toolCallState.toolCallId),
) ?? []
);
}
export function toolCallCtxItemToCtxItemWithId(
ctxItem: ContextItem,
toolCallId: string,
): ContextItemWithId {
return {
...ctxItem,
id: {
providerTitle: "toolCall",
itemId: toolCallId,
},
};
}

View file

@ -20,13 +20,20 @@ import {
SessionMetadata,
} from "core";
import { NEW_SESSION_TITLE } from "core/util/constants";
import { renderChatMessage } from "core/util/messageContent";
import {
renderChatMessage,
renderContextItems,
} from "core/util/messageContent";
import { findUriInDirs, getUriPathBasename } from "core/util/uri";
import { findLastIndex } from "lodash";
import { v4 as uuidv4 } from "uuid";
import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem";
import { addToolCallDeltaToState } from "../../util/toolCallState";
import { RootState } from "../store";
import { streamResponseThunk } from "../thunks/streamResponse";
import { findCurrentToolCall, findToolCall } from "../util";
import { findCurrentToolCall, findToolCall, findToolOutput } from "../util";
const getIdeMessenger = () => (window as any).ideMessenger;
// 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.
@ -105,19 +112,39 @@ export const sessionSlice = createSlice({
curMessage.isGatheringContext = payload;
}
},
clearLastEmptyResponse: (state) => {
clearDanglingMessages: (state) => {
// This is used during cancellation
// After the last user or tool message, we can have thinking and or valid assitant message (content or generated tool calls) OR nothing.
// The only thing allowed after the last assistant message that has either content or generated tool calls
// is a user or tool message
if (state.history.length < 2) {
return;
}
const lastMessage = state.history[state.history.length - 1];
const lastUserOrToolIdx = findLastIndex(
state.history,
(item) => item.message.role === "tool" || item.message.role === "user",
);
// Only clear in the case of an empty message
if (!lastMessage.message.content.length) {
state.mainEditorContentTrigger =
state.history[state.history.length - 2].editorState;
state.history = state.history.slice(0, -2);
// TODO is this logic correct for tool use conversations?
// Maybe slice at last index of "user" role message?
let validAssistantMessageIdx = -1;
for (let i = state.history.length - 1; i > lastUserOrToolIdx; i--) {
const message = state.history[i];
if (
message.message.content ||
message.toolCallState?.status !== "generating"
) {
validAssistantMessageIdx = i;
// Cancel any tool calls that are dangling and generated
if (message.toolCallState?.status === "generated") {
message.toolCallState.status = "canceled";
}
break;
}
}
if (validAssistantMessageIdx === -1) {
state.history = state.history.slice(0, lastUserOrToolIdx + 1);
} else {
state.history = state.history.slice(0, validAssistantMessageIdx + 1);
}
},
// Trigger value picked up by editor with isMainInput to set its content
@ -525,6 +552,7 @@ export const sessionSlice = createSlice({
contextItems: ContextItem[];
}>,
) => {
// Update tool call state and corresponding tool output message
const toolCallState = findToolCall(
state.history,
action.payload.toolCallId,
@ -532,6 +560,15 @@ export const sessionSlice = createSlice({
if (toolCallState) {
toolCallState.output = action.payload.contextItems;
}
const toolItem = findToolOutput(state.history, action.payload.toolCallId);
if (toolItem) {
toolItem.message.content = renderContextItems(
action.payload.contextItems,
);
toolItem.contextItems = action.payload.contextItems.map((item) =>
toolCallCtxItemToCtxItemWithId(item, action.payload.toolCallId),
);
}
},
cancelToolCall: (
state,
@ -677,7 +714,7 @@ export const {
setActive,
submitEditorAndInitAtIndex,
updateHistoryItemAtIndex,
clearLastEmptyResponse,
clearDanglingMessages,
setMainEditorContentTrigger,
deleteMessage,
setIsGatheringContext,

View file

@ -106,6 +106,18 @@ export const uiSlice = createSlice({
state.toolSettings[action.payload.function.name] =
"allowedWithPermission";
},
setToolPolicy: (
state,
action: PayloadAction<{
toolName: string;
policy: ToolPolicy;
}>,
) => {
state.toolSettings[action.payload.toolName] = action.payload.policy;
},
clearToolPolicy: (state, action: PayloadAction<string>) => {
delete state.toolSettings[action.payload];
},
toggleToolSetting: (state, action: PayloadAction<string>) => {
const setting = state.toolSettings[action.payload];
@ -166,6 +178,8 @@ export const {
setIsExploreDialogOpen,
setHasDismissedExploreDialog,
toggleToolSetting,
setToolPolicy,
clearToolPolicy,
toggleToolGroupSetting,
addTool,
addRule,

View file

@ -12,6 +12,7 @@ import {
updateToolCallOutput,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { logToolUsage } from "../util";
import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
export const callCurrentTool = createAsyncThunk<void, undefined, ThunkApiType>(
@ -100,6 +101,8 @@ export const callCurrentTool = createAsyncThunk<void, undefined, ThunkApiType>(
],
}),
);
logToolUsage(toolCallState, false, extra.ideMessenger, output);
} else if (output?.length) {
dispatch(
updateToolCallOutput({
@ -107,6 +110,8 @@ export const callCurrentTool = createAsyncThunk<void, undefined, ThunkApiType>(
contextItems: output,
}),
);
logToolUsage(toolCallState, true, extra.ideMessenger, output);
}
// Because we don't have access to use hooks, we check `allowAnonymousTelemetry`

View file

@ -1,50 +0,0 @@
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

@ -1,7 +1,7 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import {
abortStream,
clearLastEmptyResponse,
clearDanglingMessages,
setInactive,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
@ -12,9 +12,7 @@ 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
dispatch(clearLastEmptyResponse());
// Clear any dangling incomplete tool calls, thinking messages, etc.
dispatch(clearDanglingMessages());
},
);

View file

@ -1,5 +1,5 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ChatMessage, LLMFullCompletionOptions } from "core";
import { LLMFullCompletionOptions } from "core";
import { modelSupportsTools } from "core/llm/autodetect";
import { ToCoreProtocol } from "core/protocol";
import { selectActiveTools } from "../selectors/selectActiveTools";
@ -9,38 +9,40 @@ import {
abortStream,
addPromptCompletionPair,
setActive,
setAppliedRulesAtIndex,
setInactive,
setToolGenerated,
streamUpdate,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import {
constructMessages,
getBaseSystemMessage,
} from "../util/constructMessages";
import { callCurrentTool } from "./callCurrentTool";
export const streamNormalInput = createAsyncThunk<
void,
{
messages: ChatMessage[];
legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"];
},
ThunkApiType
>(
"chat/streamNormalInput",
async (
{ messages, legacySlashCommandData },
{ dispatch, extra, getState },
) => {
// Gather state
async ({ legacySlashCommandData }, { dispatch, extra, getState }) => {
const state = getState();
const selectedChatModel = selectSelectedChatModel(state);
const streamAborter = state.session.streamAborter;
if (!selectedChatModel) {
throw new Error("Default model not defined");
throw new Error("No chat model selected");
}
let completionOptions: LLMFullCompletionOptions = {};
// Get tools
const activeTools = selectActiveTools(state);
const toolsSupported = modelSupportsTools(selectedChatModel);
// Construct completion options
let completionOptions: LLMFullCompletionOptions = {};
if (toolsSupported && activeTools.length > 0) {
completionOptions = {
tools: activeTools,
@ -55,20 +57,46 @@ export const streamNormalInput = createAsyncThunk<
};
}
// Construct messages (excluding system message)
const baseSystemMessage = getBaseSystemMessage(
state.session.mode,
selectedChatModel,
);
const withoutMessageIds = state.session.history.map((item) => {
const { id, ...messageWithoutId } = item.message;
return { ...item, message: messageWithoutId };
});
const { messages, appliedRules, appliedRuleIndex } = constructMessages(
withoutMessageIds,
baseSystemMessage,
state.config.config.rules,
state.ui.ruleSettings,
);
// TODO parallel tool calls will cause issues with this
// because there will be multiple tool messages, so which one should have applied rules?
dispatch(
setAppliedRulesAtIndex({
index: appliedRuleIndex,
appliedRules: appliedRules,
}),
);
dispatch(setActive());
// Send request
// Send request and stream response
const streamAborter = state.session.streamAborter;
const gen = extra.ideMessenger.llmStreamChat(
{
completionOptions,
title: selectedChatModel.title,
messages,
messages: messages,
legacySlashCommandData,
},
streamAborter.signal,
);
// Stream response
let next = await gen.next();
while (!next.done) {
if (!getState().session.isStreaming) {

View file

@ -1,15 +1,11 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { JSONContent } from "@tiptap/core";
import { InputModifiers, ToolResultChatMessage, UserChatMessage } from "core";
import { constructMessages } from "core/llm/constructMessages";
import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules";
import { InputModifiers } from "core";
import posthog from "posthog-js";
import { v4 as uuidv4 } from "uuid";
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent";
import { getBaseSystemMessage } from "../../util";
import { selectSelectedChatModel } from "../slices/configSlice";
import {
setAppliedRulesAtIndex,
submitEditorAndInitAtIndex,
updateHistoryItemAtIndex,
} from "../slices/sessionSlice";
@ -77,7 +73,7 @@ export const streamResponseThunk = createAsyncThunk<
.map((item) => item.uri!.value),
...selectedCode.map((rif) => rif.filepath),
];
dispatch(updateFileSymbolsFromFiles(filesForSymbols));
void dispatch(updateFileSymbolsFromFiles(filesForSymbols));
dispatch(
updateHistoryItemAtIndex({
@ -93,47 +89,6 @@ export const streamResponseThunk = createAsyncThunk<
}),
);
// Get updated history after the update
const updatedHistory = getState().session.history;
// Determine which rules apply to this message
const userMsg = updatedHistory[inputIndex].message;
const rules = getState().config.config.rules;
const rulePolicies = getState().ui.ruleSettings;
// Calculate applicable rules once
// We need to check the message type to match what getApplicableRules expects
const applicableRules = getApplicableRules(
userMsg.role === "user" || userMsg.role === "tool"
? (userMsg as UserChatMessage | ToolResultChatMessage)
: undefined,
rules,
selectedContextItems,
rulePolicies,
);
// Store in history for UI display
dispatch(
setAppliedRulesAtIndex({
index: inputIndex,
appliedRules: applicableRules,
}),
);
const messageMode = getState().session.mode;
const baseChatOrAgentSystemMessage = getBaseSystemMessage(
selectedChatModel,
messageMode,
);
const messages = constructMessages(
messageMode,
[...updatedHistory],
baseChatOrAgentSystemMessage,
applicableRules,
rulePolicies,
);
posthog.capture("step run", {
step_name: "User Input",
params: {},
@ -150,7 +105,6 @@ export const streamResponseThunk = createAsyncThunk<
unwrapResult(
await dispatch(
streamNormalInput({
messages,
legacySlashCommandData: legacyCommandWithInput
? {
command: legacyCommandWithInput.command,

View file

@ -1,10 +1,7 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ChatMessage } from "core";
import { constructMessages } from "core/llm/constructMessages";
import { renderContextItems } from "core/util/messageContent";
import { getBaseSystemMessage } from "../../util";
import { selectSelectedChatModel } from "../slices/configSlice";
import { addContextItemsAtIndex, streamUpdate } from "../slices/sessionSlice";
import { streamUpdate } from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { findToolCall } from "../util";
import { resetStateForNewMessage } from "./resetStateForNewMessage";
@ -21,15 +18,8 @@ export const streamResponseAfterToolCall = createAsyncThunk<
await dispatch(
streamThunkWrapper(async () => {
const state = getState();
const initialHistory = state.session.history;
const selectedChatModel = selectSelectedChatModel(state);
if (!selectedChatModel) {
throw new Error("No model selected");
}
const toolCallState = findToolCall(state.session.history, toolCallId);
if (!toolCallState) {
return; // in cases where edit tool is cancelled mid apply, this will be triggered
}
@ -40,41 +30,15 @@ export const streamResponseAfterToolCall = createAsyncThunk<
await new Promise((resolve) => setTimeout(resolve, 0));
// TODO parallel tool calls - dispatch one tool message per tool call
const newMessage: ChatMessage = {
role: "tool",
content: renderContextItems(toolOutput),
toolCallId,
};
dispatch(streamUpdate([newMessage]));
dispatch(
addContextItemsAtIndex({
index: initialHistory.length,
contextItems: toolOutput.map((contextItem) => ({
...contextItem,
id: {
providerTitle: "toolCall",
itemId: toolCallId,
},
})),
}),
);
const updatedHistory = getState().session.history;
const messageMode = getState().session.mode;
const baseChatOrAgentSystemMessage = getBaseSystemMessage(
selectedChatModel,
messageMode,
);
const messages = constructMessages(
messageMode,
[...updatedHistory],
baseChatOrAgentSystemMessage,
state.config.config.rules,
);
unwrapResult(await dispatch(streamNormalInput({ messages })));
unwrapResult(await dispatch(streamNormalInput({})));
}),
);
},

View file

@ -22,7 +22,7 @@ export const streamThunkWrapper = createAsyncThunk<
);
}
} catch (e) {
dispatch(cancelStream());
await dispatch(cancelStream());
dispatch(setDialogMessage(<StreamErrorDialog error={e} />));
dispatch(setShowDialog(true));
}

View file

@ -0,0 +1,734 @@
import {
AssistantChatMessage,
ChatHistoryItem,
ChatMessage,
ContextItemWithId,
ModelDescription,
RuleWithSource,
ThinkingChatMessage,
ToolResultChatMessage,
UserChatMessage,
} from "core";
import {
DEFAULT_AGENT_SYSTEM_MESSAGE,
DEFAULT_CHAT_SYSTEM_MESSAGE,
} from "core/llm/defaultSystemMessages";
import { renderChatMessage } from "core/util/messageContent";
import { beforeEach, describe, expect, test, vi } from "vitest";
import {
CANCELLED_TOOL_CALL_MESSAGE,
constructMessages,
getBaseSystemMessage,
NO_TOOL_CALL_OUTPUT_MESSAGE,
} from "./constructMessages";
// For these tests we will mock the rules to simulate different scenarios
const CONTEXT_RULE: RuleWithSource = {
source: "rules-block",
rule: "CONTEXT_RULE",
description: "CONTEXT_TRIGGER",
};
const LAST_MESSAGE_RULE: RuleWithSource = {
source: "rules-block",
rule: "LAST_MESSAGE_RULE",
description: "LAST_MESSAGE_TRIGGER",
};
const NORMAL_RULE: RuleWithSource = {
source: "rules-block",
rule: "Always apply rule",
};
vi.mock("core/llm/rules/getSystemMessageWithRules", async (importOriginal) => {
const original = (await importOriginal()) as any;
return {
...original,
getSystemMessageWithRules: ({
baseSystemMessage,
availableRules,
userMessage,
contextItems,
rulePolicies,
}: {
baseSystemMessage: string;
availableRules: RuleWithSource[];
userMessage?: UserChatMessage | ToolResultChatMessage;
contextItems: ContextItemWithId[];
rulePolicies?: Record<string, any>;
}) => {
// Filter rules based on our mock logic
const appliedRules = availableRules.filter((rule) => {
if (rule.rule === LAST_MESSAGE_RULE.rule) {
if (userMessage) {
return renderChatMessage(userMessage).includes(
LAST_MESSAGE_RULE.description!,
);
} else {
return false;
}
}
if (rule.rule === CONTEXT_RULE.rule) {
return contextItems.some((item) =>
item.content.includes(CONTEXT_RULE.description!),
);
}
return true;
});
// Build the system message with applied rules
let systemMessage = baseSystemMessage || "";
if (appliedRules.length > 0) {
systemMessage += "\n\nRules to follow:\n";
for (const rule of appliedRules) {
systemMessage += `- ${rule.rule}\n`;
}
}
return { systemMessage, appliedRules };
},
};
});
test("getBaseSystemMessage should return the correct system message based on mode", () => {
const mockModel = {
baseAgentSystemMessage: "Custom Agent System Message",
baseChatSystemMessage: "Custom Chat System Message",
} as ModelDescription;
// Test agent mode with custom message
expect(getBaseSystemMessage("agent", mockModel)).toBe(
"Custom Agent System Message",
);
// Test chat mode with custom message
expect(getBaseSystemMessage("chat", mockModel)).toBe(
"Custom Chat System Message",
);
// Test agent mode with default message
expect(getBaseSystemMessage("agent", {} as ModelDescription)).toBe(
DEFAULT_AGENT_SYSTEM_MESSAGE,
);
// Test chat mode with default message
expect(getBaseSystemMessage("chat", {} as ModelDescription)).toBe(
DEFAULT_CHAT_SYSTEM_MESSAGE,
);
});
describe("constructMessages", () => {
// Setup mock data
let mockHistory: ChatHistoryItem[];
const mockRules: RuleWithSource[] = [
CONTEXT_RULE,
LAST_MESSAGE_RULE,
NORMAL_RULE,
];
const createContextItem = (
id: string,
content: string,
): ContextItemWithId => ({
id: {
providerTitle: "test-provider",
itemId: id,
},
content,
name: `Context Item ${id}`,
description: `Description for ${id}`,
});
beforeEach(() => {
// Reset mock history before each test
mockHistory = [];
});
test("should ignore empty, tool, and system messages that go in", () => {
// Setup history with various message types including ones to be ignored
mockHistory = [
{
message: {
role: "system",
content: "I should be ignored",
} as ChatMessage,
contextItems: [],
},
{
message: {
role: "tool",
content: "I should be ignored",
toolCallId: "123",
} as ToolResultChatMessage,
contextItems: [],
},
{
message: { role: "user", content: "" } as ChatMessage, // Empty message
contextItems: [],
},
{
message: { role: "user", content: "Valid user message" } as ChatMessage,
contextItems: [],
},
];
const { messages } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
// Should only contain a system message (added by the function) and the valid user message
expect(messages.length).toBe(2);
expect(messages[0].role).toBe("system");
expect(messages[1].role).toBe("user");
expect(messages[1].content).toEqual([
{ type: "text", text: "Valid user message" },
]);
expect(messages.some((msg) => msg.content === "I should be ignored")).toBe(
false,
);
});
test("should convert user messages to message parts arrays with context items", () => {
const contextItems = [
createContextItem("1", "Context content 1"),
createContextItem("2", "Context content 2"),
];
mockHistory = [
{
message: {
role: "user",
content: "User message with context",
} as ChatMessage,
contextItems,
},
];
const { messages } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
// Check that user message was converted to parts array with context items first
expect(messages.length).toBe(2); // System message + user message
expect(messages[1].role).toBe("user");
// Check content structure
const content = messages[1].content as any[];
expect(content.length).toBe(3); // 2 context items + original message
expect(content[0].text).toContain("Context content 1");
expect(content[1].text).toContain("Context content 2");
expect(content[2].text).toBe("User message with context");
});
test("should inject thinking messages with no changes", () => {
const thinkingMessage: ThinkingChatMessage = {
role: "thinking",
content: "Thinking process...",
};
mockHistory = [
{
message: thinkingMessage,
contextItems: [],
},
];
const { messages } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
// Should have system message + thinking message
expect(messages.length).toBe(2);
expect(messages[1].role).toBe("thinking");
expect(messages[1].content).toBe("Thinking process...");
});
test("should inject assistant messages with no changes", () => {
const assistantMessage: AssistantChatMessage = {
role: "assistant",
content: "Assistant response",
};
mockHistory = [
{
message: assistantMessage,
contextItems: [],
},
];
const { messages } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
// Should have system message + assistant message
expect(messages.length).toBe(2);
expect(messages[1].role).toBe("assistant");
expect(messages[1].content).toBe("Assistant response");
});
test("should follow assistant messages with tool calls by tool messages containing the tool output", () => {
const assistantWithToolCall: AssistantChatMessage = {
role: "assistant",
content: "I will search for that",
toolCalls: [
{
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
],
};
// With tool output
mockHistory = [
{
message: {
role: "user",
content: "Can you search for something?",
} as UserChatMessage,
contextItems: [],
},
{
message: assistantWithToolCall,
contextItems: [],
toolCallState: {
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
status: "done",
parsedArgs: { query: "test" },
output: [createContextItem("search-result", "Search result content")],
},
},
];
const { messages } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
// Should have: system + user + assistant + tool messages
expect(messages.length).toBe(4);
expect(messages[2].role).toBe("assistant");
expect(messages[3].role).toBe("tool");
const toolMessage = messages[3] as ToolResultChatMessage;
expect(toolMessage.toolCallId).toBe("tool-call-1");
expect(toolMessage.content).toContain("Search result content");
});
test("should show cancelled message for cancelled tool calls", () => {
const assistantWithToolCall: AssistantChatMessage = {
role: "assistant",
content: "I will search for that",
toolCalls: [
{
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
],
};
// With cancelled tool call
mockHistory = [
{
message: assistantWithToolCall,
contextItems: [],
toolCallState: {
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
status: "canceled",
parsedArgs: { query: "test" },
},
},
];
const { messages } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
// Should have system + assistant + tool message with cancelled message
expect(messages.length).toBe(3);
expect(messages[2].role).toBe("tool");
const toolMessage = messages[2] as ToolResultChatMessage;
expect(toolMessage.toolCallId).toBe("tool-call-1");
expect(toolMessage.content).toBe(CANCELLED_TOOL_CALL_MESSAGE);
});
test('should show "No tool output" for tool calls without output', () => {
const assistantWithToolCall: AssistantChatMessage = {
role: "assistant",
content: "I will search for that",
toolCalls: [
{
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
],
};
// With tool call but no output
mockHistory = [
{
message: assistantWithToolCall,
contextItems: [],
toolCallState: {
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
status: "generating", // Not done yet
parsedArgs: { query: "test" },
},
},
];
const { messages } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
// Should have system + assistant + tool message with "No tool output"
expect(messages.length).toBe(3);
expect(messages[2].role).toBe("tool");
expect(messages[2].content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE);
});
test("should start with system message using base message if provided", () => {
mockHistory = [
{
message: { role: "user", content: "Hello" } as UserChatMessage,
contextItems: [],
},
];
const { messages } = constructMessages(
mockHistory,
"Custom Base System Message",
mockRules,
{},
);
expect(messages[0].role).toBe("system");
expect(messages[0].content).toContain("Custom Base System Message");
});
test("should handle multiple tool calls in a single assistant message", () => {
const assistantWithMultipleToolCalls: AssistantChatMessage = {
role: "assistant",
content: "I will search and check the weather",
toolCalls: [
{
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
{
id: "tool-call-2",
type: "function",
function: {
name: "weather",
arguments: '{"location": "New York"}',
},
},
],
};
// Only the first tool call has output
mockHistory = [
{
message: assistantWithMultipleToolCalls,
contextItems: [],
toolCallState: {
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
status: "done",
parsedArgs: { query: "test" },
output: [createContextItem("search-result", "Search result content")],
},
},
];
const { messages } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
// Should have: system + assistant + 2 tool messages
expect(messages.length).toBe(4);
expect(messages[1].role).toBe("assistant");
// First tool message should have output
expect(messages[2].role).toBe("tool");
expect(messages[3].role).toBe("tool");
const toolMessage1 = messages[2] as ToolResultChatMessage;
const toolMessage2 = messages[3] as ToolResultChatMessage;
expect(toolMessage1.toolCallId).toBe("tool-call-1");
expect(toolMessage1.content).toContain("Search result content");
// Second tool message should have "No tool output"
expect(toolMessage2.toolCallId).toBe("tool-call-2");
expect(toolMessage2.content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE);
});
test("should handle messages with array content", () => {
// User message with array content (including an image)
const userMessageWithArray: UserChatMessage = {
role: "user",
content: [
{ type: "text", text: "Here is some text" },
{
type: "imageUrl",
imageUrl: { url: "https://example.com/image.jpg" },
},
],
};
mockHistory = [
{
message: userMessageWithArray,
contextItems: [createContextItem("ctx", "Context text")],
},
];
const { messages, appliedRules } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
// Check the user message content structure
expect(messages.length).toBe(2);
expect(messages[1].role).toBe("user");
const content = messages[1].content as any[];
// Should have context item + original 2 parts
expect(content.length).toBe(3);
expect(content[0].type).toBe("text");
expect(content[0].text).toContain("Context text");
expect(content[1].type).toBe("text");
expect(content[1].text).toBe("Here is some text");
expect(content[2].type).toBe("imageUrl");
expect(content[2].imageUrl.url).toBe("https://example.com/image.jpg");
// This also verifies that rules are NOT applied if the triggers are not present
expect(appliedRules).toHaveLength(1);
expect(appliedRules).toContainEqual(NORMAL_RULE);
});
test("system message should include rules triggered by context items from the last user message forward", () => {
// Create context item that should trigger the CONTEXT_RULE
const triggeringContextItem = createContextItem(
"trigger",
`Some content with ${CONTEXT_RULE.description} in it`,
);
mockHistory = [
// First user message with non-triggering context
{
message: { role: "user", content: "First message" } as UserChatMessage,
contextItems: [createContextItem("normal", "Normal context")],
},
// Assistant response
{
message: {
role: "assistant",
content: "Assistant response",
} as AssistantChatMessage,
contextItems: [],
},
// Last user message with triggering context
{
message: { role: "user", content: "Last message" } as UserChatMessage,
contextItems: [triggeringContextItem],
},
];
const { messages, appliedRules } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
// Verify context rule was applied in the system message
expect(appliedRules).toHaveLength(2);
expect(appliedRules).toContainEqual(NORMAL_RULE);
expect(appliedRules).toContainEqual(CONTEXT_RULE);
expect(messages[0].role).toBe("system");
expect(messages[0].content).toContain("Base System Message");
expect(messages[0].content).toContain(CONTEXT_RULE.rule);
});
test("system message should include rules triggered by tool output after the last user message", () => {
// Create a history with a user message, assistant with tool call, and tool output containing triggering content
const assistantWithToolCall: AssistantChatMessage = {
role: "assistant",
content: "I will search for that",
toolCalls: [
{
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
],
};
// Tool output containing the trigger for CONTEXT_RULE
const triggeringToolOutput = createContextItem(
"search-result",
`Search result with ${CONTEXT_RULE.description} trigger`,
);
mockHistory = [
{
message: {
role: "user",
content: "Can you search for something?",
} as UserChatMessage,
contextItems: [],
},
{
message: assistantWithToolCall,
contextItems: [],
toolCallState: {
toolCallId: "tool-call-1",
toolCall: {
id: "tool-call-1",
type: "function",
function: {
name: "search",
arguments: '{"query": "test"}',
},
},
status: "done",
parsedArgs: { query: "test" },
output: [triggeringToolOutput],
},
},
];
const { messages, appliedRules } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
// Verify context rule was applied in the system message due to the tool output
expect(appliedRules).toHaveLength(2);
expect(appliedRules).toContainEqual(NORMAL_RULE);
expect(appliedRules).toContainEqual(CONTEXT_RULE);
expect(messages[0].role).toBe("system");
expect(messages[0].content).toContain("Base System Message");
expect(messages[0].content).toContain(CONTEXT_RULE.rule);
});
test("system message should only apply rules triggered by the last user message", () => {
// First user message with trigger for LAST_MESSAGE_RULE
const firstUserMessage = {
role: "user",
content: `This contains ${LAST_MESSAGE_RULE.description}`,
} as UserChatMessage;
// Last user message without any triggers
const lastUserMessage = {
role: "user",
content: "This is a normal message",
} as UserChatMessage;
mockHistory = [
{
message: firstUserMessage,
contextItems: [],
},
{
message: {
role: "assistant",
content: "First response",
} as AssistantChatMessage,
contextItems: [],
},
{
message: lastUserMessage,
contextItems: [],
},
];
const { messages, appliedRules } = constructMessages(
mockHistory,
"Base System Message",
mockRules,
{},
);
// LAST_MESSAGE_RULE should not be applied since the trigger is not in the last message
expect(appliedRules).toHaveLength(1);
expect(appliedRules).toContainEqual(NORMAL_RULE); // Normal rule should always apply
expect(messages[0].role).toBe("system");
expect(messages[0].content).toContain("Base System Message");
expect(messages[0].content).not.toContain(LAST_MESSAGE_RULE.rule);
});
});

View file

@ -0,0 +1,173 @@
import {
ChatHistoryItem,
ChatMessage,
ContextItemWithId,
ModelDescription,
RuleWithSource,
TextMessagePart,
ToolResultChatMessage,
UserChatMessage,
} from "core";
import {
DEFAULT_AGENT_SYSTEM_MESSAGE,
DEFAULT_CHAT_SYSTEM_MESSAGE,
} from "core/llm/defaultSystemMessages";
import { chatMessageIsEmpty } from "core/llm/messages";
import { getSystemMessageWithRules } from "core/llm/rules/getSystemMessageWithRules";
import { RulePolicies } from "core/llm/rules/types";
import { findLast, findLastIndex } from "core/util/findLast";
import {
normalizeToMessageParts,
renderContextItems,
} from "core/util/messageContent";
import { toolCallStateToContextItems } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem";
export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output";
export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call.";
interface MessageWithContextItems {
ctxItems: ContextItemWithId[];
message: ChatMessage;
}
export function constructMessages(
history: ChatHistoryItem[],
baseSystemMessage: string | undefined,
availableRules: RuleWithSource[],
rulePolicies: RulePolicies,
): {
messages: ChatMessage[];
appliedRules: RuleWithSource[];
appliedRuleIndex: number;
} {
const historyCopy = [...history];
const msgs: MessageWithContextItems[] = [];
let appliedRuleIndex = -1;
let index = -1;
for (const item of historyCopy) {
index++;
if (
item.message.role === "system" ||
item.message.role === "tool" ||
chatMessageIsEmpty(item.message)
) {
// Tool messages will be re-inserted
continue;
}
if (item.message.role === "user") {
appliedRuleIndex = index;
// Gather context items for user messages
let content = normalizeToMessageParts(item.message);
const ctxItemParts = item.contextItems
.map((ctxItem) => {
return {
type: "text",
text: `${ctxItem.content}\n`,
} as TextMessagePart;
})
.filter((part) => !!part.text.trim());
content = [...ctxItemParts, ...content];
msgs.push({
ctxItems: item.contextItems,
message: {
...item.message,
content,
},
});
} else if (item.message.role === "thinking") {
msgs.push({
ctxItems: item.contextItems,
message: item.message,
});
} else if (item.message.role === "assistant") {
msgs.push({
ctxItems: item.contextItems,
message: item.message,
});
// Add a tool message for each tool call
if (item.message.toolCalls?.length) {
// If the assistant message has tool calls, we need to insert tool messages
for (const toolCall of item.message.toolCalls) {
let content: string = NO_TOOL_CALL_OUTPUT_MESSAGE;
// TODO parallel tool calls: toolCallState only supports one tool call per message for now
if (item.toolCallState?.status === "canceled") {
content = CANCELLED_TOOL_CALL_MESSAGE;
} else if (
item.toolCallState?.toolCallId === toolCall.id &&
item.toolCallState?.output
) {
content = renderContextItems(item.toolCallState.output);
}
msgs.push({
ctxItems: toolCallStateToContextItems(item.toolCallState),
message: {
role: "tool",
content,
toolCallId: toolCall.id!,
},
});
}
}
}
}
// Some rules only apply to the last user or tool message
const lastUserOrToolMsg = findLast(
msgs,
(item) => item.message.role === "user" || item.message.role === "tool",
)?.message as UserChatMessage | ToolResultChatMessage;
// Some rules apply to all context items since the last user message, inclusiv
const lastUserMsgIndex = findLastIndex(
msgs,
(item) => item.message.role === "user",
);
const itemsBackToLastUserMessage = msgs
.slice(lastUserMsgIndex, msgs.length)
.filter(
(item) => item.message.role === "tool" || item.message.role === "user",
);
const rulesContextItems = itemsBackToLastUserMessage
.map((item) => item.ctxItems)
.flat();
const { systemMessage, appliedRules } = getSystemMessageWithRules({
baseSystemMessage,
availableRules,
userMessage: lastUserOrToolMsg,
contextItems: rulesContextItems,
rulePolicies,
});
if (systemMessage.trim()) {
msgs.unshift({
ctxItems: [],
message: {
role: "system",
content: systemMessage,
},
});
}
const messages = msgs.map((m) => m.message);
return {
messages,
appliedRules,
appliedRuleIndex,
};
}
export function getBaseSystemMessage(
messageMode: string,
model: ModelDescription,
): string {
if (messageMode === "agent") {
return model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE;
} else {
return model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE;
}
}

View file

@ -1,4 +1,7 @@
import { ToolCallState } from "core";
import { ContextItem, ToolCallState } from "core";
import { safeParseToolCallArgs } from "core/tools/parseArgs";
import { IIdeMessenger } from "../../context/IdeMessenger";
import { ChatHistoryItemWithMessageId } from "../slices/sessionSlice";
import { RootState } from "../store";
export function findCurrentToolCall(
@ -7,6 +10,7 @@ export function findCurrentToolCall(
return chatHistory[chatHistory.length - 1]?.toolCallState;
}
// TODO parallel tool calls - find tool call must search within arrays
export function findToolCall(
chatHistory: RootState["session"]["history"],
toolCallId: string,
@ -15,3 +19,33 @@ export function findToolCall(
(item) => item.toolCallState?.toolCallId === toolCallId,
)?.toolCallState;
}
export function findToolOutput(
chatHistory: RootState["session"]["history"],
toolCallId: string,
): ChatHistoryItemWithMessageId | undefined {
return chatHistory.find(
(item) =>
item.message.role === "tool" && item.message.toolCallId === toolCallId,
);
}
export function logToolUsage(
toolCallState: ToolCallState,
success: boolean,
messenger: IIdeMessenger,
finalOutput?: ContextItem[],
) {
messenger.post("devdata/log", {
name: "toolUsage",
data: {
toolCallId: toolCallState.toolCallId,
functionName: toolCallState.toolCall?.function?.name,
functionArgs: toolCallState.toolCall?.function?.arguments,
toolCallArgs: safeParseToolCallArgs(toolCallState.toolCall),
parsedArgs: toolCallState.parsedArgs,
output: finalOutput || toolCallState.output || [],
succeeded: success,
},
});
}

View file

@ -1,10 +1,4 @@
import { MessageModes, ModelDescription } from "core";
import { ProfileDescription } from "core/config/ProfileLifecycleManager";
import {
DEFAULT_AGENT_SYSTEM_MESSAGE,
DEFAULT_CHAT_SYSTEM_MESSAGE,
} from "core/llm/constructMessages";
import _ from "lodash";
import { KeyboardEvent as ReactKeyboardEvent } from "react";
import { getLocalStorage } from "./localStorage";
@ -88,52 +82,6 @@ export function isPrerelease() {
return false;
}
/**
* Updates the values of an object's properties based on the specified paths.
*
* This function creates a deep clone of the provided object and updates its properties
* based on the given path-to-value mappings. If a value in the mapping is a function,
* it will be used to determine the new value for the property. Otherwise, the value itself
* will be set for the property.
*
* @param {Object} old - The original object to be cloned and updated.
* @param {Object} pathToValue - An object where the keys represent the paths to the properties
* to be updated and the values represent the new values or functions
* to determine the new values.
* @returns {Object} A new object with the updated values.
*/
export function updatedObj(old: any, pathToValue: { [key: string]: any }) {
const newObject = _.cloneDeep(old);
for (const key in pathToValue) {
if (typeof pathToValue[key] === "function") {
_.updateWith(newObject, key, pathToValue[key]);
} else {
_.updateWith(newObject, key, (__) => pathToValue[key]);
}
}
return newObject;
}
export function isLocalProfile(profile: ProfileDescription): boolean {
return profile.profileType === "local";
}
/**
* Get the base system message for the agent or chat mode from the model description.
*/
export function getBaseSystemMessage(
modelDetails: ModelDescription | null,
mode: MessageModes,
) {
let baseChatOrAgentSystemMessage: string | undefined;
if (mode === "agent") {
baseChatOrAgentSystemMessage =
modelDetails?.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE;
} else {
baseChatOrAgentSystemMessage =
modelDetails?.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE;
}
return baseChatOrAgentSystemMessage;
}

View file

@ -0,0 +1,74 @@
import { BuiltInToolNames } from "core/tools/builtIn";
import {
clearToolPolicy,
setToolPolicy,
ToolPolicy,
} from "../redux/slices/uiSlice";
import { AppDispatch } from "../redux/store";
const validPolicyValues: ToolPolicy[] = [
"allowedWithPermission",
"allowedWithoutPermission",
"disabled",
];
function migrateToolPolicies(dispatch: AppDispatch) {
const toFromMap: Record<string, string[]> = {
[BuiltInToolNames.ReadFile]: ["builtin_read_file"],
[BuiltInToolNames.EditExistingFile]: ["builtin_edit_existing_file"],
[BuiltInToolNames.SearchAndReplaceInFile]: [
"builtin_search_and_replace_in_file",
],
[BuiltInToolNames.ReadCurrentlyOpenFile]: [
"builtin_read_currently_open_file",
],
[BuiltInToolNames.CreateNewFile]: ["builtin_create_new_file"],
[BuiltInToolNames.RunTerminalCommand]: ["builtin_run_terminal_command"],
[BuiltInToolNames.GrepSearch]: ["builtin_grep_search"],
[BuiltInToolNames.FileGlobSearch]: ["builtin_file_glob_search"],
[BuiltInToolNames.SearchWeb]: ["builtin_search_web"],
[BuiltInToolNames.ViewDiff]: ["builtin_view_diff"],
[BuiltInToolNames.LSTool]: ["builtin_ls"],
[BuiltInToolNames.CreateRuleBlock]: ["builtin_create_rule_block"],
[BuiltInToolNames.RequestRule]: ["builtin_request_rule"],
[BuiltInToolNames.FetchUrlContent]: ["builtin_fetch_url_content"],
[BuiltInToolNames.CodebaseTool]: ["builtin_codebase"],
[BuiltInToolNames.ViewRepoMap]: ["builtin_view_repo_map"],
[BuiltInToolNames.ViewSubdirectory]: ["builtin_view_subdirectory"],
};
const persistedRedux = localStorage.getItem("persist:root");
if (persistedRedux) {
const uiState = JSON.parse(persistedRedux)?.ui;
if (uiState) {
const parsedSettings = JSON.parse(uiState)?.toolSettings;
if (parsedSettings) {
let migratedToolSettings = 0;
Object.entries(toFromMap).forEach(([newToolName, oldToolNames]) => {
for (const tool of oldToolNames) {
if (
tool in parsedSettings &&
validPolicyValues.includes(parsedSettings[tool])
) {
dispatch(
setToolPolicy({
toolName: newToolName,
policy: parsedSettings[tool],
}),
);
dispatch(clearToolPolicy(tool));
migratedToolSettings++;
}
}
});
if (migratedToolSettings > 0) {
console.log(
`Migrated ${migratedToolSettings} tool policies successfully.`,
);
}
}
}
}
}
export function migrateLocalStorage(dispatch: AppDispatch) {
migrateToolPolicies(dispatch);
}

View file

@ -28,6 +28,7 @@ import {
editInteractionEventSchema_0_2_0,
editInteractionEventSchema_0_2_0_noCode,
} from "./editInteraction/v0.2.0.js";
import { editOutcomeEventAllSchema } from "./editOutcome/index.js";
import {
editOutcomeEventSchema_0_2_0,
editOutcomeEventSchema_0_2_0_noCode,
@ -51,6 +52,11 @@ import {
tokensGeneratedEventSchema_0_2_0,
tokensGeneratedEventSchema_0_2_0_noCode,
} from "./tokensGenerated/v0.2.0.js";
import { toolUsageEventAllSchema } from "./toolUsage/index.js";
import {
toolUsageEventSchema_0_2_0,
toolUsageEventSchema_0_2_0_noCode,
} from "./toolUsage/v0.2.0.js";
const semverRegex =
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
@ -81,7 +87,9 @@ const devEventAllVersionDataSchemas = z.object({
tokensGenerated: tokensGeneratedEventAllSchema,
chatInteraction: chatInteractionEventAllSchema,
editInteraction: editInteractionEventAllSchema,
editOutcome: editOutcomeEventAllSchema,
nextEdit: nextEditEventAllSchema,
toolUsage: toolUsageEventAllSchema,
});
// Version and level specific schemas are organized here
@ -109,6 +117,7 @@ export const devDataVersionedSchemas = {
editInteraction: editInteractionEventSchema_0_2_0,
editOutcome: editOutcomeEventSchema_0_2_0,
nextEdit: nextEditEventSchema_0_2_0,
toolUsage: toolUsageEventSchema_0_2_0,
},
noCode: {
autocomplete: autocompleteEventSchema_0_2_0_noCode,
@ -118,6 +127,7 @@ export const devDataVersionedSchemas = {
editInteraction: editInteractionEventSchema_0_2_0_noCode,
editOutcome: editOutcomeEventSchema_0_2_0_noCode,
nextEdit: nextEditEventSchema_0_2_0_noCode,
toolUsage: toolUsageEventSchema_0_2_0_noCode,
},
},
};

View file

@ -0,0 +1,12 @@
import { z } from "zod";
import { baseDevDataAllSchema } from "../base.js";
export const toolUsageEventAllSchema = baseDevDataAllSchema.extend({
toolCallId: z.string(),
functionName: z.string(),
functionArgs: z.string(),
toolCallArgs: z.any(),
parsedArgs: z.any(),
succeeded: z.boolean(),
output: z.array(z.any()).optional(),
});

View file

@ -0,0 +1,27 @@
import { toolUsageEventAllSchema } from "./index.js";
export const toolUsageEventSchema_0_2_0 = toolUsageEventAllSchema.pick({
// base
timestamp: true,
userId: true,
userAgent: true,
selectedProfileId: true,
eventName: true,
schema: true,
// tool-usage-specific
toolCallId: true,
functionName: true,
functionArgs: true,
toolCallArgs: true,
parsedArgs: true,
succeeded: true,
output: true,
});
export const toolUsageEventSchema_0_2_0_noCode =
toolUsageEventSchema_0_2_0.omit({
functionArgs: true,
parsedArgs: true,
output: true,
});