Elffuss BraidHub

kikocis/continue public

Merge pull request #6333 from continuedev/dallin/agent-papercuts

Update Agent/Tool Message Construction and Handling
Changesetfc1d06ba6663de58e11a0c5d0d84c2040d2d5a9f012746006d1d4f372ef415ff
AuthorDallin Romney <dallinromney@gmail.com> · 2025-07-01 20:57 -07:00
CommitterGitHub <noreply@github.com> · 2025-07-01 20:57 -07:00
Parentse1a75b61f8f3, a968bb06ae87

Browse the files at this changeset

30 files changed

modified core/config/util.ts +1 −1
@@ -10,7 +10,7 @@
1010 JSONModelDescription,
1111 PromptTemplate,
1212 } from "../";
13-import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages";
13+import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages";
1414 import { GlobalContext } from "../util/GlobalContext";
1515 import { editConfigFile } from "../util/paths";
1616
modified core/edit/streamDiffLines.ts +2 −2
@@ -112,7 +112,7 @@
112112 // If any rules are present this will result in using chat instead of legacy completion
113113 const systemMessage = rulesToInclude
114114 ? getSystemMessageWithRules({
115- rules: rulesToInclude,
115+ availableRules: rulesToInclude,
116116 userMessage:
117117 typeof prompt === "string"
118118 ? ({
@@ -125,7 +125,7 @@
125125 ) as UserChatMessage | ToolResultChatMessage | undefined),
126126 baseSystemMessage: undefined,
127127 contextItems: [],
128- })
128+ }).systemMessage
129129 : undefined;
130130
131131 if (systemMessage) {
deleted core/llm/constructMessages.ts +0 −187
@@ -1,187 +0,0 @@
1-import {
2- ChatHistoryItem,
3- ChatMessage,
4- ContextItemWithId,
5- RuleWithSource,
6- TextMessagePart,
7- ToolResultChatMessage,
8- UserChatMessage,
9-} from "../";
10-import { findLast } from "../util/findLast";
11-import { normalizeToMessageParts } from "../util/messageContent";
12-import { isUserOrToolMsg } from "./messages";
13-import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
14-import { RulePolicies } from "./rules/types";
15-
16-export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
17- "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
18-
19-export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL =
20- "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
21-
22-export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\
23- Always include the language and file name in the info string when you write code blocks.
24- If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
25-`;
26-
27-export const EDIT_CODE_INSTRUCTIONS = `\
28- When addressing code modification requests, present a concise code snippet that
29- emphasizes only the necessary changes and uses abbreviated placeholders for
30- unmodified sections. For example:
31-
32- \`\`\`language /path/to/file
33- // ... existing code ...
34-
35- {{ modified code here }}
36-
37- // ... existing code ...
38-
39- {{ another modification }}
40-
41- // ... rest of code ...
42- \`\`\`
43-
44- In existing files, you should always restate the function or class that the snippet belongs to:
45-
46- \`\`\`language /path/to/file
47- // ... existing code ...
48-
49- function exampleFunction() {
50- // ... existing code ...
51-
52- {{ modified code here }}
53-
54- // ... rest of function ...
55- }
56-
57- // ... rest of code ...
58- \`\`\`
59-
60- Since users have access to their complete file, they prefer reading only the
61- relevant modifications. It's perfectly acceptable to omit unmodified portions
62- at the beginning, middle, or end of files using these "lazy" comments. Only
63- provide the complete file when explicitly requested. Include a concise explanation
64- of changes unless the user specifically asks for code only.
65-`;
66-
67-export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
68-<important_rules>
69- You are in chat mode.
70-
71- 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.
72- If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
73-
74-${CODEBLOCK_FORMATTING_INSTRUCTIONS}
75-${EDIT_CODE_INSTRUCTIONS}
76-</important_rules>`;
77-
78-export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
79-<important_rules>
80- You are in agent mode.
81-
82-${CODEBLOCK_FORMATTING_INSTRUCTIONS}
83-</important_rules>`;
84-
85-/**
86- * Helper function to get the context items for a user message
87- */
88-function getUserContextItems(
89- userMsg: UserChatMessage | ToolResultChatMessage | undefined,
90- history: ChatHistoryItem[],
91-): ContextItemWithId[] {
92- if (!userMsg) return [];
93-
94- // Find the history item that contains the userMsg
95- const historyItem = history.find((item) => {
96- // Check if the message ID matches
97- if ("id" in userMsg && "id" in item.message) {
98- return (item.message as any).id === (userMsg as any).id;
99- }
100- // Fallback to content comparison
101- return (
102- item.message.content === userMsg.content &&
103- item.message.role === userMsg.role
104- );
105- });
106-
107- return historyItem?.contextItems || [];
108-}
109-
110-export function constructMessages(
111- messageMode: string,
112- history: ChatHistoryItem[],
113- baseChatOrAgentSystemMessage: string | undefined,
114- rules: RuleWithSource[],
115- rulePolicies?: RulePolicies,
116-): ChatMessage[] {
117- const filteredHistory = history.filter(
118- (item) => item.message.role !== "system",
119- );
120- const msgs: ChatMessage[] = [];
121-
122- for (let i = 0; i < filteredHistory.length; i++) {
123- const historyItem = filteredHistory[i];
124-
125- if (messageMode === "chat") {
126- const toolMessage: ToolResultChatMessage =
127- historyItem.message as ToolResultChatMessage;
128- if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) {
129- // remove all tool calls from the history
130- continue;
131- }
132- }
133-
134- if (historyItem.message.role === "user") {
135- // Gather context items for user messages
136- let content = normalizeToMessageParts(historyItem.message);
137-
138- const ctxItems = historyItem.contextItems
139- .map((ctxItem) => {
140- return {
141- type: "text",
142- text: `${ctxItem.content}\n`,
143- } as TextMessagePart;
144- })
145- .filter((part) => !!part.text.trim());
146-
147- content = [...ctxItems, ...content];
148- msgs.push({
149- ...historyItem.message,
150- content,
151- });
152- } else {
153- msgs.push(historyItem.message);
154- }
155- }
156-
157- const lastUserMsg = findLast(msgs, isUserOrToolMsg) as
158- | UserChatMessage
159- | ToolResultChatMessage
160- | undefined;
161-
162- // Get context items for the last user message
163- const lastUserContextItems = getUserContextItems(
164- lastUserMsg,
165- filteredHistory,
166- );
167- const systemMessage = getSystemMessageWithRules({
168- baseSystemMessage: baseChatOrAgentSystemMessage,
169- rules,
170- userMessage: lastUserMsg,
171- contextItems: lastUserContextItems,
172- rulePolicies,
173- });
174-
175- if (systemMessage.trim()) {
176- msgs.unshift({
177- role: "system",
178- content: systemMessage,
179- });
180- }
181-
182- // Remove the "id" from all of the messages
183- return msgs.map((msg) => {
184- const { id, ...rest } = msg as any;
185- return rest;
186- });
187-}
added core/llm/defaultSystemMessages.ts +68 −0
@@ -0,0 +1,68 @@
1+export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
2+ "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts";
3+
4+export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL =
5+ "https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts";
6+
7+export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\
8+ Always include the language and file name in the info string when you write code blocks.
9+ If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
10+`;
11+
12+export const EDIT_CODE_INSTRUCTIONS = `\
13+ When addressing code modification requests, present a concise code snippet that
14+ emphasizes only the necessary changes and uses abbreviated placeholders for
15+ unmodified sections. For example:
16+
17+ \`\`\`language /path/to/file
18+ // ... existing code ...
19+
20+ {{ modified code here }}
21+
22+ // ... existing code ...
23+
24+ {{ another modification }}
25+
26+ // ... rest of code ...
27+ \`\`\`
28+
29+ In existing files, you should always restate the function or class that the snippet belongs to:
30+
31+ \`\`\`language /path/to/file
32+ // ... existing code ...
33+
34+ function exampleFunction() {
35+ // ... existing code ...
36+
37+ {{ modified code here }}
38+
39+ // ... rest of function ...
40+ }
41+
42+ // ... rest of code ...
43+ \`\`\`
44+
45+ Since users have access to their complete file, they prefer reading only the
46+ relevant modifications. It's perfectly acceptable to omit unmodified portions
47+ at the beginning, middle, or end of files using these "lazy" comments. Only
48+ provide the complete file when explicitly requested. Include a concise explanation
49+ of changes unless the user specifically asks for code only.
50+`;
51+
52+export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
53+<important_rules>
54+ You are in chat mode.
55+
56+ 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.
57+ If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
58+
59+${CODEBLOCK_FORMATTING_INSTRUCTIONS}
60+${EDIT_CODE_INSTRUCTIONS}
61+</important_rules>`;
62+
63+export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
64+<important_rules>
65+ You are in agent mode.
66+
67+${CODEBLOCK_FORMATTING_INSTRUCTIONS}
68+</important_rules>`;
modified core/llm/llms/Bedrock.test.ts +248 −80
@@ -1,12 +1,10 @@
1-import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
2-import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
3-import Bedrock from "./Bedrock.js";
41 import {
52 ChatMessage,
63 Chunk,
74 CompletionOptions,
85 UserChatMessage,
96 } from "../../index.js";
7+import Bedrock from "./Bedrock.js";
108
119 // Mock AWS SDK
1210 jest.mock("@aws-sdk/client-bedrock-runtime", () => ({
@@ -317,96 +315,266 @@
317315 });
318316 });
319317
320- it("should convert text messages correctly", () => {
321- const message: ChatMessage = {
322- role: "user",
323- content: "Hello",
324- } as UserChatMessage;
325- const converted = bedrock["_convertMessage"](message);
326- expect(converted).toEqual({
327- role: "user",
328- content: [{ text: "Hello" }],
329- });
318+ it("should convert simple user and assistant messages correctly", () => {
319+ const messages: ChatMessage[] = [
320+ { role: "user", content: "Hello" } as UserChatMessage,
321+ { role: "assistant", content: "Hi there" },
322+ ];
323+
324+ const availableTools = new Set<string>();
325+ const converted = bedrock["_convertMessages"](messages, availableTools);
326+
327+ expect(converted).toEqual([
328+ { role: "user", content: [{ text: "Hello" }] },
329+ { role: "assistant", content: [{ text: "Hi there" }] },
330+ ]);
330331 });
331332
332- it("should convert tool responses correctly", () => {
333- const message: ChatMessage = {
334- role: "tool",
335- content: "Tool result",
336- toolCallId: "tool-1",
337- };
338- const converted = bedrock["_convertMessage"](message);
339- expect(converted).toEqual({
340- role: "user",
341- content: [
342- {
343- toolResult: {
344- toolUseId: "tool-1",
345- content: [{ text: "Tool result" }],
333+ it("should handle tool responses correctly", () => {
334+ const messages: ChatMessage[] = [
335+ { role: "user", content: "Use a tool" } as UserChatMessage,
336+ {
337+ role: "assistant",
338+ content: "",
339+ toolCalls: [
340+ {
341+ id: "tool-1",
342+ type: "function",
343+ function: {
344+ name: "test_tool",
345+ arguments: '{"arg":"value"}',
346+ },
346347 },
347- },
348- ],
349- });
348+ ],
349+ },
350+ {
351+ role: "tool",
352+ content: "Tool result",
353+ toolCallId: "tool-1",
354+ },
355+ ];
356+
357+ const availableTools = new Set(["test_tool"]);
358+ const converted = bedrock["_convertMessages"](messages, availableTools);
359+
360+ expect(converted).toEqual([
361+ { role: "user", content: [{ text: "Use a tool" }] },
362+ {
363+ role: "assistant",
364+ content: [
365+ {
366+ toolUse: {
367+ toolUseId: "tool-1",
368+ name: "test_tool",
369+ input: { arg: "value" },
370+ },
371+ },
372+ ],
373+ },
374+ {
375+ role: "user",
376+ content: [
377+ {
378+ toolResult: {
379+ toolUseId: "tool-1",
380+ content: [{ text: "Tool result" }],
381+ },
382+ },
383+ ],
384+ },
385+ ]);
350386 });
351387
352- it("should convert tool calls correctly", () => {
353- const message: ChatMessage = {
354- role: "assistant",
355- content: "",
356- toolCalls: [
357- {
358- id: "tool-1",
359- type: "function" as const,
360- function: {
361- name: "test_tool",
362- arguments: '{"arg":"value"}',
388+ it("should handle tool calls with unavailable tools as text", () => {
389+ const messages: ChatMessage[] = [
390+ { role: "user", content: "Use a tool" } as UserChatMessage,
391+ {
392+ role: "assistant",
393+ content: "",
394+ toolCalls: [
395+ {
396+ id: "tool-1",
397+ type: "function",
398+ function: {
399+ name: "unavailable_tool",
400+ arguments: '{"arg":"value"}',
401+ },
363402 },
364- },
365- ],
366- };
367- const converted = bedrock["_convertMessage"](message);
368- expect(converted).toEqual({
369- role: "assistant",
370- content: [
371- {
372- toolUse: {
373- toolUseId: "tool-1",
374- name: "test_tool",
375- input: { arg: "value" },
403+ ],
404+ },
405+ ];
406+
407+ // Empty set means no tools are available
408+ const availableTools = new Set<string>();
409+ const converted = bedrock["_convertMessages"](messages, availableTools);
410+
411+ expect(converted).toEqual([
412+ { role: "user", content: [{ text: "Use a tool" }] },
413+ {
414+ role: "assistant",
415+ content: [
416+ {
417+ text: expect.stringContaining("Assistant tool call:"),
376418 },
377- },
378- ],
379- });
419+ ],
420+ },
421+ ]);
380422 });
381423
382- it("should handle multimodal content correctly", () => {
383- const message: ChatMessage = {
384- role: "user",
385- content: [
386- { type: "text", text: "Look at this image:" },
387- {
388- type: "imageUrl",
389- imageUrl: {
390- url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==",
424+ it("should handle thinking messages correctly", () => {
425+ const messages: ChatMessage[] = [
426+ { role: "user", content: "Think about this" } as UserChatMessage,
427+ { role: "thinking", content: "I am thinking about the solution" },
428+ { role: "assistant", content: "Here's my answer" },
429+ ];
430+
431+ const availableTools = new Set<string>();
432+ const converted = bedrock["_convertMessages"](messages, availableTools);
433+
434+ expect(converted).toEqual([
435+ { role: "user", content: [{ text: "Think about this" }] },
436+ {
437+ role: "assistant",
438+ content: [
439+ {
440+ reasoningContent: {
441+ reasoningText: {
442+ text: "I am thinking about the solution",
443+ signature: undefined,
444+ },
445+ },
391446 },
392- },
393- ],
394- } as UserChatMessage;
395- const converted = bedrock["_convertMessage"](message);
396- expect(converted).toEqual({
397- role: "user",
398- content: [
399- { text: "Look at this image:" },
400- {
401- image: {
402- format: "jpeg",
403- source: {
404- bytes: Buffer.from("/9j/4AAQSkZJRg==", "base64"),
447+ { text: "Here's my answer" },
448+ ],
449+ },
450+ ]);
451+ });
452+
453+ it("should handle redacted thinking messages", () => {
454+ const messages: ChatMessage[] = [
455+ { role: "user", content: "Think about this" } as UserChatMessage,
456+ {
457+ role: "thinking",
458+ content: "",
459+ redactedThinking: "redacted-content-bytes",
460+ },
461+ { role: "assistant", content: "Here's my answer" },
462+ ];
463+
464+ const availableTools = new Set<string>();
465+ const converted = bedrock["_convertMessages"](messages, availableTools);
466+
467+ expect(converted).toEqual([
468+ { role: "user", content: [{ text: "Think about this" }] },
469+ {
470+ role: "assistant",
471+ content: [
472+ {
473+ reasoningContent: {
474+ redactedContent: expect.any(Uint8Array),
405475 },
406476 },
407- },
408- ],
477+ { text: "Here's my answer" },
478+ ],
479+ },
480+ ]);
481+
482+ // Check that the Uint8Array contains the expected bytes
483+ const redactedContent =
484+ converted[1].content?.[0].reasoningContent?.redactedContent;
485+ expect(redactedContent).toBeInstanceOf(Uint8Array);
486+ expect(Buffer.from(redactedContent!).toString()).toBe(
487+ "redacted-content-bytes",
488+ );
489+ });
490+
491+ it("should convert multimodal content correctly", () => {
492+ const messages: ChatMessage[] = [
493+ {
494+ role: "user",
495+ content: [
496+ { type: "text", text: "Look at this image:" },
497+ {
498+ type: "imageUrl",
499+ imageUrl: {
500+ url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==",
501+ },
502+ },
503+ ],
504+ } as UserChatMessage,
505+ ];
506+
507+ const availableTools = new Set<string>();
508+ const converted = bedrock["_convertMessages"](messages, availableTools);
509+
510+ expect(converted).toEqual([
511+ {
512+ role: "user",
513+ content: [
514+ { text: "Look at this image:" },
515+ {
516+ image: {
517+ format: "jpeg",
518+ source: {
519+ bytes: expect.any(Uint8Array),
520+ },
521+ },
522+ },
523+ ],
524+ },
525+ ]);
526+
527+ // Check that the image bytes were processed correctly
528+ const imageBytes = converted[0].content?.[1].image?.source?.bytes;
529+ expect(imageBytes).toBeInstanceOf(Uint8Array);
530+ expect(Buffer.from(imageBytes!).toString("base64")).toBe(
531+ "/9j/4AAQSkZJRg==",
532+ );
533+ });
534+
535+ it("should add cache points for prompt caching when needed", () => {
536+ // Create a test instance with caching behavior enabled
537+ const bedrockWithCaching = new TestBedrock({
538+ apiKey: "test-key",
539+ model: "anthropic.claude-3-sonnet-20240229-v1:0",
540+ region: "us-east-1",
409541 });
542+
543+ // Set caching behavior
544+ bedrockWithCaching.cacheBehavior = {
545+ cacheConversation: true,
546+ cacheSystemMessage: true,
547+ };
548+
549+ const messages: ChatMessage[] = [
550+ { role: "system", content: "You are a helpful assistant" },
551+ { role: "user", content: "First message" } as UserChatMessage,
552+ { role: "assistant", content: "First response" },
553+ { role: "user", content: "Second message" } as UserChatMessage,
554+ ];
555+
556+ const availableTools = new Set<string>();
557+ const converted = bedrockWithCaching["_convertMessages"](
558+ messages,
559+ availableTools,
560+ );
561+
562+ // The last two user messages should have cache points
563+ // But we're not testing the system message here since it's handled separately
564+ expect(converted.length).toBe(3);
565+ expect(converted[0].role).toBe("user");
566+ expect(converted[0].content?.some((block) => block.cachePoint)).toBe(
567+ true,
568+ );
569+ expect(converted[1].role).toBe("assistant");
570+ expect(converted[2].role).toBe("user");
571+ expect(converted[2].content?.some((block) => block.cachePoint)).toBe(
572+ true,
573+ );
574+
575+ // Verify that text content includes a cache ID suffix
576+ const userMessageText = converted[0].content?.[0].text;
577+ expect(userMessageText).toMatch(/First message.+/);
410578 });
411579 });
412580 });
modified core/llm/llms/Bedrock.ts +236 −159
@@ -1,8 +1,10 @@
11 import {
22 BedrockRuntimeClient,
33 ContentBlock,
4+ ConversationRole,
45 ConverseStreamCommand,
56 ConverseStreamCommandOutput,
7+ ImageFormat,
68 InvokeModelCommand,
79 Message,
810 ToolConfiguration,
@@ -14,6 +16,7 @@
1416 Chunk,
1517 CompletionOptions,
1618 LLMOptions,
19+ MessageContent,
1720 } from "../../index.js";
1821 import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
1922 import { renderChatMessage, stripImages } from "../../util/messageContent.js";
@@ -289,8 +292,8 @@
289292 const systemMessage = stripImages(
290293 messages.find((m) => m.role === "system")?.content ?? "",
291294 );
292- const convertedMessages = this._convertMessages(messages);
293295
296+ // Prompt and system message caching settings
294297 const shouldCacheSystemMessage =
295298 (!!systemMessage && this.cacheBehavior?.cacheSystemMessage) ||
296299 this.completionOptions.promptCaching;
@@ -298,9 +301,7 @@
298301 shouldCacheSystemMessage ||
299302 this.cacheBehavior?.cacheConversation ||
300303 this.completionOptions.promptCaching;
301- const shouldCacheToolsConfig = this.completionOptions.promptCaching;
302304
303- // Add header for prompt caching
304305 if (enablePromptCaching) {
305306 this.requestOptions.headers = {
306307 ...this.requestOptions.headers,
@@ -308,30 +309,37 @@
308309 };
309310 }
310311
312+ // First get tools
311313 const supportsTools =
312314 (this.capabilities?.tools ||
313315 PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ??
314316 false;
315317
316- let toolConfig =
317- supportsTools && options.tools
318- ? ({
319- tools: options.tools.map((tool) => ({
320- toolSpec: {
321- name: tool.function.name,
322- description: tool.function.description,
323- inputSchema: {
324- json: tool.function.parameters,
325- },
326- },
327- })),
328- } as ToolConfiguration)
329- : undefined;
330-
331- if (toolConfig?.tools && shouldCacheToolsConfig) {
332- toolConfig.tools.push({ cachePoint: { type: "default" } });
318+ let toolConfig: undefined | ToolConfiguration = undefined;
319+ const availableTools = new Set<string>();
320+ if (supportsTools && options.tools && options.tools.length > 0) {
321+ toolConfig = {
322+ tools: options.tools.map((tool) => ({
323+ toolSpec: {
324+ name: tool.function.name,
325+ description: tool.function.description,
326+ inputSchema: {
327+ json: tool.function.parameters,
328+ },
329+ },
330+ })),
331+ } as ToolConfiguration;
332+ const shouldCacheToolsConfig = this.completionOptions.promptCaching;
333+ if (shouldCacheToolsConfig) {
334+ toolConfig.tools!.push({ cachePoint: { type: "default" } });
335+ }
336+ options.tools.forEach((tool) => {
337+ availableTools.add(tool.function.name);
338+ });
333339 }
334340
341+ const convertedMessages = this._convertMessages(messages, availableTools);
342+
335343 return {
336344 modelId: options.model,
337345 system: systemMessage
@@ -368,167 +376,236 @@
368376 };
369377 }
370378
371- private _convertMessage(
372- message: ChatMessage,
373- addCaching: boolean = false,
374- ): Message | null {
375- // Handle system messages explicitly
376- if (message.role === "system") {
377- return null;
378- }
379+ /*
380+ Converts the messages to the format expected by the Bedrock API.
381+
382+ */
383+ private _convertMessages(
384+ messages: ChatMessage[],
385+ availableTools: Set<string>,
386+ ): Message[] {
387+ let currentRole: "user" | "assistant" = "user";
388+ let currentBlocks: ContentBlock[] = [];
389+
390+ const converted: Message[] = [];
391+ const pushCurrentMessage = () => {
392+ if (currentBlocks.length === 0 && converted.length > 1) {
393+ throw new Error(
394+ `Bedrock: no content in ${currentRole} message before conversational turn change`,
395+ );
396+ }
397+ if (currentBlocks.length > 0) {
398+ converted.push({
399+ role: currentRole,
400+ content: currentBlocks,
401+ });
402+ }
403+ currentBlocks = [];
404+ };
379405
380- const cachePoint = addCaching
381- ? { cachePoint: { type: "default" } }
382- : undefined;
383-
384- // Tool response handling
385- if (message.role === "tool") {
386- return {
387- role: "user",
388- content: [
389- {
390- toolResult: {
391- toolUseId: message.toolCallId,
392- content: [
393- {
394- text: message.content || "",
406+ const nonSystemMessages = messages.filter((m) => m.role !== "system");
407+ const hasAddedToolCallIds = new Set<string>();
408+
409+ for (let idx = 0; idx < nonSystemMessages.length; idx++) {
410+ const message = nonSystemMessages[idx];
411+
412+ if (message.role === "user" || message.role === "tool") {
413+ // Detect conversational turn change
414+ if (currentRole !== ConversationRole.USER) {
415+ pushCurrentMessage();
416+ currentRole = ConversationRole.USER;
417+ }
418+
419+ // USER messages:
420+ // Non-empty user message content is converted to "text" and "image" blocks
421+ // If ANY user message part is cached, we add a single cache point block when we push the message
422+ if (message.role === "user") {
423+ const trimmedContent =
424+ typeof message.content === "string"
425+ ? message.content.trim()
426+ : message.content;
427+ if (trimmedContent) {
428+ currentBlocks.push(
429+ ...this._convertMessageContentToBlocks(trimmedContent),
430+ );
431+ }
432+ }
433+ // TOOL messages:
434+ // Tool messages are represented by "toolResult" blocks
435+ // toolResult blocks must follow valid toolUse blocks (which also verifies that the tool name is present in toolConfig)
436+ // If it doesn't, we convert it to a text block
437+ else if (message.role === "tool") {
438+ const trimmedContent = message.content.trim() || "No tool output";
439+ if (hasAddedToolCallIds.has(message.toolCallId)) {
440+ currentBlocks.push({
441+ toolResult: {
442+ toolUseId: message.toolCallId,
443+ content: [
444+ {
445+ text: trimmedContent,
446+ },
447+ ],
448+ },
449+ });
450+ } else {
451+ currentBlocks.push({
452+ text: `Tool call output for Tool Call ID ${message.toolCallId}:\n\n${trimmedContent}`,
453+ });
454+ }
455+ }
456+ } else if (message.role === "assistant" || message.role === "thinking") {
457+ // Detect conversational turn change
458+ if (currentRole !== ConversationRole.ASSISTANT) {
459+ pushCurrentMessage();
460+ currentRole = ConversationRole.ASSISTANT;
461+ }
462+
463+ // ASSISTANT messages:
464+ // Non-empty assistant message content is converted to "text" and "image" blocks
465+ if (message.role === "assistant") {
466+ const trimmedContent =
467+ typeof message.content === "string"
468+ ? message.content.trim()
469+ : message.content;
470+ if (trimmedContent) {
471+ currentBlocks.push(
472+ ...this._convertMessageContentToBlocks(trimmedContent),
473+ );
474+ }
475+ // TOOL CALLS:
476+ // Tool calls are represented by "toolUse" blocks
477+ // Each tool call must have an id and a function name
478+ // The function name must match one of the available tools
479+ // Otherwise, we will convert it to a text block (e.g. Chat mode will pass no tools)
480+ if (message.toolCalls) {
481+ for (const toolCall of message.toolCalls) {
482+ if (toolCall.id && toolCall.function?.name) {
483+ if (availableTools.has(toolCall.function.name)) {
484+ currentBlocks.push({
485+ toolUse: {
486+ toolUseId: toolCall.id,
487+ name: toolCall.function.name,
488+ input: safeParseToolCallArgs(toolCall),
489+ },
490+ });
491+ hasAddedToolCallIds.add(toolCall.id);
492+ } else {
493+ const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`;
494+ currentBlocks.push({
495+ text: toolCallText,
496+ });
497+ }
498+ } else {
499+ console.warn(
500+ `Bedrock: tool call missing id or name, skipping tool call: ${JSON.stringify(toolCall)}`,
501+ );
502+ continue;
503+ }
504+ }
505+ }
506+ } else if (message.role === "thinking") {
507+ // THINKING:
508+ // Thinking messages are represented by "reasoningContent" blocks which can have redacted content or reasoning content
509+ if (message.redactedThinking) {
510+ const block: ContentBlock.ReasoningContentMember = {
511+ reasoningContent: {
512+ redactedContent: new Uint8Array(
513+ Buffer.from(message.redactedThinking),
514+ ),
515+ },
516+ };
517+ currentBlocks.push(block);
518+ } else {
519+ const block: ContentBlock.ReasoningContentMember = {
520+ reasoningContent: {
521+ reasoningText: {
522+ text: (message.content as string) || "",
523+ signature: message.signature,
395524 },
396- ],
397- },
398- },
399- ],
400- };
525+ },
526+ };
527+ currentBlocks.push(block);
528+ }
529+ }
530+ }
401531 }
402-
403- // Tool calls handling
404- if (message.role === "assistant" && message.toolCalls) {
405- return {
406- role: "assistant",
407- content: message.toolCalls.map((toolCall) => ({
408- toolUse: {
409- toolUseId: toolCall.id,
410- name: toolCall.function?.name,
411- input: safeParseToolCallArgs(toolCall),
412- },
413- })),
414- };
532+ if (currentBlocks.length > 0) {
533+ pushCurrentMessage();
415534 }
416535
417- if (message.role === "thinking") {
418- if (message.redactedThinking) {
419- const content: ContentBlock.ReasoningContentMember = {
420- reasoningContent: {
421- redactedContent: new Uint8Array(
422- Buffer.from(message.redactedThinking),
423- ),
424- },
425- };
426- return {
427- role: "assistant",
428- content: [content],
429- };
430- } else {
431- const content: ContentBlock.ReasoningContentMember = {
432- reasoningContent: {
433- reasoningText: {
434- text: (message.content as string) || "",
435- signature: message.signature,
436- },
437- },
438- };
439- return {
440- role: "assistant",
441- content: [content],
442- };
443- }
536+ // If caching is enabled, we add cache_control parameter to the last two user messages
537+ // The second-to-last because it retrieves potentially already cached contents,
538+ // The last one because we want it cached for later retrieval.
539+ // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
540+ if (this.cacheBehavior?.cacheConversation) {
541+ this._addCachingToLastTwoUserMessages(converted);
444542 }
445543
446- // Standard text message
447- if (typeof message.content === "string") {
448- if (addCaching) {
449- message.content += getSecureID();
544+ return converted;
545+ }
546+
547+ private _addCachingToLastTwoUserMessages(converted: Message[]) {
548+ let numCached = 0;
549+ for (let i = converted.length - 1; i >= 0; i--) {
550+ const message = converted[i];
551+ if (message.role === "user") {
552+ message.content?.forEach((block) => {
553+ if (block.text) {
554+ block.text += getSecureID();
555+ }
556+ });
557+ message.content?.push({ cachePoint: { type: "default" } });
558+ numCached++;
450559 }
451- const content: any[] = [{ text: message.content }];
452- if (addCaching) {
453- content.push({ cachePoint: { type: "default" } });
560+ if (numCached === 2) {
561+ break;
454562 }
455- return {
456- role: message.role,
457- content,
458- };
459563 }
564+ }
460565
461- // Improved multimodal content handling
462- if (Array.isArray(message.content)) {
463- const content: any[] = [];
464-
465- // Process all parts first
466- message.content.forEach((part) => {
566+ // Converts Continue message content (string/parts) to Bedrock ContentBlock format.
567+ // Unsupported/problematic image formats are skipped with a warning.
568+ private _convertMessageContentToBlocks(
569+ content: MessageContent,
570+ ): ContentBlock[] {
571+ const blocks: ContentBlock[] = [];
572+ if (typeof content === "string") {
573+ blocks.push({ text: content });
574+ } else {
575+ for (const part of content) {
467576 if (part.type === "text") {
468- if (addCaching) {
469- part.text += getSecureID();
470- }
471- content.push({ text: part.text });
577+ blocks.push({ text: part.text });
472578 } else if (part.type === "imageUrl" && part.imageUrl) {
473579 try {
474580 const [mimeType, base64Data] = part.imageUrl.url.split(",");
475581 const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
476- content.push({
477- image: {
478- format,
479- source: {
480- bytes: Buffer.from(base64Data, "base64"),
582+ if (
583+ format === ImageFormat.JPEG ||
584+ format === ImageFormat.PNG ||
585+ format === ImageFormat.WEBP ||
586+ format === ImageFormat.GIF
587+ ) {
588+ blocks.push({
589+ image: {
590+ format,
591+ source: {
592+ bytes: Uint8Array.from(Buffer.from(base64Data, "base64")),
593+ },
481594 },
482- },
483- });
595+ });
596+ } else {
597+ console.warn(
598+ `Bedrock: skipping unsupported image part format: ${format}`,
599+ part,
600+ );
601+ }
484602 } catch (error) {
485- console.warn(`Failed to process image: ${error}`);
603+ console.warn("Bedrock: failed to process image part", error, part);
486604 }
487605 }
488- });
489-
490- // Add cache point as a separate block at the end if needed
491- if (addCaching && content.length > 0) {
492- content.push({ cachePoint: { type: "default" } });
493606 }
494-
495- return {
496- role: message.role,
497- content,
498- } as Message;
499607 }
500- return null;
501- }
502-
503- private _convertMessages(messages: ChatMessage[]): any[] {
504- const filteredmessages = messages.filter(
505- (m) => m.role !== "system" && !!m.content,
506- );
507- const lastTwoUserMsgIndices = filteredmessages
508- .map((msg, index) => (msg.role === "user" ? index : -1))
509- .filter((index) => index !== -1)
510- .slice(-2);
511-
512- const converted = filteredmessages
513- .map((message, filteredMsgIdx) => {
514- // Add cache_control parameter to the last two user messages
515- // The second-to-last because it retrieves potentially already cached contents,
516- // The last one because we want it cached for later retrieval.
517- // See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
518- const addCaching =
519- this.cacheBehavior?.cacheConversation &&
520- lastTwoUserMsgIndices.includes(filteredMsgIdx);
521-
522- try {
523- return this._convertMessage(message, addCaching);
524- } catch (error) {
525- console.error(`Failed to convert message: ${error}`);
526- return null;
527- }
528- })
529- .filter(Boolean);
530-
531- return converted;
608+ return blocks;
532609 }
533610
534611 private async _getCredentials() {
modified core/llm/llms/index.ts +1 −1
@@ -8,7 +8,7 @@
88 LLMOptions,
99 } from "../..";
1010 import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString";
11-import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages";
11+import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../defaultSystemMessages";
1212 import { BaseLLM } from "../index";
1313 import Anthropic from "./Anthropic";
1414 import Asksage from "./Asksage";
modified core/llm/rules/getSystemMessageWithRules.ts +17 −8
@@ -327,27 +327,36 @@
327327 export const getSystemMessageWithRules = ({
328328 baseSystemMessage,
329329 userMessage,
330- rules,
330+ availableRules,
331331 contextItems,
332332 rulePolicies = {},
333333 }: {
334334 baseSystemMessage?: string;
335335 userMessage: UserChatMessage | ToolResultChatMessage | undefined;
336- rules: RuleWithSource[];
336+ availableRules: RuleWithSource[];
337337 contextItems: ContextItemWithId[];
338338 rulePolicies?: RulePolicies;
339-}) => {
340- const applicableRules = getApplicableRules(
339+}): {
340+ systemMessage: string;
341+ appliedRules: RuleWithSource[];
342+} => {
343+ const appliedRules = getApplicableRules(
341344 userMessage,
342- rules,
345+ availableRules,
343346 contextItems,
344347 rulePolicies,
345348 );
346349 let systemMessage = baseSystemMessage ?? "";
347350
348- for (const rule of applicableRules) {
349- systemMessage += `\n\n${rule.rule}`;
351+ for (const rule of appliedRules) {
352+ if (systemMessage) {
353+ systemMessage += "\n\n";
354+ }
355+ systemMessage += rule.rule;
350356 }
351357
352- return systemMessage;
358+ return {
359+ systemMessage,
360+ appliedRules,
361+ };
353362 };
modified core/tools/definitions/editFile.ts +1 −1
@@ -1,5 +1,5 @@
11 import { Tool } from "../..";
2-import { EDIT_CODE_INSTRUCTIONS } from "../../llm/constructMessages";
2+import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages";
33 import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
44
55 export interface EditToolArgs {
modified core/util/findLast.ts +3 −3
@@ -1,6 +1,6 @@
1-export function findLastIndex(
2- arr: any[],
3- criterion: (item: any) => boolean,
1+export function findLastIndex<T = any>(
2+ arr: T[],
3+ criterion: (item: T) => boolean,
44 ): number {
55 let lastIndex = -1;
66
modified extensions/vscode/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/src/components/AcceptRejectDiffButtons.tsx +17 −1
@@ -2,6 +2,9 @@
22 import { ApplyState } from "core";
33 import { useContext } from "react";
44 import { IdeMessengerContext } from "../context/IdeMessenger";
5+import { useAppDispatch, useAppSelector } from "../redux/hooks";
6+import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall";
7+import { cancelToolCall } from "../redux/slices/sessionSlice";
58 import { getMetaKeyLabel } from "../util";
69 import { ToolTip } from "./gui/Tooltip";
710
@@ -20,8 +23,21 @@
2023 (state) => state.status === "done",
2124 );
2225 const ideMessenger = useContext(IdeMessengerContext);
23-
26+ const currentToolCallApplyState = useAppSelector(
27+ selectCurrentToolCallApplyState,
28+ );
29+ const dispatch = useAppDispatch();
2430 async function handleAcceptOrReject(status: AcceptOrRejectOutcome) {
31+ if (
32+ status === "rejectDiff" &&
33+ currentToolCallApplyState?.status === "done"
34+ ) {
35+ dispatch(
36+ cancelToolCall({
37+ toolCallId: currentToolCallApplyState.toolCallId!,
38+ }),
39+ );
40+ }
2541 for (const { filepath = "", streamId } of pendingApplyStates) {
2642 ideMessenger.post(status, {
2743 filepath,
modified gui/src/components/mainInput/InputToolbar.tsx +1 −13
@@ -9,10 +9,6 @@
99 import { IdeMessengerContext } from "../../context/IdeMessenger";
1010 import { useAppDispatch, useAppSelector } from "../../redux/hooks";
1111 import { selectUseActiveFile } from "../../redux/selectors";
12-import {
13- selectCurrentToolCall,
14- selectCurrentToolCallApplyState,
15-} from "../../redux/selectors/selectCurrentToolCall";
1612 import { selectSelectedChatModel } from "../../redux/slices/configSlice";
1713 import { setHasReasoningEnabled } from "../../redux/slices/sessionSlice";
1814 import { exitEdit } from "../../redux/thunks/edit";
@@ -53,20 +49,12 @@
5349 const useActiveFile = useAppSelector(selectUseActiveFile);
5450 const isInEdit = useAppSelector((store) => store.session.isInEdit);
5551 const codeToEdit = useAppSelector((store) => store.editModeState.codeToEdit);
56- const toolCallState = useAppSelector(selectCurrentToolCall);
57- const currentToolCallApplyState = useAppSelector(
58- selectCurrentToolCallApplyState,
59- );
6052 const hasReasoningEnabled = useAppSelector(
6153 (store) => store.session.hasReasoningEnabled,
6254 );
6355
6456 const isEnterDisabled =
65- props.disabled ||
66- (isInEdit && codeToEdit.length === 0) ||
67- toolCallState?.status === "generated" ||
68- (currentToolCallApplyState &&
69- currentToolCallApplyState.status !== "closed");
57+ props.disabled || (isInEdit && codeToEdit.length === 0);
7058
7159 const toolsSupported = defaultModel && modelSupportsTools(defaultModel);
7260
modified gui/src/components/mainInput/Lump/LumpToolbar/LumpToolbar.tsx +6 −2
@@ -2,8 +2,8 @@
22 import { useSelector } from "react-redux";
33 import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
44 import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall";
5+import { cancelToolCall } from "../../../../redux/slices/sessionSlice";
56 import { callCurrentTool } from "../../../../redux/thunks/callCurrentTool";
6-import { cancelCurrentToolCall } from "../../../../redux/thunks/cancelCurrentToolCall";
77 import { isJetBrains } from "../../../../util";
88 import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar";
99 import { EditOutcomeToolbar } from "./EditOutcomeToolbar";
@@ -50,7 +50,11 @@
5050 } else if ((jetbrains ? altKey : metaKey) && event.key === "Backspace") {
5151 event.preventDefault();
5252 event.stopPropagation();
53- void dispatch(cancelCurrentToolCall());
53+ void dispatch(
54+ cancelToolCall({
55+ toolCallId: toolCallState.toolCallId,
56+ }),
57+ );
5458 }
5559 };
5660
modified gui/src/components/mainInput/Lump/LumpToolbar/PendingToolCallToolbar.tsx +15 −3
@@ -1,7 +1,8 @@
11 import styled from "styled-components";
2-import { useAppDispatch } from "../../../../redux/hooks";
2+import { useAppDispatch, useAppSelector } from "../../../../redux/hooks";
3+import { selectCurrentToolCall } from "../../../../redux/selectors/selectCurrentToolCall";
4+import { cancelToolCall } from "../../../../redux/slices/sessionSlice";
35 import { callCurrentTool } from "../../../../redux/thunks/callCurrentTool";
4-import { cancelCurrentToolCall } from "../../../../redux/thunks/cancelCurrentToolCall";
56 import {
67 getAltKeyLabel,
78 getFontSize,
@@ -27,6 +28,7 @@
2728 export function PendingToolCallToolbar() {
2829 const dispatch = useAppDispatch();
2930 const jetbrains = isJetBrains();
31+ const currentToolCall = useAppSelector(selectCurrentToolCall);
3032
3133 return (
3234 <Container>
@@ -37,7 +39,17 @@
3739 <div className="flex gap-2 pb-0.5">
3840 <StopButton
3941 className="text-description"
40- onClick={() => dispatch(cancelCurrentToolCall())}
42+ onClick={
43+ currentToolCall
44+ ? () => {
45+ dispatch(
46+ cancelToolCall({
47+ toolCallId: currentToolCall.toolCallId,
48+ }),
49+ );
50+ }
51+ : undefined
52+ }
4153 data-testid="reject-tool-call-button"
4254 >
4355 {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
modified gui/src/components/mainInput/Lump/sections/RulesSection.tsx +1 −1
@@ -10,7 +10,7 @@
1010 DEFAULT_AGENT_SYSTEM_MESSAGE_URL,
1111 DEFAULT_CHAT_SYSTEM_MESSAGE,
1212 DEFAULT_CHAT_SYSTEM_MESSAGE_URL,
13-} from "core/llm/constructMessages";
13+} from "core/llm/defaultSystemMessages";
1414 import { useContext, useMemo } from "react";
1515 import { useAuth } from "../../../../context/Auth";
1616 import { IdeMessengerContext } from "../../../../context/IdeMessenger";
modified gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx +26 −31
@@ -123,40 +123,35 @@
123123 return (
124124 <div
125125 onClick={() => openContextItem(contextItem, ideMessenger)}
126- 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"
126+ 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"
127127 data-testid="context-items-peek-item"
128128 >
129- <div className="flex w-full items-center">
130- {getContextItemIcon()}
131- <div className="flex min-w-0 flex-1 gap-2 text-xs">
132- <div
133- className={`max-w-[50%] flex-shrink-0 truncate ${isUrl ? "hover:underline" : ""}`}
134- >
135- {contextItem.name}
136- </div>
137- <div
138- className={`min-w-0 flex-1 overflow-hidden truncate whitespace-nowrap text-xs text-gray-400 ${isUrl ? "hover:underline" : ""}`}
139- onClick={
140- isUrl
141- ? (e) => {
142- if (contextItem.uri?.value) {
143- e.stopPropagation();
144- ideMessenger.post("openUrl", contextItem.uri.value);
145- } else {
146- console.error("Couldn't open url", contextItem.uri);
147- }
148- }
149- : undefined
150- }
151- >
152- {contextItem.uri?.type === "file"
153- ? getUriPathBasename(contextItem.description)
154- : contextItem.description}
155- </div>
156- </div>
157-
129+ {getContextItemIcon()}
130+ <span className={`line-clamp-1 max-w-[130px] flex-shrink-0`}>
131+ {contextItem.name}
132+ </span>
133+ <div
134+ className={`group flex flex-row items-center gap-1.5 pr-1.5 text-xs text-gray-400 ${isUrl ? "hover:underline" : ""}`}
135+ onClick={
136+ isUrl
137+ ? (e) => {
138+ if (contextItem.uri?.value) {
139+ e.stopPropagation();
140+ ideMessenger.post("openUrl", contextItem.uri.value);
141+ } else {
142+ console.error("Couldn't open url", contextItem.uri);
143+ }
144+ }
145+ : undefined
146+ }
147+ >
148+ <span className={`line-clamp-1 flex-1 break-all`}>
149+ {contextItem.uri?.type === "file"
150+ ? getUriPathBasename(contextItem.description)
151+ : contextItem.description}
152+ </span>
158153 {isUrl && (
159- <ArrowTopRightOnSquareIcon className="mx-2 h-4 w-4 flex-shrink-0 text-gray-400 opacity-0 group-hover:opacity-100" />
154+ <ArrowTopRightOnSquareIcon className="h-3 w-3 flex-shrink-0 text-gray-400 opacity-80 group-hover:opacity-100" />
160155 )}
161156 </div>
162157 </div>
modified gui/src/hooks/ParallelListeners.tsx +5 −6
@@ -268,7 +268,6 @@
268268 currentToolCallApplyState.streamId === state.streamId
269269 ) {
270270 if (state.status === "done" && autoAcceptEditToolDiffs) {
271- console.log("AUTO ACCEPTED");
272271 ideMessenger.post("acceptDiff", {
273272 streamId: state.streamId,
274273 filepath: state.filepath,
@@ -281,6 +280,11 @@
281280 toolCallId: currentToolCallApplyState.toolCallId!,
282281 }),
283282 );
283+ void dispatch(
284+ streamResponseAfterToolCall({
285+ toolCallId: currentToolCallApplyState.toolCallId!,
286+ }),
287+ );
284288 }
285289 // const output: ContextItem = {
286290 // name: "Edit tool output",
@@ -288,11 +292,6 @@
288292 // description: "",
289293 // };
290294 // dispatch(setToolCallOutput([]));
291- void dispatch(
292- streamResponseAfterToolCall({
293- toolCallId: currentToolCallApplyState.toolCallId!,
294- }),
295- );
296295 }
297296 }
298297 }
added gui/src/pages/gui/ToolCallDiv/toolCallStateToContextItem.ts +27 −0
@@ -0,0 +1,27 @@
1+import { ContextItem, ContextItemWithId, ToolCallState } from "core";
2+
3+export function toolCallStateToContextItems(
4+ toolCallState: ToolCallState | undefined,
5+): ContextItemWithId[] {
6+ if (!toolCallState) {
7+ return [];
8+ }
9+ return (
10+ toolCallState.output?.map((ctxItem) =>
11+ toolCallCtxItemToCtxItemWithId(ctxItem, toolCallState.toolCallId),
12+ ) ?? []
13+ );
14+}
15+
16+export function toolCallCtxItemToCtxItemWithId(
17+ ctxItem: ContextItem,
18+ toolCallId: string,
19+): ContextItemWithId {
20+ return {
21+ ...ctxItem,
22+ id: {
23+ providerTitle: "toolCall",
24+ itemId: toolCallId,
25+ },
26+ };
27+}
modified gui/src/redux/slices/sessionSlice.ts +47 −12
@@ -20,13 +20,18 @@
2020 SessionMetadata,
2121 } from "core";
2222 import { NEW_SESSION_TITLE } from "core/util/constants";
23-import { renderChatMessage } from "core/util/messageContent";
23+import {
24+ renderChatMessage,
25+ renderContextItems,
26+} from "core/util/messageContent";
2427 import { findUriInDirs, getUriPathBasename } from "core/util/uri";
28+import { findLastIndex } from "lodash";
2529 import { v4 as uuidv4 } from "uuid";
30+import { toolCallCtxItemToCtxItemWithId } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem";
2631 import { addToolCallDeltaToState } from "../../util/toolCallState";
2732 import { RootState } from "../store";
2833 import { streamResponseThunk } from "../thunks/streamResponse";
29-import { findCurrentToolCall, findToolCall } from "../util";
34+import { findCurrentToolCall, findToolCall, findToolOutput } from "../util";
3035
3136 const getIdeMessenger = () => (window as any).ideMessenger;
3237
@@ -107,19 +112,39 @@
107112 curMessage.isGatheringContext = payload;
108113 }
109114 },
110- clearLastEmptyResponse: (state) => {
115+ clearDanglingMessages: (state) => {
116+ // This is used during cancellation
117+ // After the last user or tool message, we can have thinking and or valid assitant message (content or generated tool calls) OR nothing.
118+ // The only thing allowed after the last assistant message that has either content or generated tool calls
119+ // is a user or tool message
111120 if (state.history.length < 2) {
112121 return;
113122 }
114- const lastMessage = state.history[state.history.length - 1];
123+ const lastUserOrToolIdx = findLastIndex(
124+ state.history,
125+ (item) => item.message.role === "tool" || item.message.role === "user",
126+ );
127+
128+ let validAssistantMessageIdx = -1;
129+ for (let i = state.history.length - 1; i > lastUserOrToolIdx; i--) {
130+ const message = state.history[i];
131+ if (
132+ message.message.content ||
133+ message.toolCallState?.status !== "generating"
134+ ) {
135+ validAssistantMessageIdx = i;
136+ // Cancel any tool calls that are dangling and generated
137+ if (message.toolCallState?.status === "generated") {
138+ message.toolCallState.status = "canceled";
139+ }
140+ break;
141+ }
142+ }
115143
116- // Only clear in the case of an empty message
117- if (!lastMessage.message.content.length) {
118- state.mainEditorContentTrigger =
119- state.history[state.history.length - 2].editorState;
120- state.history = state.history.slice(0, -2);
121- // TODO is this logic correct for tool use conversations?
122- // Maybe slice at last index of "user" role message?
144+ if (validAssistantMessageIdx === -1) {
145+ state.history = state.history.slice(0, lastUserOrToolIdx + 1);
146+ } else {
147+ state.history = state.history.slice(0, validAssistantMessageIdx + 1);
123148 }
124149 },
125150 // Trigger value picked up by editor with isMainInput to set its content
@@ -527,6 +552,7 @@
527552 contextItems: ContextItem[];
528553 }>,
529554 ) => {
555+ // Update tool call state and corresponding tool output message
530556 const toolCallState = findToolCall(
531557 state.history,
532558 action.payload.toolCallId,
@@ -534,6 +560,15 @@
534560 if (toolCallState) {
535561 toolCallState.output = action.payload.contextItems;
536562 }
563+ const toolItem = findToolOutput(state.history, action.payload.toolCallId);
564+ if (toolItem) {
565+ toolItem.message.content = renderContextItems(
566+ action.payload.contextItems,
567+ );
568+ toolItem.contextItems = action.payload.contextItems.map((item) =>
569+ toolCallCtxItemToCtxItemWithId(item, action.payload.toolCallId),
570+ );
571+ }
537572 },
538573 cancelToolCall: (
539574 state,
@@ -679,7 +714,7 @@
679714 setActive,
680715 submitEditorAndInitAtIndex,
681716 updateHistoryItemAtIndex,
682- clearLastEmptyResponse,
717+ clearDanglingMessages,
683718 setMainEditorContentTrigger,
684719 deleteMessage,
685720 setIsGatheringContext,
deleted gui/src/redux/thunks/cancelCurrentToolCall.ts +0 −50
@@ -1,50 +0,0 @@
1-import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
2-import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
3-import { cancelToolCall, updateToolCallOutput } from "../slices/sessionSlice";
4-import { ThunkApiType } from "../store";
5-import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall";
6-
7-export const cancelCurrentToolCall = createAsyncThunk<
8- void,
9- undefined,
10- ThunkApiType
11->("chat/cancelTool", async (_, { dispatch, extra, getState }) => {
12- const state = getState();
13- const toolCallState = selectCurrentToolCall(state);
14-
15- if (!toolCallState) {
16- return;
17- }
18-
19- if (toolCallState.status !== "generated") {
20- return;
21- }
22-
23- const { toolCallId } = toolCallState;
24- dispatch(
25- cancelToolCall({
26- toolCallId,
27- }),
28- );
29-
30- dispatch(
31- updateToolCallOutput({
32- toolCallId,
33- contextItems: [
34- {
35- name: "Tool Cancelled",
36- description: "Tool Cancelled",
37- content:
38- "The tool call was cancelled by the user. Please try something else or request further instructions.",
39- hidden: true,
40- },
41- ],
42- }),
43- );
44- const output = await dispatch(
45- streamResponseAfterToolCall({
46- toolCallId,
47- }),
48- );
49- unwrapResult(output);
50-});
modified gui/src/redux/thunks/cancelStream.ts +3 −5
@@ -1,7 +1,7 @@
11 import { createAsyncThunk } from "@reduxjs/toolkit";
22 import {
33 abortStream,
4- clearLastEmptyResponse,
4+ clearDanglingMessages,
55 setInactive,
66 } from "../slices/sessionSlice";
77 import { ThunkApiType } from "../store";
@@ -12,9 +12,7 @@
1212 dispatch(setInactive());
1313 dispatch(abortStream());
1414
15- // In the case tool calls were being generated,
16- // Replace them with
17- // If the assistant message is empty, then remove it and the user message, placing the user input in the main text box
18- dispatch(clearLastEmptyResponse());
15+ // Clear any dangling incomplete tool calls, thinking messages, etc.
16+ dispatch(clearDanglingMessages());
1917 },
2018 );
modified gui/src/redux/thunks/streamNormalInput.ts +41 −13
@@ -1,5 +1,5 @@
11 import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
2-import { ChatMessage, LLMFullCompletionOptions } from "core";
2+import { LLMFullCompletionOptions } from "core";
33 import { modelSupportsTools } from "core/llm/autodetect";
44 import { ToCoreProtocol } from "core/protocol";
55 import { selectActiveTools } from "../selectors/selectActiveTools";
@@ -9,38 +9,40 @@
99 abortStream,
1010 addPromptCompletionPair,
1111 setActive,
12+ setAppliedRulesAtIndex,
1213 setInactive,
1314 setToolGenerated,
1415 streamUpdate,
1516 } from "../slices/sessionSlice";
1617 import { ThunkApiType } from "../store";
18+import {
19+ constructMessages,
20+ getBaseSystemMessage,
21+} from "../util/constructMessages";
1722 import { callCurrentTool } from "./callCurrentTool";
1823
1924 export const streamNormalInput = createAsyncThunk<
2025 void,
2126 {
22- messages: ChatMessage[];
2327 legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"];
2428 },
2529 ThunkApiType
2630 >(
2731 "chat/streamNormalInput",
28- async (
29- { messages, legacySlashCommandData },
30- { dispatch, extra, getState },
31- ) => {
32- // Gather state
32+ async ({ legacySlashCommandData }, { dispatch, extra, getState }) => {
3333 const state = getState();
3434 const selectedChatModel = selectSelectedChatModel(state);
3535
36- const streamAborter = state.session.streamAborter;
3736 if (!selectedChatModel) {
38- throw new Error("Default model not defined");
37+ throw new Error("No chat model selected");
3938 }
4039
41- let completionOptions: LLMFullCompletionOptions = {};
40+ // Get tools
4241 const activeTools = selectActiveTools(state);
4342 const toolsSupported = modelSupportsTools(selectedChatModel);
43+
44+ // Construct completion options
45+ let completionOptions: LLMFullCompletionOptions = {};
4446 if (toolsSupported && activeTools.length > 0) {
4547 completionOptions = {
4648 tools: activeTools,
@@ -55,20 +57,46 @@
5557 };
5658 }
5759
60+ // Construct messages (excluding system message)
61+ const baseSystemMessage = getBaseSystemMessage(
62+ state.session.mode,
63+ selectedChatModel,
64+ );
65+
66+ const withoutMessageIds = state.session.history.map((item) => {
67+ const { id, ...messageWithoutId } = item.message;
68+ return { ...item, message: messageWithoutId };
69+ });
70+ const { messages, appliedRules, appliedRuleIndex } = constructMessages(
71+ withoutMessageIds,
72+ baseSystemMessage,
73+ state.config.config.rules,
74+ state.ui.ruleSettings,
75+ );
76+
77+ // TODO parallel tool calls will cause issues with this
78+ // because there will be multiple tool messages, so which one should have applied rules?
79+ dispatch(
80+ setAppliedRulesAtIndex({
81+ index: appliedRuleIndex,
82+ appliedRules: appliedRules,
83+ }),
84+ );
85+
5886 dispatch(setActive());
5987
60- // Send request
88+ // Send request and stream response
89+ const streamAborter = state.session.streamAborter;
6190 const gen = extra.ideMessenger.llmStreamChat(
6291 {
6392 completionOptions,
6493 title: selectedChatModel.title,
65- messages,
94+ messages: messages,
6695 legacySlashCommandData,
6796 },
6897 streamAborter.signal,
6998 );
7099
71- // Stream response
72100 let next = await gen.next();
73101 while (!next.done) {
74102 if (!getState().session.isStreaming) {
modified gui/src/redux/thunks/streamResponse.ts +2 −48
@@ -1,15 +1,11 @@
11 import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
22 import { JSONContent } from "@tiptap/core";
3-import { InputModifiers, ToolResultChatMessage, UserChatMessage } from "core";
4-import { constructMessages } from "core/llm/constructMessages";
5-import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules";
3+import { InputModifiers } from "core";
64 import posthog from "posthog-js";
75 import { v4 as uuidv4 } from "uuid";
86 import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent";
9-import { getBaseSystemMessage } from "../../util";
107 import { selectSelectedChatModel } from "../slices/configSlice";
118 import {
12- setAppliedRulesAtIndex,
139 submitEditorAndInitAtIndex,
1410 updateHistoryItemAtIndex,
1511 } from "../slices/sessionSlice";
@@ -77,7 +73,7 @@
7773 .map((item) => item.uri!.value),
7874 ...selectedCode.map((rif) => rif.filepath),
7975 ];
80- dispatch(updateFileSymbolsFromFiles(filesForSymbols));
76+ void dispatch(updateFileSymbolsFromFiles(filesForSymbols));
8177
8278 dispatch(
8379 updateHistoryItemAtIndex({
@@ -93,47 +89,6 @@
9389 }),
9490 );
9591
96- // Get updated history after the update
97- const updatedHistory = getState().session.history;
98-
99- // Determine which rules apply to this message
100- const userMsg = updatedHistory[inputIndex].message;
101- const rules = getState().config.config.rules;
102- const rulePolicies = getState().ui.ruleSettings;
103-
104- // Calculate applicable rules once
105- // We need to check the message type to match what getApplicableRules expects
106- const applicableRules = getApplicableRules(
107- userMsg.role === "user" || userMsg.role === "tool"
108- ? (userMsg as UserChatMessage | ToolResultChatMessage)
109- : undefined,
110- rules,
111- selectedContextItems,
112- rulePolicies,
113- );
114-
115- // Store in history for UI display
116- dispatch(
117- setAppliedRulesAtIndex({
118- index: inputIndex,
119- appliedRules: applicableRules,
120- }),
121- );
122-
123- const messageMode = getState().session.mode;
124- const baseChatOrAgentSystemMessage = getBaseSystemMessage(
125- selectedChatModel,
126- messageMode,
127- );
128-
129- const messages = constructMessages(
130- messageMode,
131- [...updatedHistory],
132- baseChatOrAgentSystemMessage,
133- applicableRules,
134- rulePolicies,
135- );
136-
13792 posthog.capture("step run", {
13893 step_name: "User Input",
13994 params: {},
@@ -150,7 +105,6 @@
150105 unwrapResult(
151106 await dispatch(
152107 streamNormalInput({
153- messages,
154108 legacySlashCommandData: legacyCommandWithInput
155109 ? {
156110 command: legacyCommandWithInput.command,
modified gui/src/redux/thunks/streamResponseAfterToolCall.ts +3 −39
@@ -1,10 +1,7 @@
11 import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
22 import { ChatMessage } from "core";
3-import { constructMessages } from "core/llm/constructMessages";
43 import { renderContextItems } from "core/util/messageContent";
5-import { getBaseSystemMessage } from "../../util";
6-import { selectSelectedChatModel } from "../slices/configSlice";
7-import { addContextItemsAtIndex, streamUpdate } from "../slices/sessionSlice";
4+import { streamUpdate } from "../slices/sessionSlice";
85 import { ThunkApiType } from "../store";
96 import { findToolCall } from "../util";
107 import { resetStateForNewMessage } from "./resetStateForNewMessage";
@@ -21,15 +18,8 @@
2118 await dispatch(
2219 streamThunkWrapper(async () => {
2320 const state = getState();
24- const initialHistory = state.session.history;
25- const selectedChatModel = selectSelectedChatModel(state);
26-
27- if (!selectedChatModel) {
28- throw new Error("No model selected");
29- }
3021
3122 const toolCallState = findToolCall(state.session.history, toolCallId);
32-
3323 if (!toolCallState) {
3424 return; // in cases where edit tool is cancelled mid apply, this will be triggered
3525 }
@@ -40,41 +30,15 @@
4030
4131 await new Promise((resolve) => setTimeout(resolve, 0));
4232
33+ // TODO parallel tool calls - dispatch one tool message per tool call
4334 const newMessage: ChatMessage = {
4435 role: "tool",
4536 content: renderContextItems(toolOutput),
4637 toolCallId,
4738 };
4839 dispatch(streamUpdate([newMessage]));
49- dispatch(
50- addContextItemsAtIndex({
51- index: initialHistory.length,
52- contextItems: toolOutput.map((contextItem) => ({
53- ...contextItem,
54- id: {
55- providerTitle: "toolCall",
56- itemId: toolCallId,
57- },
58- })),
59- }),
60- );
61-
62- const updatedHistory = getState().session.history;
63- const messageMode = getState().session.mode;
64-
65- const baseChatOrAgentSystemMessage = getBaseSystemMessage(
66- selectedChatModel,
67- messageMode,
68- );
69-
70- const messages = constructMessages(
71- messageMode,
72- [...updatedHistory],
73- baseChatOrAgentSystemMessage,
74- state.config.config.rules,
75- );
7640
77- unwrapResult(await dispatch(streamNormalInput({ messages })));
41+ unwrapResult(await dispatch(streamNormalInput({})));
7842 }),
7943 );
8044 },
modified gui/src/redux/thunks/streamThunkWrapper.tsx +1 −1
@@ -22,7 +22,7 @@
2222 );
2323 }
2424 } catch (e) {
25- dispatch(cancelStream());
25+ await dispatch(cancelStream());
2626 dispatch(setDialogMessage(<StreamErrorDialog error={e} />));
2727 dispatch(setShowDialog(true));
2828 }
added gui/src/redux/util/constructMessages.test.ts +734 −0
@@ -0,0 +1,734 @@
1+import {
2+ AssistantChatMessage,
3+ ChatHistoryItem,
4+ ChatMessage,
5+ ContextItemWithId,
6+ ModelDescription,
7+ RuleWithSource,
8+ ThinkingChatMessage,
9+ ToolResultChatMessage,
10+ UserChatMessage,
11+} from "core";
12+import {
13+ DEFAULT_AGENT_SYSTEM_MESSAGE,
14+ DEFAULT_CHAT_SYSTEM_MESSAGE,
15+} from "core/llm/defaultSystemMessages";
16+import { renderChatMessage } from "core/util/messageContent";
17+import { beforeEach, describe, expect, test, vi } from "vitest";
18+import {
19+ CANCELLED_TOOL_CALL_MESSAGE,
20+ constructMessages,
21+ getBaseSystemMessage,
22+ NO_TOOL_CALL_OUTPUT_MESSAGE,
23+} from "./constructMessages";
24+
25+// For these tests we will mock the rules to simulate different scenarios
26+const CONTEXT_RULE: RuleWithSource = {
27+ source: "rules-block",
28+ rule: "CONTEXT_RULE",
29+ description: "CONTEXT_TRIGGER",
30+};
31+const LAST_MESSAGE_RULE: RuleWithSource = {
32+ source: "rules-block",
33+ rule: "LAST_MESSAGE_RULE",
34+ description: "LAST_MESSAGE_TRIGGER",
35+};
36+const NORMAL_RULE: RuleWithSource = {
37+ source: "rules-block",
38+ rule: "Always apply rule",
39+};
40+
41+vi.mock("core/llm/rules/getSystemMessageWithRules", async (importOriginal) => {
42+ const original = (await importOriginal()) as any;
43+ return {
44+ ...original,
45+ getSystemMessageWithRules: ({
46+ baseSystemMessage,
47+ availableRules,
48+ userMessage,
49+ contextItems,
50+ rulePolicies,
51+ }: {
52+ baseSystemMessage: string;
53+ availableRules: RuleWithSource[];
54+ userMessage?: UserChatMessage | ToolResultChatMessage;
55+ contextItems: ContextItemWithId[];
56+ rulePolicies?: Record<string, any>;
57+ }) => {
58+ // Filter rules based on our mock logic
59+ const appliedRules = availableRules.filter((rule) => {
60+ if (rule.rule === LAST_MESSAGE_RULE.rule) {
61+ if (userMessage) {
62+ return renderChatMessage(userMessage).includes(
63+ LAST_MESSAGE_RULE.description!,
64+ );
65+ } else {
66+ return false;
67+ }
68+ }
69+ if (rule.rule === CONTEXT_RULE.rule) {
70+ return contextItems.some((item) =>
71+ item.content.includes(CONTEXT_RULE.description!),
72+ );
73+ }
74+ return true;
75+ });
76+
77+ // Build the system message with applied rules
78+ let systemMessage = baseSystemMessage || "";
79+ if (appliedRules.length > 0) {
80+ systemMessage += "\n\nRules to follow:\n";
81+ for (const rule of appliedRules) {
82+ systemMessage += `- ${rule.rule}\n`;
83+ }
84+ }
85+
86+ return { systemMessage, appliedRules };
87+ },
88+ };
89+});
90+
91+test("getBaseSystemMessage should return the correct system message based on mode", () => {
92+ const mockModel = {
93+ baseAgentSystemMessage: "Custom Agent System Message",
94+ baseChatSystemMessage: "Custom Chat System Message",
95+ } as ModelDescription;
96+
97+ // Test agent mode with custom message
98+ expect(getBaseSystemMessage("agent", mockModel)).toBe(
99+ "Custom Agent System Message",
100+ );
101+
102+ // Test chat mode with custom message
103+ expect(getBaseSystemMessage("chat", mockModel)).toBe(
104+ "Custom Chat System Message",
105+ );
106+
107+ // Test agent mode with default message
108+ expect(getBaseSystemMessage("agent", {} as ModelDescription)).toBe(
109+ DEFAULT_AGENT_SYSTEM_MESSAGE,
110+ );
111+
112+ // Test chat mode with default message
113+ expect(getBaseSystemMessage("chat", {} as ModelDescription)).toBe(
114+ DEFAULT_CHAT_SYSTEM_MESSAGE,
115+ );
116+});
117+
118+describe("constructMessages", () => {
119+ // Setup mock data
120+ let mockHistory: ChatHistoryItem[];
121+ const mockRules: RuleWithSource[] = [
122+ CONTEXT_RULE,
123+ LAST_MESSAGE_RULE,
124+ NORMAL_RULE,
125+ ];
126+
127+ const createContextItem = (
128+ id: string,
129+ content: string,
130+ ): ContextItemWithId => ({
131+ id: {
132+ providerTitle: "test-provider",
133+ itemId: id,
134+ },
135+ content,
136+ name: `Context Item ${id}`,
137+ description: `Description for ${id}`,
138+ });
139+
140+ beforeEach(() => {
141+ // Reset mock history before each test
142+ mockHistory = [];
143+ });
144+
145+ test("should ignore empty, tool, and system messages that go in", () => {
146+ // Setup history with various message types including ones to be ignored
147+ mockHistory = [
148+ {
149+ message: {
150+ role: "system",
151+ content: "I should be ignored",
152+ } as ChatMessage,
153+ contextItems: [],
154+ },
155+ {
156+ message: {
157+ role: "tool",
158+ content: "I should be ignored",
159+ toolCallId: "123",
160+ } as ToolResultChatMessage,
161+ contextItems: [],
162+ },
163+ {
164+ message: { role: "user", content: "" } as ChatMessage, // Empty message
165+ contextItems: [],
166+ },
167+ {
168+ message: { role: "user", content: "Valid user message" } as ChatMessage,
169+ contextItems: [],
170+ },
171+ ];
172+
173+ const { messages } = constructMessages(
174+ mockHistory,
175+ "Base System Message",
176+ mockRules,
177+ {},
178+ );
179+
180+ // Should only contain a system message (added by the function) and the valid user message
181+ expect(messages.length).toBe(2);
182+ expect(messages[0].role).toBe("system");
183+ expect(messages[1].role).toBe("user");
184+ expect(messages[1].content).toEqual([
185+ { type: "text", text: "Valid user message" },
186+ ]);
187+ expect(messages.some((msg) => msg.content === "I should be ignored")).toBe(
188+ false,
189+ );
190+ });
191+
192+ test("should convert user messages to message parts arrays with context items", () => {
193+ const contextItems = [
194+ createContextItem("1", "Context content 1"),
195+ createContextItem("2", "Context content 2"),
196+ ];
197+
198+ mockHistory = [
199+ {
200+ message: {
201+ role: "user",
202+ content: "User message with context",
203+ } as ChatMessage,
204+ contextItems,
205+ },
206+ ];
207+
208+ const { messages } = constructMessages(
209+ mockHistory,
210+ "Base System Message",
211+ mockRules,
212+ {},
213+ );
214+
215+ // Check that user message was converted to parts array with context items first
216+ expect(messages.length).toBe(2); // System message + user message
217+ expect(messages[1].role).toBe("user");
218+
219+ // Check content structure
220+ const content = messages[1].content as any[];
221+ expect(content.length).toBe(3); // 2 context items + original message
222+ expect(content[0].text).toContain("Context content 1");
223+ expect(content[1].text).toContain("Context content 2");
224+ expect(content[2].text).toBe("User message with context");
225+ });
226+
227+ test("should inject thinking messages with no changes", () => {
228+ const thinkingMessage: ThinkingChatMessage = {
229+ role: "thinking",
230+ content: "Thinking process...",
231+ };
232+
233+ mockHistory = [
234+ {
235+ message: thinkingMessage,
236+ contextItems: [],
237+ },
238+ ];
239+
240+ const { messages } = constructMessages(
241+ mockHistory,
242+ "Base System Message",
243+ mockRules,
244+ {},
245+ );
246+
247+ // Should have system message + thinking message
248+ expect(messages.length).toBe(2);
249+ expect(messages[1].role).toBe("thinking");
250+ expect(messages[1].content).toBe("Thinking process...");
251+ });
252+
253+ test("should inject assistant messages with no changes", () => {
254+ const assistantMessage: AssistantChatMessage = {
255+ role: "assistant",
256+ content: "Assistant response",
257+ };
258+
259+ mockHistory = [
260+ {
261+ message: assistantMessage,
262+ contextItems: [],
263+ },
264+ ];
265+
266+ const { messages } = constructMessages(
267+ mockHistory,
268+ "Base System Message",
269+ mockRules,
270+ {},
271+ );
272+
273+ // Should have system message + assistant message
274+ expect(messages.length).toBe(2);
275+ expect(messages[1].role).toBe("assistant");
276+ expect(messages[1].content).toBe("Assistant response");
277+ });
278+
279+ test("should follow assistant messages with tool calls by tool messages containing the tool output", () => {
280+ const assistantWithToolCall: AssistantChatMessage = {
281+ role: "assistant",
282+ content: "I will search for that",
283+ toolCalls: [
284+ {
285+ id: "tool-call-1",
286+ type: "function",
287+ function: {
288+ name: "search",
289+ arguments: '{"query": "test"}',
290+ },
291+ },
292+ ],
293+ };
294+
295+ // With tool output
296+ mockHistory = [
297+ {
298+ message: {
299+ role: "user",
300+ content: "Can you search for something?",
301+ } as UserChatMessage,
302+ contextItems: [],
303+ },
304+ {
305+ message: assistantWithToolCall,
306+ contextItems: [],
307+ toolCallState: {
308+ toolCallId: "tool-call-1",
309+ toolCall: {
310+ id: "tool-call-1",
311+ type: "function",
312+ function: {
313+ name: "search",
314+ arguments: '{"query": "test"}',
315+ },
316+ },
317+ status: "done",
318+ parsedArgs: { query: "test" },
319+ output: [createContextItem("search-result", "Search result content")],
320+ },
321+ },
322+ ];
323+
324+ const { messages } = constructMessages(
325+ mockHistory,
326+ "Base System Message",
327+ mockRules,
328+ {},
329+ );
330+
331+ // Should have: system + user + assistant + tool messages
332+ expect(messages.length).toBe(4);
333+ expect(messages[2].role).toBe("assistant");
334+ expect(messages[3].role).toBe("tool");
335+ const toolMessage = messages[3] as ToolResultChatMessage;
336+ expect(toolMessage.toolCallId).toBe("tool-call-1");
337+ expect(toolMessage.content).toContain("Search result content");
338+ });
339+
340+ test("should show cancelled message for cancelled tool calls", () => {
341+ const assistantWithToolCall: AssistantChatMessage = {
342+ role: "assistant",
343+ content: "I will search for that",
344+ toolCalls: [
345+ {
346+ id: "tool-call-1",
347+ type: "function",
348+ function: {
349+ name: "search",
350+ arguments: '{"query": "test"}',
351+ },
352+ },
353+ ],
354+ };
355+
356+ // With cancelled tool call
357+ mockHistory = [
358+ {
359+ message: assistantWithToolCall,
360+ contextItems: [],
361+ toolCallState: {
362+ toolCallId: "tool-call-1",
363+ toolCall: {
364+ id: "tool-call-1",
365+ type: "function",
366+ function: {
367+ name: "search",
368+ arguments: '{"query": "test"}',
369+ },
370+ },
371+ status: "canceled",
372+ parsedArgs: { query: "test" },
373+ },
374+ },
375+ ];
376+
377+ const { messages } = constructMessages(
378+ mockHistory,
379+ "Base System Message",
380+ mockRules,
381+ {},
382+ );
383+
384+ // Should have system + assistant + tool message with cancelled message
385+ expect(messages.length).toBe(3);
386+ expect(messages[2].role).toBe("tool");
387+ const toolMessage = messages[2] as ToolResultChatMessage;
388+ expect(toolMessage.toolCallId).toBe("tool-call-1");
389+ expect(toolMessage.content).toBe(CANCELLED_TOOL_CALL_MESSAGE);
390+ });
391+
392+ test('should show "No tool output" for tool calls without output', () => {
393+ const assistantWithToolCall: AssistantChatMessage = {
394+ role: "assistant",
395+ content: "I will search for that",
396+ toolCalls: [
397+ {
398+ id: "tool-call-1",
399+ type: "function",
400+ function: {
401+ name: "search",
402+ arguments: '{"query": "test"}',
403+ },
404+ },
405+ ],
406+ };
407+
408+ // With tool call but no output
409+ mockHistory = [
410+ {
411+ message: assistantWithToolCall,
412+ contextItems: [],
413+ toolCallState: {
414+ toolCallId: "tool-call-1",
415+ toolCall: {
416+ id: "tool-call-1",
417+ type: "function",
418+ function: {
419+ name: "search",
420+ arguments: '{"query": "test"}',
421+ },
422+ },
423+ status: "generating", // Not done yet
424+ parsedArgs: { query: "test" },
425+ },
426+ },
427+ ];
428+
429+ const { messages } = constructMessages(
430+ mockHistory,
431+ "Base System Message",
432+ mockRules,
433+ {},
434+ );
435+
436+ // Should have system + assistant + tool message with "No tool output"
437+ expect(messages.length).toBe(3);
438+ expect(messages[2].role).toBe("tool");
439+ expect(messages[2].content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE);
440+ });
441+
442+ test("should start with system message using base message if provided", () => {
443+ mockHistory = [
444+ {
445+ message: { role: "user", content: "Hello" } as UserChatMessage,
446+ contextItems: [],
447+ },
448+ ];
449+
450+ const { messages } = constructMessages(
451+ mockHistory,
452+ "Custom Base System Message",
453+ mockRules,
454+ {},
455+ );
456+
457+ expect(messages[0].role).toBe("system");
458+ expect(messages[0].content).toContain("Custom Base System Message");
459+ });
460+
461+ test("should handle multiple tool calls in a single assistant message", () => {
462+ const assistantWithMultipleToolCalls: AssistantChatMessage = {
463+ role: "assistant",
464+ content: "I will search and check the weather",
465+ toolCalls: [
466+ {
467+ id: "tool-call-1",
468+ type: "function",
469+ function: {
470+ name: "search",
471+ arguments: '{"query": "test"}',
472+ },
473+ },
474+ {
475+ id: "tool-call-2",
476+ type: "function",
477+ function: {
478+ name: "weather",
479+ arguments: '{"location": "New York"}',
480+ },
481+ },
482+ ],
483+ };
484+
485+ // Only the first tool call has output
486+ mockHistory = [
487+ {
488+ message: assistantWithMultipleToolCalls,
489+ contextItems: [],
490+ toolCallState: {
491+ toolCallId: "tool-call-1",
492+ toolCall: {
493+ id: "tool-call-1",
494+ type: "function",
495+ function: {
496+ name: "search",
497+ arguments: '{"query": "test"}',
498+ },
499+ },
500+ status: "done",
501+ parsedArgs: { query: "test" },
502+ output: [createContextItem("search-result", "Search result content")],
503+ },
504+ },
505+ ];
506+
507+ const { messages } = constructMessages(
508+ mockHistory,
509+ "Base System Message",
510+ mockRules,
511+ {},
512+ );
513+
514+ // Should have: system + assistant + 2 tool messages
515+ expect(messages.length).toBe(4);
516+ expect(messages[1].role).toBe("assistant");
517+
518+ // First tool message should have output
519+ expect(messages[2].role).toBe("tool");
520+ expect(messages[3].role).toBe("tool");
521+
522+ const toolMessage1 = messages[2] as ToolResultChatMessage;
523+ const toolMessage2 = messages[3] as ToolResultChatMessage;
524+ expect(toolMessage1.toolCallId).toBe("tool-call-1");
525+ expect(toolMessage1.content).toContain("Search result content");
526+
527+ // Second tool message should have "No tool output"
528+ expect(toolMessage2.toolCallId).toBe("tool-call-2");
529+ expect(toolMessage2.content).toBe(NO_TOOL_CALL_OUTPUT_MESSAGE);
530+ });
531+
532+ test("should handle messages with array content", () => {
533+ // User message with array content (including an image)
534+ const userMessageWithArray: UserChatMessage = {
535+ role: "user",
536+ content: [
537+ { type: "text", text: "Here is some text" },
538+ {
539+ type: "imageUrl",
540+ imageUrl: { url: "https://example.com/image.jpg" },
541+ },
542+ ],
543+ };
544+
545+ mockHistory = [
546+ {
547+ message: userMessageWithArray,
548+ contextItems: [createContextItem("ctx", "Context text")],
549+ },
550+ ];
551+
552+ const { messages, appliedRules } = constructMessages(
553+ mockHistory,
554+ "Base System Message",
555+ mockRules,
556+ {},
557+ );
558+
559+ // Check the user message content structure
560+ expect(messages.length).toBe(2);
561+ expect(messages[1].role).toBe("user");
562+
563+ const content = messages[1].content as any[];
564+ // Should have context item + original 2 parts
565+ expect(content.length).toBe(3);
566+ expect(content[0].type).toBe("text");
567+ expect(content[0].text).toContain("Context text");
568+ expect(content[1].type).toBe("text");
569+ expect(content[1].text).toBe("Here is some text");
570+ expect(content[2].type).toBe("imageUrl");
571+ expect(content[2].imageUrl.url).toBe("https://example.com/image.jpg");
572+
573+ // This also verifies that rules are NOT applied if the triggers are not present
574+ expect(appliedRules).toHaveLength(1);
575+ expect(appliedRules).toContainEqual(NORMAL_RULE);
576+ });
577+
578+ test("system message should include rules triggered by context items from the last user message forward", () => {
579+ // Create context item that should trigger the CONTEXT_RULE
580+ const triggeringContextItem = createContextItem(
581+ "trigger",
582+ `Some content with ${CONTEXT_RULE.description} in it`,
583+ );
584+
585+ mockHistory = [
586+ // First user message with non-triggering context
587+ {
588+ message: { role: "user", content: "First message" } as UserChatMessage,
589+ contextItems: [createContextItem("normal", "Normal context")],
590+ },
591+ // Assistant response
592+ {
593+ message: {
594+ role: "assistant",
595+ content: "Assistant response",
596+ } as AssistantChatMessage,
597+ contextItems: [],
598+ },
599+ // Last user message with triggering context
600+ {
601+ message: { role: "user", content: "Last message" } as UserChatMessage,
602+ contextItems: [triggeringContextItem],
603+ },
604+ ];
605+
606+ const { messages, appliedRules } = constructMessages(
607+ mockHistory,
608+ "Base System Message",
609+ mockRules,
610+ {},
611+ );
612+
613+ // Verify context rule was applied in the system message
614+ expect(appliedRules).toHaveLength(2);
615+ expect(appliedRules).toContainEqual(NORMAL_RULE);
616+ expect(appliedRules).toContainEqual(CONTEXT_RULE);
617+ expect(messages[0].role).toBe("system");
618+ expect(messages[0].content).toContain("Base System Message");
619+ expect(messages[0].content).toContain(CONTEXT_RULE.rule);
620+ });
621+
622+ test("system message should include rules triggered by tool output after the last user message", () => {
623+ // Create a history with a user message, assistant with tool call, and tool output containing triggering content
624+ const assistantWithToolCall: AssistantChatMessage = {
625+ role: "assistant",
626+ content: "I will search for that",
627+ toolCalls: [
628+ {
629+ id: "tool-call-1",
630+ type: "function",
631+ function: {
632+ name: "search",
633+ arguments: '{"query": "test"}',
634+ },
635+ },
636+ ],
637+ };
638+
639+ // Tool output containing the trigger for CONTEXT_RULE
640+ const triggeringToolOutput = createContextItem(
641+ "search-result",
642+ `Search result with ${CONTEXT_RULE.description} trigger`,
643+ );
644+
645+ mockHistory = [
646+ {
647+ message: {
648+ role: "user",
649+ content: "Can you search for something?",
650+ } as UserChatMessage,
651+ contextItems: [],
652+ },
653+ {
654+ message: assistantWithToolCall,
655+ contextItems: [],
656+ toolCallState: {
657+ toolCallId: "tool-call-1",
658+ toolCall: {
659+ id: "tool-call-1",
660+ type: "function",
661+ function: {
662+ name: "search",
663+ arguments: '{"query": "test"}',
664+ },
665+ },
666+ status: "done",
667+ parsedArgs: { query: "test" },
668+ output: [triggeringToolOutput],
669+ },
670+ },
671+ ];
672+
673+ const { messages, appliedRules } = constructMessages(
674+ mockHistory,
675+ "Base System Message",
676+ mockRules,
677+ {},
678+ );
679+
680+ // Verify context rule was applied in the system message due to the tool output
681+ expect(appliedRules).toHaveLength(2);
682+ expect(appliedRules).toContainEqual(NORMAL_RULE);
683+ expect(appliedRules).toContainEqual(CONTEXT_RULE);
684+ expect(messages[0].role).toBe("system");
685+ expect(messages[0].content).toContain("Base System Message");
686+ expect(messages[0].content).toContain(CONTEXT_RULE.rule);
687+ });
688+
689+ test("system message should only apply rules triggered by the last user message", () => {
690+ // First user message with trigger for LAST_MESSAGE_RULE
691+ const firstUserMessage = {
692+ role: "user",
693+ content: `This contains ${LAST_MESSAGE_RULE.description}`,
694+ } as UserChatMessage;
695+
696+ // Last user message without any triggers
697+ const lastUserMessage = {
698+ role: "user",
699+ content: "This is a normal message",
700+ } as UserChatMessage;
701+
702+ mockHistory = [
703+ {
704+ message: firstUserMessage,
705+ contextItems: [],
706+ },
707+ {
708+ message: {
709+ role: "assistant",
710+ content: "First response",
711+ } as AssistantChatMessage,
712+ contextItems: [],
713+ },
714+ {
715+ message: lastUserMessage,
716+ contextItems: [],
717+ },
718+ ];
719+
720+ const { messages, appliedRules } = constructMessages(
721+ mockHistory,
722+ "Base System Message",
723+ mockRules,
724+ {},
725+ );
726+
727+ // LAST_MESSAGE_RULE should not be applied since the trigger is not in the last message
728+ expect(appliedRules).toHaveLength(1);
729+ expect(appliedRules).toContainEqual(NORMAL_RULE); // Normal rule should always apply
730+ expect(messages[0].role).toBe("system");
731+ expect(messages[0].content).toContain("Base System Message");
732+ expect(messages[0].content).not.toContain(LAST_MESSAGE_RULE.rule);
733+ });
734+});
added gui/src/redux/util/constructMessages.ts +173 −0
@@ -0,0 +1,173 @@
1+import {
2+ ChatHistoryItem,
3+ ChatMessage,
4+ ContextItemWithId,
5+ ModelDescription,
6+ RuleWithSource,
7+ TextMessagePart,
8+ ToolResultChatMessage,
9+ UserChatMessage,
10+} from "core";
11+import {
12+ DEFAULT_AGENT_SYSTEM_MESSAGE,
13+ DEFAULT_CHAT_SYSTEM_MESSAGE,
14+} from "core/llm/defaultSystemMessages";
15+import { chatMessageIsEmpty } from "core/llm/messages";
16+import { getSystemMessageWithRules } from "core/llm/rules/getSystemMessageWithRules";
17+import { RulePolicies } from "core/llm/rules/types";
18+import { findLast, findLastIndex } from "core/util/findLast";
19+import {
20+ normalizeToMessageParts,
21+ renderContextItems,
22+} from "core/util/messageContent";
23+import { toolCallStateToContextItems } from "../../pages/gui/ToolCallDiv/toolCallStateToContextItem";
24+
25+export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output";
26+export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call.";
27+
28+interface MessageWithContextItems {
29+ ctxItems: ContextItemWithId[];
30+ message: ChatMessage;
31+}
32+export function constructMessages(
33+ history: ChatHistoryItem[],
34+ baseSystemMessage: string | undefined,
35+ availableRules: RuleWithSource[],
36+ rulePolicies: RulePolicies,
37+): {
38+ messages: ChatMessage[];
39+ appliedRules: RuleWithSource[];
40+ appliedRuleIndex: number;
41+} {
42+ const historyCopy = [...history];
43+
44+ const msgs: MessageWithContextItems[] = [];
45+ let appliedRuleIndex = -1;
46+ let index = -1;
47+ for (const item of historyCopy) {
48+ index++;
49+ if (
50+ item.message.role === "system" ||
51+ item.message.role === "tool" ||
52+ chatMessageIsEmpty(item.message)
53+ ) {
54+ // Tool messages will be re-inserted
55+ continue;
56+ }
57+
58+ if (item.message.role === "user") {
59+ appliedRuleIndex = index;
60+ // Gather context items for user messages
61+ let content = normalizeToMessageParts(item.message);
62+
63+ const ctxItemParts = item.contextItems
64+ .map((ctxItem) => {
65+ return {
66+ type: "text",
67+ text: `${ctxItem.content}\n`,
68+ } as TextMessagePart;
69+ })
70+ .filter((part) => !!part.text.trim());
71+
72+ content = [...ctxItemParts, ...content];
73+ msgs.push({
74+ ctxItems: item.contextItems,
75+ message: {
76+ ...item.message,
77+ content,
78+ },
79+ });
80+ } else if (item.message.role === "thinking") {
81+ msgs.push({
82+ ctxItems: item.contextItems,
83+ message: item.message,
84+ });
85+ } else if (item.message.role === "assistant") {
86+ msgs.push({
87+ ctxItems: item.contextItems,
88+ message: item.message,
89+ });
90+
91+ // Add a tool message for each tool call
92+ if (item.message.toolCalls?.length) {
93+ // If the assistant message has tool calls, we need to insert tool messages
94+ for (const toolCall of item.message.toolCalls) {
95+ let content: string = NO_TOOL_CALL_OUTPUT_MESSAGE;
96+ // TODO parallel tool calls: toolCallState only supports one tool call per message for now
97+ if (item.toolCallState?.status === "canceled") {
98+ content = CANCELLED_TOOL_CALL_MESSAGE;
99+ } else if (
100+ item.toolCallState?.toolCallId === toolCall.id &&
101+ item.toolCallState?.output
102+ ) {
103+ content = renderContextItems(item.toolCallState.output);
104+ }
105+ msgs.push({
106+ ctxItems: toolCallStateToContextItems(item.toolCallState),
107+ message: {
108+ role: "tool",
109+ content,
110+ toolCallId: toolCall.id!,
111+ },
112+ });
113+ }
114+ }
115+ }
116+ }
117+
118+ // Some rules only apply to the last user or tool message
119+ const lastUserOrToolMsg = findLast(
120+ msgs,
121+ (item) => item.message.role === "user" || item.message.role === "tool",
122+ )?.message as UserChatMessage | ToolResultChatMessage;
123+
124+ // Some rules apply to all context items since the last user message, inclusiv
125+ const lastUserMsgIndex = findLastIndex(
126+ msgs,
127+ (item) => item.message.role === "user",
128+ );
129+ const itemsBackToLastUserMessage = msgs
130+ .slice(lastUserMsgIndex, msgs.length)
131+ .filter(
132+ (item) => item.message.role === "tool" || item.message.role === "user",
133+ );
134+ const rulesContextItems = itemsBackToLastUserMessage
135+ .map((item) => item.ctxItems)
136+ .flat();
137+
138+ const { systemMessage, appliedRules } = getSystemMessageWithRules({
139+ baseSystemMessage,
140+ availableRules,
141+ userMessage: lastUserOrToolMsg,
142+ contextItems: rulesContextItems,
143+ rulePolicies,
144+ });
145+
146+ if (systemMessage.trim()) {
147+ msgs.unshift({
148+ ctxItems: [],
149+ message: {
150+ role: "system",
151+ content: systemMessage,
152+ },
153+ });
154+ }
155+
156+ const messages = msgs.map((m) => m.message);
157+ return {
158+ messages,
159+ appliedRules,
160+ appliedRuleIndex,
161+ };
162+}
163+
164+export function getBaseSystemMessage(
165+ messageMode: string,
166+ model: ModelDescription,
167+): string {
168+ if (messageMode === "agent") {
169+ return model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE;
170+ } else {
171+ return model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE;
172+ }
173+}
modified gui/src/redux/util/index.ts +12 −0
@@ -1,6 +1,7 @@
11 import { ContextItem, ToolCallState } from "core";
22 import { safeParseToolCallArgs } from "core/tools/parseArgs";
33 import { IIdeMessenger } from "../../context/IdeMessenger";
4+import { ChatHistoryItemWithMessageId } from "../slices/sessionSlice";
45 import { RootState } from "../store";
56
67 export function findCurrentToolCall(
@@ -9,6 +10,7 @@
910 return chatHistory[chatHistory.length - 1]?.toolCallState;
1011 }
1112
13+// TODO parallel tool calls - find tool call must search within arrays
1214 export function findToolCall(
1315 chatHistory: RootState["session"]["history"],
1416 toolCallId: string,
@@ -18,6 +20,16 @@
1820 )?.toolCallState;
1921 }
2022
23+export function findToolOutput(
24+ chatHistory: RootState["session"]["history"],
25+ toolCallId: string,
26+): ChatHistoryItemWithMessageId | undefined {
27+ return chatHistory.find(
28+ (item) =>
29+ item.message.role === "tool" && item.message.toolCallId === toolCallId,
30+ );
31+}
32+
2133 export function logToolUsage(
2234 toolCallState: ToolCallState,
2335 success: boolean,
modified gui/src/util/index.ts +0 −52
@@ -1,10 +1,4 @@
1-import { MessageModes, ModelDescription } from "core";
21 import { ProfileDescription } from "core/config/ProfileLifecycleManager";
3-import {
4- DEFAULT_AGENT_SYSTEM_MESSAGE,
5- DEFAULT_CHAT_SYSTEM_MESSAGE,
6-} from "core/llm/constructMessages";
7-import _ from "lodash";
82 import { KeyboardEvent as ReactKeyboardEvent } from "react";
93 import { getLocalStorage } from "./localStorage";
104
@@ -88,52 +82,6 @@
8882 return false;
8983 }
9084
91-/**
92- * Updates the values of an object's properties based on the specified paths.
93- *
94- * This function creates a deep clone of the provided object and updates its properties
95- * based on the given path-to-value mappings. If a value in the mapping is a function,
96- * it will be used to determine the new value for the property. Otherwise, the value itself
97- * will be set for the property.
98- *
99- * @param {Object} old - The original object to be cloned and updated.
100- * @param {Object} pathToValue - An object where the keys represent the paths to the properties
101- * to be updated and the values represent the new values or functions
102- * to determine the new values.
103- * @returns {Object} A new object with the updated values.
104- */
105-export function updatedObj(old: any, pathToValue: { [key: string]: any }) {
106- const newObject = _.cloneDeep(old);
107-
108- for (const key in pathToValue) {
109- if (typeof pathToValue[key] === "function") {
110- _.updateWith(newObject, key, pathToValue[key]);
111- } else {
112- _.updateWith(newObject, key, (__) => pathToValue[key]);
113- }
114- }
115-
116- return newObject;
117-}
118-
11985 export function isLocalProfile(profile: ProfileDescription): boolean {
12086 return profile.profileType === "local";
12187 }
122-
123-/**
124- * Get the base system message for the agent or chat mode from the model description.
125- */
126-export function getBaseSystemMessage(
127- modelDetails: ModelDescription | null,
128- mode: MessageModes,
129-) {
130- let baseChatOrAgentSystemMessage: string | undefined;
131- if (mode === "agent") {
132- baseChatOrAgentSystemMessage =
133- modelDetails?.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE;
134- } else {
135- baseChatOrAgentSystemMessage =
136- modelDetails?.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE;
137- }
138- return baseChatOrAgentSystemMessage;
139-}