@@ -259,8 +259,8 @@ export function getToolResultTextLength(msg: AgentMessage): number {
259259 }
260260 let totalLength = 0 ;
261261 for ( const block of content ) {
262- if ( block && typeof block === "object" && ( block as { type ?: string } ) . type === "text" ) {
263- const text = ( block as TextContent ) . text ;
262+ if ( isToolResultTextBlock ( block ) ) {
263+ const text = block . text ;
264264 if ( typeof text === "string" ) {
265265 totalLength += text . length ;
266266 }
@@ -297,10 +297,10 @@ export function truncateToolResultMessage(
297297
298298 // Distribute the budget proportionally among text blocks
299299 const newContent = content . map ( ( block : unknown ) => {
300- if ( ! block || typeof block !== "object" || ( block as { type ?: string } ) . type !== "text" ) {
300+ if ( ! isToolResultTextBlock ( block ) ) {
301301 return block ; // Keep non-text blocks (images) as-is
302302 }
303- const textBlock = block as TextContent ;
303+ const textBlock = block ;
304304 if ( typeof textBlock . text !== "string" ) {
305305 return block ;
306306 }
@@ -314,17 +314,33 @@ export function truncateToolResultMessage(
314314 1 ,
315315 Math . min ( maxChars , Math . max ( minKeepChars + defaultSuffix . length , proportionalBudget ) ) ,
316316 ) ;
317- return Object . assign ( { } , textBlock , {
318- text : truncateToolResultText ( textBlock . text , blockBudget , {
319- suffix : suffixFactory ,
320- minKeepChars,
321- } ) ,
317+ const truncatedText = truncateToolResultText ( textBlock . text , blockBudget , {
318+ suffix : suffixFactory ,
319+ minKeepChars,
322320 } ) ;
321+ const nextBlock = Object . assign ( { } , textBlock , { text : truncatedText } ) ;
322+ if ( typeof textBlock . content === "string" ) {
323+ nextBlock . content = truncatedText ;
324+ }
325+ return nextBlock ;
323326 } ) ;
324327
325328 return { ...msg , content : newContent } as AgentMessage ;
326329}
327330
331+ function isToolResultTextBlock (
332+ block : unknown ,
333+ ) : block is TextContent & { content ?: unknown ; type : "text" | "toolResult" } {
334+ if ( ! block || typeof block !== "object" ) {
335+ return false ;
336+ }
337+ const type = ( block as { type ?: unknown } ) . type ;
338+ return (
339+ ( type === "text" || type === "toolResult" ) &&
340+ typeof ( block as { text ?: unknown } ) . text === "string"
341+ ) ;
342+ }
343+
328344/**
329345 * Truncate oversized tool results in an array of messages (in-memory).
330346 * Returns a new array with truncated messages.
0 commit comments