11import type { PluginState } from "./state"
22
3+ /** Maximum number of tool parameters to cache to prevent unbounded memory growth */
4+ const MAX_TOOL_PARAMETERS_CACHE_SIZE = 500
5+
6+ /**
7+ * Ensures the toolParameters cache doesn't exceed the maximum size.
8+ * Removes oldest entries (first inserted) when limit is exceeded.
9+ */
10+ function trimToolParametersCache ( state : PluginState ) : void {
11+ if ( state . toolParameters . size > MAX_TOOL_PARAMETERS_CACHE_SIZE ) {
12+ const excess = state . toolParameters . size - MAX_TOOL_PARAMETERS_CACHE_SIZE
13+ const keys = Array . from ( state . toolParameters . keys ( ) )
14+ for ( let i = 0 ; i < excess ; i ++ ) {
15+ state . toolParameters . delete ( keys [ i ] )
16+ }
17+ }
18+ }
19+
320/**
421 * Cache tool parameters from OpenAI Chat Completions style messages.
522 * Extracts tool call IDs and their parameters from assistant messages with tool_calls.
23+ * Returns the list of tool call IDs that were cached from this request.
624 */
725export function cacheToolParametersFromMessages (
826 messages : any [ ] ,
927 state : PluginState
10- ) : void {
28+ ) : string [ ] {
29+ const cachedIds : string [ ] = [ ]
1130 for ( const message of messages ) {
1231 if ( message . role !== 'assistant' || ! Array . isArray ( message . tool_calls ) ) {
1332 continue
@@ -26,21 +45,26 @@ export function cacheToolParametersFromMessages(
2645 tool : toolCall . function . name ,
2746 parameters : params
2847 } )
48+ cachedIds . push ( toolCall . id )
2949 } catch ( error ) {
3050 // Silently ignore parse errors
3151 }
3252 }
3353 }
54+ trimToolParametersCache ( state )
55+ return cachedIds
3456}
3557
3658/**
3759 * Cache tool parameters from OpenAI Responses API format.
3860 * Extracts from input array items with type='function_call'.
61+ * Returns the list of tool call IDs that were cached from this request.
3962 */
4063export function cacheToolParametersFromInput (
4164 input : any [ ] ,
4265 state : PluginState
43- ) : void {
66+ ) : string [ ] {
67+ const cachedIds : string [ ] = [ ]
4468 for ( const item of input ) {
4569 if ( item . type !== 'function_call' || ! item . call_id || ! item . name ) {
4670 continue
@@ -54,8 +78,11 @@ export function cacheToolParametersFromInput(
5478 tool : item . name ,
5579 parameters : params
5680 } )
81+ cachedIds . push ( item . call_id )
5782 } catch ( error ) {
5883 // Silently ignore parse errors
5984 }
6085 }
86+ trimToolParametersCache ( state )
87+ return cachedIds
6188}
0 commit comments