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