MCPcopy Create free account
hub / github.com/freecodexyz/free-code / applyGrouping

Function applyGrouping

src/utils/groupToolUses.ts:54–182  ·  view source on GitHub ↗
(
  messages: MessageWithoutProgress[],
  tools: Tools,
  verbose: boolean = false,
)

Source from the content-addressed store, hash-verified

52 * When verbose is true, skips grouping so messages render at original positions.
53 */
54export function applyGrouping(
55 messages: MessageWithoutProgress[],
56 tools: Tools,
57 verbose: boolean = false,
58): GroupingResult {
59 // In verbose mode, don't group - each message renders at its original position
60 if (verbose) {
61 return {
62 messages: messages,
63 }
64 }
65 const toolsWithGrouping = getToolsWithGrouping(tools)
66
67 // First pass: group tool uses by message.id + tool name
68 const groups = new Map<
69 string,
70 NormalizedAssistantMessage<BetaToolUseBlock>[]
71 >()
72
73 for (const msg of messages) {
74 const info = getToolUseInfo(msg)
75 if (info && toolsWithGrouping.has(info.toolName)) {
76 const key = `${info.messageId}:${info.toolName}`
77 const group = groups.get(key) ?? []
78 group.push(msg as NormalizedAssistantMessage<BetaToolUseBlock>)
79 groups.set(key, group)
80 }
81 }
82
83 // Identify valid groups (2+ items) and collect their tool use IDs
84 const validGroups = new Map<
85 string,
86 NormalizedAssistantMessage<BetaToolUseBlock>[]
87 >()
88 const groupedToolUseIds = new Set<string>()
89
90 for (const [key, group] of groups) {
91 if (group.length >= 2) {
92 validGroups.set(key, group)
93 for (const msg of group) {
94 const info = getToolUseInfo(msg)
95 if (info) {
96 groupedToolUseIds.add(info.toolUseId)
97 }
98 }
99 }
100 }
101
102 // Collect result messages for grouped tool_uses
103 // Map from tool_use_id to the user message containing that result
104 const resultsByToolUseId = new Map<string, NormalizedUserMessage>()
105
106 for (const msg of messages) {
107 if (msg.type === 'user') {
108 for (const content of msg.message.content) {
109 if (
110 content.type === 'tool_result' &&
111 groupedToolUseIds.has(content.tool_use_id)

Callers 1

MessagesImplFunction · 0.85

Calls 6

getToolsWithGroupingFunction · 0.85
getToolUseInfoFunction · 0.85
setMethod · 0.80
hasMethod · 0.45
getMethod · 0.45
addMethod · 0.45

Tested by

no test coverage detected