| 1 | import type { ChatHistoryItem, ToolCallState, ToolStatus } from "core/index.js"; |
| 2 | |
| 3 | import { getCurrentSession, updateSessionTitle } from "../../session.js"; |
| 4 | |
| 5 | import { generateSessionTitle } from "./useChat.helpers.js"; |
| 6 | |
| 7 | interface CreateStreamCallbacksOptions { |
| 8 | setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; |
| 9 | setActivePermissionRequest: React.Dispatch<React.SetStateAction<any>>; |
| 10 | llmApi?: any; |
| 11 | model?: any; |
| 12 | } |
| 13 | |
| 14 | /** |
| 15 | * Create stream callbacks for chat response |
| 16 | */ |
| 17 | export function createStreamCallbacks( |
| 18 | options: CreateStreamCallbacksOptions, |
| 19 | ): any { |
| 20 | const { setChatHistory, setActivePermissionRequest, llmApi, model } = options; |
| 21 | |
| 22 | return { |
| 23 | onContent: (_: string) => {}, |
| 24 | |
| 25 | onContentComplete: async (content: string) => { |
| 26 | setChatHistory((prev) => [ |
| 27 | ...prev, |
| 28 | { |
| 29 | contextItems: [], |
| 30 | message: { |
| 31 | role: "assistant", |
| 32 | content: content, |
| 33 | isStreaming: false, |
| 34 | }, |
| 35 | }, |
| 36 | ]); |
| 37 | |
| 38 | // Generate session title after first assistant response |
| 39 | if (content && llmApi && model) { |
| 40 | const currentSession = getCurrentSession(); |
| 41 | const generatedTitle = await generateSessionTitle( |
| 42 | content, |
| 43 | llmApi, |
| 44 | model, |
| 45 | currentSession.title, |
| 46 | ); |
| 47 | |
| 48 | if (generatedTitle) { |
| 49 | updateSessionTitle(generatedTitle); |
| 50 | } |
| 51 | } |
| 52 | }, |
| 53 | |
| 54 | onToolStart: (toolName: string, toolArgs?: any) => { |
| 55 | setChatHistory((prev) => { |
| 56 | const newHistory = [...prev]; |
| 57 | |
| 58 | // Always create a new assistant message for each tool call |
| 59 | const toolCallId = `tool_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`; |
| 60 | const toolCallState: ToolCallState = { |
| 61 | toolCallId: toolCallId, |
| 62 | toolCall: { |
| 63 | id: toolCallId, |
| 64 | type: "function", |
| 65 | function: { |
| 66 | name: toolName, |
| 67 | arguments: JSON.stringify(toolArgs || {}), |
| 68 | }, |
| 69 | }, |
| 70 | status: "calling", |
| 71 | parsedArgs: toolArgs, |
| 72 | }; |
| 73 | |
| 74 | newHistory.push({ |
| 75 | message: { |
| 76 | role: "assistant", |
| 77 | content: "", |
| 78 | toolCalls: [ |
| 79 | { |
| 80 | id: toolCallId, |
| 81 | type: "function", |
| 82 | function: { |
| 83 | name: toolName, |
| 84 | arguments: JSON.stringify(toolArgs || {}), |
| 85 | }, |
| 86 | }, |
| 87 | ], |
| 88 | }, |
| 89 | contextItems: [], |
| 90 | toolCallStates: [toolCallState], |
| 91 | }); |
| 92 | |
| 93 | return newHistory; |
| 94 | }); |
| 95 | }, |
| 96 | |
| 97 | onToolResult: (result: string, toolName: string, status: ToolStatus) => { |
| 98 | setChatHistory((prev) => { |
| 99 | const newHistory = [...prev]; |
| 100 | |
| 101 | // Find the tool call state and update it |
| 102 | for (let i = newHistory.length - 1; i >= 0; i--) { |
| 103 | const item = newHistory[i]; |
| 104 | if (item.toolCallStates) { |
| 105 | const toolState = item.toolCallStates.find( |
| 106 | (ts) => |
| 107 | ts.toolCall.function.name === toolName && |
| 108 | ts.status === "calling", |
| 109 | ); |
| 110 | |
| 111 | if (toolState) { |
| 112 | toolState.status = status; |
| 113 | toolState.output = [ |
| 114 | { |
| 115 | content: result, |
| 116 | name: `Tool Result: ${toolName}`, |
| 117 | description: "Tool execution result", |
| 118 | }, |
| 119 | ]; |
| 120 | break; |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | return newHistory; |
| 126 | }); |
| 127 | }, |
| 128 | |
| 129 | onToolError: (error: string, toolName?: string) => { |
| 130 | setChatHistory((prev) => { |
| 131 | const newHistory = [...prev]; |
| 132 | |
| 133 | // Find the tool call state and mark it as errored |
| 134 | if (toolName) { |
| 135 | for (let i = newHistory.length - 1; i >= 0; i--) { |
| 136 | const item = newHistory[i]; |
| 137 | if (item.toolCallStates) { |
| 138 | const toolState = item.toolCallStates.find( |
| 139 | (ts) => |
| 140 | ts.toolCall.function.name === toolName && |
| 141 | ts.status === "calling", |
| 142 | ); |
| 143 | |
| 144 | if (toolState) { |
| 145 | toolState.status = "errored"; |
| 146 | toolState.output = [ |
| 147 | { |
| 148 | content: error, |
| 149 | name: `Tool Error: ${toolName}`, |
| 150 | description: "Tool execution error", |
| 151 | }, |
| 152 | ]; |
| 153 | break; |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 | } else { |
| 158 | // General error message |
| 159 | newHistory.push({ |
| 160 | message: { |
| 161 | role: "system", |
| 162 | content: error, |
| 163 | }, |
| 164 | contextItems: [], |
| 165 | }); |
| 166 | } |
| 167 | |
| 168 | return newHistory; |
| 169 | }); |
| 170 | }, |
| 171 | |
| 172 | onToolPermissionRequest: ( |
| 173 | toolName: string, |
| 174 | toolArgs: any, |
| 175 | requestId: string, |
| 176 | toolCallPreview?: any[], |
| 177 | ) => { |
| 178 | setActivePermissionRequest({ |
| 179 | toolName, |
| 180 | toolArgs, |
| 181 | requestId, |
| 182 | toolCallPreview, |
| 183 | }); |
| 184 | }, |
| 185 | |
| 186 | onSystemMessage: (message: string) => { |
| 187 | setChatHistory((prev) => [ |
| 188 | ...prev, |
| 189 | { |
| 190 | message: { |
| 191 | role: "system", |
| 192 | content: message, |
| 193 | }, |
| 194 | contextItems: [], |
| 195 | }, |
| 196 | ]); |
| 197 | }, |
| 198 | }; |
| 199 | } |
| 200 | |
| 201 | interface ExecuteStreamingOptions { |
| 202 | chatHistory: ChatHistoryItem[]; |
| 203 | model: any; |
| 204 | llmApi: any; |
| 205 | controller: AbortController; |
| 206 | streamCallbacks: any; |
| 207 | currentCompactionIndex: number | null; |
| 208 | } |
| 209 | |
| 210 | /** |
| 211 | * Execute streaming chat response |
| 212 | */ |
| 213 | export async function executeStreaming({ |
| 214 | chatHistory, |
| 215 | model, |
| 216 | llmApi, |
| 217 | controller, |
| 218 | streamCallbacks, |
| 219 | currentCompactionIndex, |
| 220 | }: ExecuteStreamingOptions): Promise<void> { |
| 221 | const { getHistoryForLLM } = await import("../../compaction.js"); |
| 222 | const { streamChatResponse } = await import( |
| 223 | "../../stream/streamChatResponse.js" |
| 224 | ); |
| 225 | |
| 226 | if (model && llmApi) { |
| 227 | if ( |
| 228 | currentCompactionIndex !== null && |
| 229 | currentCompactionIndex !== undefined |
| 230 | ) { |
| 231 | const historyForLLM = getHistoryForLLM( |
| 232 | chatHistory, |
| 233 | currentCompactionIndex, |
| 234 | ); |
| 235 | const _originalLength = historyForLLM.length; |
| 236 | |
| 237 | await streamChatResponse( |
| 238 | historyForLLM, |
| 239 | model, |
| 240 | llmApi, |
| 241 | controller, |
| 242 | streamCallbacks, |
| 243 | ); |
| 244 | |
| 245 | // streamChatResponse modifies the array in place |
| 246 | // The new messages are already in historyForLLM |
| 247 | } else { |
| 248 | await streamChatResponse( |
| 249 | chatHistory, |
| 250 | model, |
| 251 | llmApi, |
| 252 | controller, |
| 253 | streamCallbacks, |
| 254 | ); |
| 255 | } |
| 256 | } |
| 257 | } |