MCPcopy
hub / github.com/virattt/dexter / enforceResultBudget

Function enforceResultBudget

src/utils/tool-result-budget.ts:21–67  ·  view source on GitHub ↗
(toolMessages: ToolMessage[])

Source from the content-addressed store, hash-verified

19 * Returns the original array if already under budget.
20 */
21export function enforceResultBudget(toolMessages: ToolMessage[]): ToolMessage[] {
22 const totalChars = toolMessages.reduce((sum, tm) => {
23 const content = typeof tm.content === 'string' ? tm.content : JSON.stringify(tm.content);
24 return sum + content.length;
25 }, 0);
26
27 if (totalChars <= MAX_TURN_RESULT_CHARS) {
28 return toolMessages;
29 }
30
31 // Build index with content lengths, sort largest first
32 const indexed = toolMessages.map((tm, i) => ({
33 index: i,
34 tm,
35 content: typeof tm.content === 'string' ? tm.content : JSON.stringify(tm.content),
36 }));
37 const bySize = [...indexed].sort((a, b) => b.content.length - a.content.length);
38
39 let remaining = totalChars;
40 const toPersist = new Set<number>();
41
42 for (const entry of bySize) {
43 if (remaining <= MAX_TURN_RESULT_CHARS) break;
44 toPersist.add(entry.index);
45 remaining -= entry.content.length;
46 // Add back the preview size (~2KB)
47 remaining += 2_500;
48 }
49
50 if (toPersist.size === 0) return toolMessages;
51
52 return toolMessages.map((tm, i) => {
53 if (!toPersist.has(i)) return tm;
54
55 const content = typeof tm.content === 'string' ? tm.content : JSON.stringify(tm.content);
56 const { preview, filePath } = persistLargeResult(
57 tm.name ?? 'unknown',
58 tm.tool_call_id,
59 content,
60 );
61 return new ToolMessage({
62 content: buildPersistedContent(filePath, preview, content.length),
63 tool_call_id: tm.tool_call_id,
64 name: tm.name,
65 });
66 });
67}

Callers 1

runMethod · 0.85

Calls 3

persistLargeResultFunction · 0.85
buildPersistedContentFunction · 0.85
addMethod · 0.45

Tested by

no test coverage detected