( tool: Tool<AnyObject, Output>, toolUseResult: Output, )
| 4386 | } |
| 4387 | |
| 4388 | function createToolResultMessage<Output>( |
| 4389 | tool: Tool<AnyObject, Output>, |
| 4390 | toolUseResult: Output, |
| 4391 | ): UserMessage { |
| 4392 | try { |
| 4393 | const result = tool.mapToolResultToToolResultBlockParam(toolUseResult, '1') |
| 4394 | |
| 4395 | // If the result contains image content blocks, preserve them as is |
| 4396 | if ( |
| 4397 | Array.isArray(result.content) && |
| 4398 | result.content.some(block => block.type === 'image') |
| 4399 | ) { |
| 4400 | return createUserMessage({ |
| 4401 | content: result.content as ContentBlockParam[], |
| 4402 | isMeta: true, |
| 4403 | }) |
| 4404 | } |
| 4405 | |
| 4406 | // For string content, use raw string — jsonStringify would escape \n→\\n, |
| 4407 | // wasting ~1 token per newline (a 2000-line @-file = ~1000 wasted tokens). |
| 4408 | // Keep jsonStringify for array/object content where structure matters. |
| 4409 | const contentStr = |
| 4410 | typeof result.content === 'string' |
| 4411 | ? result.content |
| 4412 | : jsonStringify(result.content) |
| 4413 | return createUserMessage({ |
| 4414 | content: `Result of calling the ${tool.name} tool:\n${contentStr}`, |
| 4415 | isMeta: true, |
| 4416 | }) |
| 4417 | } catch { |
| 4418 | return createUserMessage({ |
| 4419 | content: `Result of calling the ${tool.name} tool: Error`, |
| 4420 | isMeta: true, |
| 4421 | }) |
| 4422 | } |
| 4423 | } |
| 4424 | |
| 4425 | function createToolUseMessage( |
| 4426 | toolName: string, |
no test coverage detected