66} from '@codebuff/common/tools/constants'
77import { buildArray } from '@codebuff/common/util/array'
88import { generateCompactId } from '@codebuff/common/util/string'
9+ import { cloneDeep } from 'lodash'
910
1011import { expireMessages } from '../util/messages'
1112import { sendAction } from '../websockets/websocket-action'
@@ -17,7 +18,10 @@ import type { StreamChunk } from '../llm-apis/vercel-ai-sdk/ai-sdk'
1718import type { AgentTemplate } from '../templates/types'
1819import type { ToolName } from '@codebuff/common/tools/constants'
1920import type { CodebuffToolCall } from '@codebuff/common/tools/list'
20- import type { Message } from '@codebuff/common/types/messages/codebuff-message'
21+ import type {
22+ Message ,
23+ ToolMessage ,
24+ } from '@codebuff/common/types/messages/codebuff-message'
2125import type { ToolResultPart } from '@codebuff/common/types/messages/content-part'
2226import type { PrintModeEvent } from '@codebuff/common/types/print-mode'
2327import type { AgentState , Subgoal } from '@codebuff/common/types/session-state'
@@ -70,6 +74,7 @@ export async function processStreamWithTools(options: {
7074 const messages = [ ...options . messages ]
7175
7276 const toolResults : ToolResultPart [ ] = [ ]
77+ const toolResultsToAddAfterStream : ToolResultPart [ ] = [ ]
7378 const toolCalls : ( CodebuffToolCall | CustomToolCall ) [ ] = [ ]
7479 const { promise : streamDonePromise , resolve : resolveStreamDonePromise } =
7580 Promise . withResolvers < void > ( )
@@ -160,12 +165,14 @@ export async function processStreamWithTools(options: {
160165 ] ) ,
161166 ] ) ,
162167 ( toolName , error ) => {
163- toolResults . push ( {
168+ const toolResult : ToolResultPart = {
164169 type : 'tool-result' ,
165170 toolName,
166171 toolCallId : generateCompactId ( ) ,
167172 output : [ { type : 'json' , value : { errorMessage : error } } ] ,
168- } )
173+ }
174+ toolResults . push ( cloneDeep ( toolResult ) )
175+ toolResultsToAddAfterStream . push ( cloneDeep ( toolResult ) )
169176 } ,
170177 onResponseChunk ,
171178 {
@@ -212,6 +219,12 @@ export async function processStreamWithTools(options: {
212219 role : 'assistant' as const ,
213220 content : fullResponseChunks . join ( '' ) ,
214221 } ,
222+ ...toolResultsToAddAfterStream . map ( ( toolResult ) => {
223+ return {
224+ role : 'tool' ,
225+ content : toolResult ,
226+ } satisfies ToolMessage
227+ } ) ,
215228 ] )
216229
217230 resolveStreamDonePromise ( )
0 commit comments