( history: ChatHistoryItem[], baseSystemMessage: string | undefined, availableRules: RuleWithSource[], rulePolicies: RulePolicies, useSystemToolsFramework?: SystemMessageToolsFramework, )
| 35 | message: ChatMessage; |
| 36 | } |
| 37 | export function constructMessages( |
| 38 | history: ChatHistoryItem[], |
| 39 | baseSystemMessage: string | undefined, |
| 40 | availableRules: RuleWithSource[], |
| 41 | rulePolicies: RulePolicies, |
| 42 | useSystemToolsFramework?: SystemMessageToolsFramework, |
| 43 | ): { |
| 44 | messages: ChatMessage[]; |
| 45 | appliedRules: RuleMetadata[]; |
| 46 | appliedRuleIndex: number; |
| 47 | } { |
| 48 | // Find the most recent conversation summary and filter history accordingly |
| 49 | let summaryContent = ""; |
| 50 | let filteredHistory = history; |
| 51 | |
| 52 | for (let i = history.length - 1; i >= 0; i--) { |
| 53 | const summary = history[i].conversationSummary; |
| 54 | if (summary) { |
| 55 | summaryContent = summary; |
| 56 | // Only include messages that come AFTER the message with the summary |
| 57 | filteredHistory = history.slice(i + 1); |
| 58 | break; |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | const historyCopy = [...filteredHistory]; |
| 63 | |
| 64 | const msgs: MessageWithContextItems[] = []; |
| 65 | let appliedRuleIndex = -1; |
| 66 | let index = -1; |
| 67 | for (const item of historyCopy) { |
| 68 | index++; |
| 69 | if ( |
| 70 | item.message.role === "system" || |
| 71 | item.message.role === "tool" || |
| 72 | chatMessageIsEmpty(item.message) |
| 73 | ) { |
| 74 | // Tool messages will be re-inserted |
| 75 | continue; |
| 76 | } |
| 77 | |
| 78 | if (item.message.role === "user") { |
| 79 | appliedRuleIndex = index; |
| 80 | // Gather context items for user messages |
| 81 | let content = normalizeToMessageParts(item.message); |
| 82 | |
| 83 | const ctxItemParts = item.contextItems |
| 84 | .map((ctxItem) => { |
| 85 | return { |
| 86 | type: "text", |
| 87 | text: `${ctxItem.content}\n`, |
| 88 | } as TextMessagePart; |
| 89 | }) |
| 90 | .filter((part) => !!part.text.trim()); |
| 91 | |
| 92 | content = [...ctxItemParts, ...content]; |
| 93 | msgs.push({ |
| 94 | ctxItems: item.contextItems, |
no test coverage detected