@@ -14,6 +14,8 @@ export class AssistantMessageParser {
1414 private currentToolUseStartIndex = 0
1515 private currentParamName : ToolParamName | undefined = undefined
1616 private currentParamValueStartIndex = 0
17+ private readonly MAX_ACCUMULATOR_SIZE = 1024 * 1024 // 1MB limit
18+ private readonly MAX_PARAM_LENGTH = 1024 * 100 // 100KB per parameter limit
1719 private accumulator = ""
1820
1921 /**
@@ -50,6 +52,9 @@ export class AssistantMessageParser {
5052 * @param chunk The new chunk of text to process.
5153 */
5254 public processChunk ( chunk : string ) : AssistantMessageContent [ ] {
55+ if ( this . accumulator . length + chunk . length > this . MAX_ACCUMULATOR_SIZE ) {
56+ throw new Error ( "Assistant message exceeds maximum allowed size" )
57+ }
5358 // Store the current length of the accumulator before adding the new chunk
5459 const accumulatorStartLength = this . accumulator . length
5560
@@ -61,6 +66,12 @@ export class AssistantMessageParser {
6166 // There should not be a param without a tool use.
6267 if ( this . currentToolUse && this . currentParamName ) {
6368 const currentParamValue = this . accumulator . slice ( this . currentParamValueStartIndex )
69+ if ( currentParamValue . length > this . MAX_PARAM_LENGTH ) {
70+ // Reset to a safe state
71+ this . currentParamName = undefined
72+ this . currentParamValueStartIndex = 0
73+ continue
74+ }
6475 const paramClosingTag = `</${ this . currentParamName } >`
6576 // Streamed param content: always write the currently accumulated value
6677 if ( currentParamValue . endsWith ( paramClosingTag ) ) {
@@ -97,7 +108,12 @@ export class AssistantMessageParser {
97108 for ( const paramOpeningTag of possibleParamOpeningTags ) {
98109 if ( this . accumulator . endsWith ( paramOpeningTag ) ) {
99110 // Start of a new parameter.
100- this . currentParamName = paramOpeningTag . slice ( 1 , - 1 ) as ToolParamName
111+ const paramName = paramOpeningTag . slice ( 1 , - 1 )
112+ if ( ! toolParamNames . includes ( paramName as ToolParamName ) ) {
113+ // Handle invalid parameter name gracefully
114+ continue
115+ }
116+ this . currentParamName = paramName as ToolParamName
101117 this . currentParamValueStartIndex = this . accumulator . length
102118 break
103119 }
0 commit comments