blob: edd98d1d372fac56c0bff125e33471ecf4514967 [file] [log] [blame]
Pokey Rulee2a8c2f2025-04-23 15:09:25 +01001import { AgentMessage } from "../types";
2
3export function aggregateAgentMessages(
4 arr1: AgentMessage[],
Philip Zeyliger72682df2025-04-23 13:09:46 -07005 arr2: AgentMessage[],
6): AgentMessage[] {
Pokey Rulee2a8c2f2025-04-23 15:09:25 +01007 const mergedArray = [...arr1, ...arr2];
8 const seenIds = new Set<number>();
9 const toolCallResults = new Map<string, AgentMessage>();
10
philip.zeyliger26bc6592025-06-30 20:15:30 -070011 const ret: AgentMessage[] = mergedArray
Pokey Rulee2a8c2f2025-04-23 15:09:25 +010012 .filter((msg) => {
13 if (msg.type == "tool") {
14 toolCallResults.set(msg.tool_call_id, msg);
15 return false;
16 }
Josh Bleecher Snyder3b44cc32025-07-22 02:28:14 +000017 // Suppress internal message types that shouldn't be displayed
18 if (msg.type == "slug" || msg.type == "compact") {
19 return false;
20 }
Josh Bleecher Snyder2d832192025-07-28 23:03:59 +000021 // Filter out messages with empty/missing content unless they have tool_calls or commits
22 const hasContent = msg.content && msg.content.trim().length > 0;
23 const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
24 const hasCommits = msg.commits && msg.commits.length > 0;
25
26 if (!hasContent && !hasToolCalls && !hasCommits) {
27 return false;
28 }
Pokey Rulee2a8c2f2025-04-23 15:09:25 +010029 if (seenIds.has(msg.idx)) {
30 return false; // Skip if idx is already seen
31 }
32
33 seenIds.add(msg.idx);
34 return true;
35 })
36 .sort((a: AgentMessage, b: AgentMessage) => a.idx - b.idx);
37
38 // Attach any tool_call result messages to the original message's tool_call object.
39 ret.forEach((msg) => {
40 msg.tool_calls?.forEach((toolCall) => {
41 if (toolCallResults.has(toolCall.tool_call_id)) {
42 toolCall.result_message = toolCallResults.get(toolCall.tool_call_id);
43 }
44 });
45 });
46 return ret;
47}