| 1 | import { |
| 2 | ChatHistoryItem, |
| 3 | ChatMessage, |
| 4 | ContextItemWithId, |
| 5 | RuleWithSource, |
| 6 | TextMessagePart, |
| 7 | ToolResultChatMessage, |
| 8 | UserChatMessage, |
| 9 | } from "core"; |
| 10 | import { chatMessageIsEmpty } from "core/llm/messages"; |
| 11 | import { getSystemMessageWithRules } from "core/llm/rules/getSystemMessageWithRules"; |
| 12 | import { RulePolicies } from "core/llm/rules/types"; |
| 13 | import { BuiltInToolNames } from "core/tools/builtIn"; |
| 14 | import { |
| 15 | CANCELLED_TOOL_CALL_MESSAGE, |
| 16 | NO_TOOL_CALL_OUTPUT_MESSAGE, |
| 17 | } from "core/tools/constants"; |
| 18 | import { convertToolCallStatesToSystemCallsAndOutput } from "core/tools/systemMessageTools/convertSystemTools"; |
| 19 | import { SystemMessageToolsFramework } from "core/tools/systemMessageTools/types"; |
| 20 | import { findLast, findLastIndex } from "core/util/findLast"; |
| 21 | import { |
| 22 | normalizeToMessageParts, |
| 23 | renderContextItems, |
| 24 | renderContextItemsWithStatus, |
| 25 | } from "core/util/messageContent"; |
| 26 | import { toolCallStateToContextItems } from "../../pages/gui/ToolCallDiv/utils"; |
| 27 | |
| 28 | // Helper function to render context items and append status information |
| 29 | // Helper function to render context items and append status information |
| 30 | |
| 31 | interface MessageWithContextItems { |
| 32 | ctxItems: ContextItemWithId[]; |
| 33 | message: ChatMessage; |
| 34 | } |
| 35 | export function constructMessages( |
| 36 | history: ChatHistoryItem[], |
| 37 | baseSystemMessage: string | undefined, |
| 38 | availableRules: RuleWithSource[], |
| 39 | rulePolicies: RulePolicies, |
| 40 | useSystemToolsFramework?: SystemMessageToolsFramework, |
| 41 | ): { |
| 42 | messages: ChatMessage[]; |
| 43 | appliedRules: RuleWithSource[]; |
| 44 | appliedRuleIndex: number; |
| 45 | } { |
| 46 | // Find the most recent conversation summary and filter history accordingly |
| 47 | let summaryContent = ""; |
| 48 | let filteredHistory = history; |
| 49 | |
| 50 | for (let i = history.length - 1; i >= 0; i--) { |
| 51 | const summary = history[i].conversationSummary; |
| 52 | if (summary) { |
| 53 | summaryContent = summary; |
| 54 | // Only include messages that come AFTER the message with the summary |
| 55 | filteredHistory = history.slice(i + 1); |
| 56 | break; |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | const historyCopy = [...filteredHistory]; |
| 61 | |
| 62 | const msgs: MessageWithContextItems[] = []; |
| 63 | let appliedRuleIndex = -1; |
| 64 | let index = -1; |
| 65 | for (const item of historyCopy) { |
| 66 | index++; |
| 67 | if ( |
| 68 | item.message.role === "system" || |
| 69 | item.message.role === "tool" || |
| 70 | chatMessageIsEmpty(item.message) |
| 71 | ) { |
| 72 | // Tool messages will be re-inserted |
| 73 | continue; |
| 74 | } |
| 75 | |
| 76 | if (item.message.role === "user") { |
| 77 | appliedRuleIndex = index; |
| 78 | // Gather context items for user messages |
| 79 | let content = normalizeToMessageParts(item.message); |
| 80 | |
| 81 | const ctxItemParts = item.contextItems |
| 82 | .map((ctxItem) => { |
| 83 | return { |
| 84 | type: "text", |
| 85 | text: `${ctxItem.content}\n`, |
| 86 | } as TextMessagePart; |
| 87 | }) |
| 88 | .filter((part) => !!part.text.trim()); |
| 89 | |
| 90 | content = [...ctxItemParts, ...content]; |
| 91 | msgs.push({ |
| 92 | ctxItems: item.contextItems, |
| 93 | message: { |
| 94 | ...item.message, |
| 95 | content, |
| 96 | }, |
| 97 | }); |
| 98 | } else if (item.message.role === "thinking") { |
| 99 | msgs.push({ |
| 100 | ctxItems: item.contextItems, |
| 101 | message: item.message, |
| 102 | }); |
| 103 | } else if (item.message.role === "assistant") { |
| 104 | // When using system message tools, convert tool calls/states to text content |
| 105 | if (item.toolCallStates?.length && useSystemToolsFramework) { |
| 106 | const { userMessage, assistantMessage } = |
| 107 | convertToolCallStatesToSystemCallsAndOutput( |
| 108 | item.message, |
| 109 | item.toolCallStates ?? [], |
| 110 | useSystemToolsFramework, |
| 111 | ); |
| 112 | msgs.push({ |
| 113 | message: assistantMessage, |
| 114 | ctxItems: [], |
| 115 | }); |
| 116 | msgs.push({ |
| 117 | message: userMessage, |
| 118 | ctxItems: [], |
| 119 | }); |
| 120 | continue; |
| 121 | } |
| 122 | |
| 123 | msgs.push({ |
| 124 | ctxItems: item.contextItems, |
| 125 | message: item.message, |
| 126 | }); |
| 127 | |
| 128 | // Add a tool message for each tool call |
| 129 | if (item.message.toolCalls?.length) { |
| 130 | // If the assistant message has tool calls, we need to insert tool messages |
| 131 | for (const toolCall of item.message.toolCalls) { |
| 132 | let content: string = NO_TOOL_CALL_OUTPUT_MESSAGE; |
| 133 | |
| 134 | // Find the corresponding tool call state for this specific tool call |
| 135 | const toolCallState = item.toolCallStates?.find( |
| 136 | (state) => state.toolCallId === toolCall.id, |
| 137 | ); |
| 138 | |
| 139 | if (toolCallState?.status === "canceled") { |
| 140 | content = CANCELLED_TOOL_CALL_MESSAGE; |
| 141 | } else if ( |
| 142 | toolCallState?.output && |
| 143 | toolCall.function?.name == BuiltInToolNames.RunTerminalCommand |
| 144 | ) { |
| 145 | // Add status for tools containing detailed status outcomes per context item |
| 146 | content = renderContextItemsWithStatus(toolCallState.output); |
| 147 | } else if (toolCallState?.output) { |
| 148 | content = renderContextItems(toolCallState?.output); |
| 149 | } |
| 150 | |
| 151 | msgs.push({ |
| 152 | ctxItems: toolCallStateToContextItems(toolCallState), |
| 153 | message: { |
| 154 | role: "tool", |
| 155 | content, |
| 156 | toolCallId: toolCall.id!, |
| 157 | }, |
| 158 | }); |
| 159 | } |
| 160 | } else if (item.toolCallStates && item.toolCallStates.length > 0) { |
| 161 | // This case indicates a potential mismatch - we have tool call states but no message.toolCalls |
| 162 | console.error( |
| 163 | "ERROR constructMessages: Assistant message has toolCallStates but no message.toolCalls:", |
| 164 | { |
| 165 | toolCallStates: item.toolCallStates.length, |
| 166 | toolCallIds: item.toolCallStates.map((s) => s.toolCallId), |
| 167 | messageContent: |
| 168 | typeof item.message.content === "string" |
| 169 | ? item.message.content?.substring(0, 50) + "..." |
| 170 | : "Non-string content", |
| 171 | }, |
| 172 | ); |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | // Some rules only apply to the last user or tool message |
| 178 | const lastUserOrToolMsg = findLast( |
| 179 | msgs, |
| 180 | (item) => item.message.role === "user" || item.message.role === "tool", |
| 181 | )?.message as UserChatMessage | ToolResultChatMessage; |
| 182 | |
| 183 | // Some rules apply to all context items since the last user message, inclusiv |
| 184 | const lastUserMsgIndex = findLastIndex( |
| 185 | msgs, |
| 186 | (item) => item.message.role === "user", |
| 187 | ); |
| 188 | const itemsBackToLastUserMessage = msgs |
| 189 | .slice(lastUserMsgIndex, msgs.length) |
| 190 | .filter( |
| 191 | (item) => item.message.role === "tool" || item.message.role === "user", |
| 192 | ); |
| 193 | const rulesContextItems = itemsBackToLastUserMessage |
| 194 | .map((item) => item.ctxItems) |
| 195 | .flat(); |
| 196 | |
| 197 | const { systemMessage, appliedRules } = getSystemMessageWithRules({ |
| 198 | baseSystemMessage, |
| 199 | availableRules, |
| 200 | userMessage: lastUserOrToolMsg, |
| 201 | contextItems: rulesContextItems, |
| 202 | rulePolicies, |
| 203 | }); |
| 204 | |
| 205 | // Append conversation summary to system message if it exists |
| 206 | let finalSystemMessage = systemMessage; |
| 207 | if (summaryContent) { |
| 208 | finalSystemMessage = systemMessage |
| 209 | ? `${systemMessage}\n\nPrevious conversation summary:\n\n ${summaryContent}` |
| 210 | : `Previous conversation summary:\n\n ${summaryContent}`; |
| 211 | } |
| 212 | |
| 213 | if (finalSystemMessage.trim()) { |
| 214 | msgs.unshift({ |
| 215 | ctxItems: [], |
| 216 | message: { |
| 217 | role: "system", |
| 218 | content: finalSystemMessage, |
| 219 | }, |
| 220 | }); |
| 221 | } |
| 222 | |
| 223 | const messages = msgs.map((m) => m.message); |
| 224 | return { |
| 225 | messages, |
| 226 | appliedRules, |
| 227 | appliedRuleIndex, |
| 228 | }; |
| 229 | } |