* 执行工具并设置超时
(
tool: ToolDefinition,
parameters: Record<string, any>
)
| 336 | * 执行工具并设置超时 |
| 337 | */ |
| 338 | private async executeToolWithTimeout( |
| 339 | tool: ToolDefinition, |
| 340 | parameters: Record<string, any> |
| 341 | ): Promise<ToolExecutionResult> { |
| 342 | const startTime = Date.now(); |
| 343 | |
| 344 | return new Promise((resolve, reject) => { |
| 345 | const timeoutId = setTimeout(() => { |
| 346 | reject( |
| 347 | new ToolExecutionError(`工具执行超时 (${this.config.executionTimeout}ms)`, tool.name) |
| 348 | ); |
| 349 | }, this.config.executionTimeout); |
| 350 | |
| 351 | Promise.resolve(tool.execute(parameters)) |
| 352 | .then(result => { |
| 353 | clearTimeout(timeoutId); |
| 354 | const duration = Date.now() - startTime; |
| 355 | |
| 356 | // 如果工具返回的已经是 ToolExecutionResult 格式,直接使用 |
| 357 | if (result && typeof result === 'object' && 'success' in result) { |
| 358 | resolve({ |
| 359 | ...result, |
| 360 | duration: result.duration || duration, |
| 361 | }); |
| 362 | } else { |
| 363 | // 否则包装成标准格式 |
| 364 | resolve({ |
| 365 | success: true, |
| 366 | data: result, |
| 367 | duration, |
| 368 | }); |
| 369 | } |
| 370 | }) |
| 371 | .catch(error => { |
| 372 | clearTimeout(timeoutId); |
| 373 | reject(new ToolExecutionError(`工具执行错误: ${error.message}`, tool.name, error)); |
| 374 | }); |
| 375 | }); |
| 376 | } |
| 377 | |
| 378 | /** |
| 379 | * 添加到历史记录 |