{"version":3,"file":"tool-call-engine/base/ToolCallEngineBase.mjs","sources":["webpack://@multimodal/agent/./src/tool-call-engine/base/ToolCallEngineBase.ts"],"sourcesContent":["/*\n * Copyright (c) 2025 Bytedance, Inc. and its affiliates.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n  Tool,\n  ToolCallEngine,\n  StreamProcessingState,\n  StreamChunkResult,\n  ChatCompletionMessageToolCall,\n} from '@multimodal/agent-interface';\nimport { zodToJsonSchema } from '../../utils';\nimport { getLogger } from '../../utils/logger';\n\n/**\n * Base configuration for tool call engines\n */\nexport interface ToolCallEngineConfig {\n  /** Maximum size of content buffer in characters */\n  maxBufferSize?: number;\n  /** Maximum number of tool calls to track */\n  maxToolCalls?: number;\n}\n\n/**\n * Cached tool description to avoid repeated generation\n */\ninterface CachedToolDescription {\n  tools: Tool[];\n  description: string;\n  hash: string;\n}\n\n/**\n * Base class for all Tool Call Engines providing common functionality\n * and performance optimizations\n */\nexport abstract class ToolCallEngineBase extends ToolCallEngine {\n  protected logger = getLogger('ToolCallEngineBase');\n  protected config: Required<ToolCallEngineConfig>;\n  private toolDescriptionCache: CachedToolDescription | null = null;\n\n  constructor(config: ToolCallEngineConfig = {}) {\n    super();\n    this.config = {\n      maxBufferSize: config.maxBufferSize ?? 1024 * 1024, // 1MB default\n      maxToolCalls: config.maxToolCalls ?? 100,\n    };\n  }\n\n  /**\n   * Generate a hash for tools array to enable caching\n   */\n  private generateToolsHash(tools: Tool[]): string {\n    return tools\n      .map((tool) => `${tool.name}:${tool.description}`)\n      .sort()\n      .join('|');\n  }\n\n  /**\n   * Get cached or generate tool description\n   */\n  protected getCachedToolDescription(tools: Tool[]): string {\n    if (tools.length === 0) return '';\n\n    const hash = this.generateToolsHash(tools);\n    \n    if (this.toolDescriptionCache?.hash === hash) {\n      return this.toolDescriptionCache.description;\n    }\n\n    const description = this.generateToolDescription(tools);\n    this.toolDescriptionCache = { tools, description, hash };\n    \n    return description;\n  }\n\n  /**\n   * Generate tool description - to be implemented by subclasses\n   */\n  protected abstract generateToolDescription(tools: Tool[]): string;\n\n  /**\n   * Format tool parameters with caching for better performance\n   */\n  protected formatToolParameters(tool: Tool): string {\n    const schema = zodToJsonSchema(tool.schema);\n    const properties = schema.properties || {};\n    const requiredProps = schema.required || [];\n\n    if (Object.keys(properties).length === 0) {\n      return 'No parameters required';\n    }\n\n    return Object.entries(properties)\n      .map(([name, prop]: [string, any]) => {\n        const isRequired = requiredProps.includes(name);\n        const description = prop.description || 'No description';\n        return `- ${name}${isRequired ? ' (required)' : ''}: ${description} (type: ${prop.type})`;\n      })\n      .join('\\n');\n  }\n\n  /**\n   * Safely truncate buffer if it exceeds maximum size\n   */\n  protected truncateBuffer(buffer: string): string {\n    if (buffer.length <= this.config.maxBufferSize) {\n      return buffer;\n    }\n\n    this.logger.warn(`Buffer exceeded max size (${this.config.maxBufferSize}), truncating`);\n    return buffer.slice(-this.config.maxBufferSize);\n  }\n\n  /**\n   * Validate and limit tool calls array\n   */\n  protected validateToolCalls(toolCalls: ChatCompletionMessageToolCall[]): ChatCompletionMessageToolCall[] {\n    if (toolCalls.length <= this.config.maxToolCalls) {\n      return toolCalls;\n    }\n\n    this.logger.warn(`Tool calls exceeded max count (${this.config.maxToolCalls}), limiting`);\n    return toolCalls.slice(0, this.config.maxToolCalls);\n  }\n\n  /**\n   * Create a safe processing state with memory limits\n   */\n  protected createSafeProcessingState(): StreamProcessingState {\n    return {\n      contentBuffer: '',\n      toolCalls: [],\n      reasoningBuffer: '',\n      finishReason: null,\n    };\n  }\n\n  /**\n   * Update processing state with safety checks\n   */\n  protected updateProcessingState(\n    state: StreamProcessingState,\n    contentDelta: string,\n    reasoningDelta: string = ''\n  ): void {\n    // Update content buffer with truncation\n    state.contentBuffer = this.truncateBuffer(state.contentBuffer + contentDelta);\n    \n    // Update reasoning buffer with truncation\n    if (reasoningDelta) {\n      state.reasoningBuffer = this.truncateBuffer(state.reasoningBuffer + reasoningDelta);\n    }\n\n    // Validate tool calls\n    state.toolCalls = this.validateToolCalls(state.toolCalls);\n  }\n\n  /**\n   * Handle common error scenarios in streaming\n   */\n  protected handleStreamingError(error: unknown, context: string): StreamChunkResult {\n    this.logger.error(`Error in ${context}: ${error}`);\n    \n    return {\n      content: '',\n      reasoningContent: '',\n      hasToolCallUpdate: false,\n      toolCalls: [],\n    };\n  }\n\n  /**\n   * Clear cache - useful for testing or when tools change frequently\n   */\n  public clearCache(): void {\n    this.toolDescriptionCache = null;\n  }\n}\n"],"names":["ToolCallEngineBase","ToolCallEngine","tools","tool","_this_toolDescriptionCache","hash","description","schema","zodToJsonSchema","properties","requiredProps","Object","name","prop","isRequired","buffer","toolCalls","state","contentDelta","reasoningDelta","error","context","config","getLogger"],"mappings":";;;;;;;AAGC;;;;;;;;;;AAmCM,MAAeA,2BAA2BC;IAgBvC,kBAAkBC,KAAa,EAAU;QAC/C,OAAOA,MACJ,GAAG,CAAC,CAACC,OAAS,GAAGA,KAAK,IAAI,CAAC,CAAC,EAAEA,KAAK,WAAW,EAAE,EAChD,IAAI,GACJ,IAAI,CAAC;IACV;IAKU,yBAAyBD,KAAa,EAAU;YAKpDE;QAJJ,IAAIF,AAAiB,MAAjBA,MAAM,MAAM,EAAQ,OAAO;QAE/B,MAAMG,OAAO,IAAI,CAAC,iBAAiB,CAACH;QAEpC,IAAIE,AAAAA,SAAAA,CAAAA,6BAAAA,IAAI,CAAC,oBAAoB,AAAD,IAAxBA,KAAAA,IAAAA,2BAA2B,IAAI,AAAD,MAAMC,MACtC,OAAO,IAAI,CAAC,oBAAoB,CAAC,WAAW;QAG9C,MAAMC,cAAc,IAAI,CAAC,uBAAuB,CAACJ;QACjD,IAAI,CAAC,oBAAoB,GAAG;YAAEA;YAAOI;YAAaD;QAAK;QAEvD,OAAOC;IACT;IAUU,qBAAqBH,IAAU,EAAU;QACjD,MAAMI,SAASC,gBAAgBL,KAAK,MAAM;QAC1C,MAAMM,aAAaF,OAAO,UAAU,IAAI,CAAC;QACzC,MAAM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