@@ -61,35 +61,46 @@ export function mergeToolResultsIntoMessages(
6161export function sanitizeMessagesForChatName (
6262 messages : ModelMessage [ ] ,
6363) : ModelMessage [ ] {
64- return messages
65- . filter ( ( m ) => m . role === 'user' || m . role === 'assistant' )
66- . map ( ( m ) => {
67- if ( typeof m . content === 'string' ) {
68- const text = m . content . trim ( ) ;
69- return text ? { role : m . role , content : text } : null ;
70- }
71- if ( Array . isArray ( m . content ) ) {
72- const textParts : string [ ] = [ ] ;
73- for ( const part of m . content as Array < unknown > ) {
64+ const isSupportedRole = ( m : ModelMessage ) =>
65+ m . role === 'user' || m . role === 'assistant' ;
66+
67+ const extractText = ( content : ModelMessage [ 'content' ] ) : string | null => {
68+ if ( typeof content === 'string' ) {
69+ const text = content . trim ( ) ;
70+ return text ? text : null ;
71+ }
72+
73+ if ( Array . isArray ( content ) ) {
74+ const merged = ( content as Array < unknown > )
75+ . reduce < string [ ] > ( ( acc , part ) => {
7476 if (
7577 part &&
7678 typeof part === 'object' &&
7779 'type' in ( part as Record < string , unknown > )
7880 ) {
7981 const p = part as { type ?: string ; text ?: string } ;
8082 if ( p . type === 'text' && typeof p . text === 'string' ) {
81- textParts . push ( p . text ) ;
83+ acc . push ( p . text ) ;
8284 }
8385 }
84- }
85- const merged = textParts . join ( '\n' ) . trim ( ) ;
86- return merged
87- ? ( { role : m . role , content : merged } as ModelMessage )
88- : null ;
89- }
90- return null ;
86+ return acc ;
87+ } , [ ] )
88+ . join ( '\n' )
89+ . trim ( ) ;
90+
91+ return merged ? merged : null ;
92+ }
93+
94+ return null ;
95+ } ;
96+
97+ return messages
98+ . filter ( isSupportedRole )
99+ . map ( ( m ) => {
100+ const text = extractText ( m . content ) ;
101+ return text ? ( { role : m . role , content : text } as ModelMessage ) : null ;
91102 } )
92- . filter ( ( m ) => m !== null ) ;
103+ . filter ( ( m ) : m is ModelMessage => m !== null ) ;
93104}
94105
95106function isToolMessage ( msg : ModelMessage ) : boolean {
0 commit comments