@@ -93,17 +93,36 @@ export function prepareTurnMessages(input: {
9393 }
9494
9595 // 3. Context pruning
96- const preStats = apiLogOn
97- ? getMessageDiagnostics(normalised)
98- : getMessageStats(normalised);
99- if (apiLogOn) logApiEvent("turn context pre-prune", preStats);
100-
10196 const pruned = applyContextPruning(normalised, pruningMode);
10297
103- const postStats = apiLogOn
104- ? getMessageDiagnostics(pruned)
105- : getMessageStats(pruned);
106- if (apiLogOn) logApiEvent("turn context post-prune", postStats);
98+ // Only compute stats when they will actually be consumed:
99+ // - apiLogOn: logged for debugging
100+ // - pruning active + messages changed: used in "context-pruned" yield event
101+ const pruningActive = pruningMode !== "off";
102+ const needsStats = apiLogOn || pruningActive;
103+
104+ let preStats: { messageCount: number; totalBytes: number };
105+ let postStats: { messageCount: number; totalBytes: number };
106+
107+ if (!needsStats) {
108+ // pruning is off and API log is off — skip expensive serialisation
109+ const count = normalised.length;
110+ preStats = { messageCount: count, totalBytes: 0 };
111+ postStats = preStats;
112+ } else {
113+ preStats = apiLogOn
114+ ? getMessageDiagnostics(normalised)
115+ : getMessageStats(normalised);
116+ if (apiLogOn) logApiEvent("turn context pre-prune", preStats);
117+ // Reuse preStats when pruning was a no-op (same array reference)
118+ postStats =
119+ pruned === normalised
120+ ? preStats
121+ : apiLogOn
122+ ? getMessageDiagnostics(pruned)
123+ : getMessageStats(pruned);
124+ if (apiLogOn) logApiEvent("turn context post-prune", postStats);
125+ }
107126
108127 // 4. Payload compaction
109128 const compacted = compactToolResultPayloads(