| 1 | import type { ChatHistoryItem, ToolCallState, ToolStatus } from "core/index.js"; |
| 2 | |
| 3 | import { getAllBuiltinTools } from "src/tools/index.js"; |
| 4 | import { logger } from "src/util/logger.js"; |
| 5 | |
| 6 | import { services } from "../../services/index.js"; |
| 7 | import { getCurrentSession, updateSessionTitle } from "../../session.js"; |
| 8 | |
| 9 | import { generateSessionTitle } from "./useChat.helpers.js"; |
| 10 | |
| 11 | interface CreateStreamCallbacksOptions { |
| 12 | setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; |
| 13 | setActivePermissionRequest: React.Dispatch<React.SetStateAction<any>>; |
| 14 | llmApi?: any; |
| 15 | model?: any; |
| 16 | } |
| 17 | |
| 18 | /** |
| 19 | * Create stream callbacks for chat response |
| 20 | */ |
| 21 | export function createStreamCallbacks( |
| 22 | options: CreateStreamCallbacksOptions, |
| 23 | ): any { |
| 24 | const { setChatHistory, setActivePermissionRequest, llmApi, model } = options; |
| 25 | |
| 26 | return { |
| 27 | onContent: (_: string) => {}, |
| 28 | |
| 29 | onContentComplete: async (content: string) => { |
| 30 | // Do not add assistant messages via service; handleToolCalls is the single writer |
| 31 | // For environments where the service isn't ready (unit tests), update local state only |
| 32 | try { |
| 33 | const svc = services.chatHistory; |
| 34 | const useService = typeof svc?.isReady === "function" && svc.isReady(); |
| 35 | if (!useService && content) { |
| 36 | setChatHistory((prev) => [ |
| 37 | ...prev, |
| 38 | { |
| 39 | contextItems: [], |
| 40 | message: { |
| 41 | role: "assistant", |
| 42 | content: content, |
| 43 | isStreaming: false, |
| 44 | }, |
| 45 | }, |
| 46 | ]); |
| 47 | } |
| 48 | } catch (error) { |
| 49 | logger.error("Failed to update chat history", { error }); |
| 50 | } |
| 51 | // Generate session title after first assistant response |
| 52 | if (content && llmApi && model) { |
| 53 | const currentSession = getCurrentSession(); |
| 54 | const generatedTitle = await generateSessionTitle( |
| 55 | content, |
| 56 | llmApi, |
| 57 | model, |
| 58 | currentSession.title, |
| 59 | ); |
| 60 | |
| 61 | if (generatedTitle) { |
| 62 | updateSessionTitle(generatedTitle); |
| 63 | } |
| 64 | } |
| 65 | }, |
| 66 | |
| 67 | onToolStart: (toolName: string, toolArgs?: any) => { |
| 68 | // When ChatHistoryService is ready, let handleToolCalls add entries |
| 69 | const svc = services.chatHistory; |
| 70 | const useService = typeof svc?.isReady === "function" && svc.isReady(); |
| 71 | if (useService) return; |
| 72 | |
| 73 | // Fallback (service not ready): create a local assistant message representing the tool call |
| 74 | setChatHistory((prev) => { |
| 75 | const newHistory = [...prev]; |
| 76 | |
| 77 | const toolCallId = `tool_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`; |
| 78 | const toolCallState: ToolCallState = { |
| 79 | toolCallId: toolCallId, |
| 80 | toolCall: { |
| 81 | id: toolCallId, |
| 82 | type: "function", |
| 83 | function: { |
| 84 | name: toolName, |
| 85 | arguments: JSON.stringify(toolArgs || {}), |
| 86 | }, |
| 87 | }, |
| 88 | status: "calling", |
| 89 | parsedArgs: toolArgs, |
| 90 | }; |
| 91 | |
| 92 | newHistory.push({ |
| 93 | message: { |
| 94 | role: "assistant", |
| 95 | content: "", |
| 96 | toolCalls: [ |
| 97 | { |
| 98 | id: toolCallId, |
| 99 | type: "function", |
| 100 | function: { |
| 101 | name: toolName, |
| 102 | arguments: JSON.stringify(toolArgs || {}), |
| 103 | }, |
| 104 | }, |
| 105 | ], |
| 106 | }, |
| 107 | contextItems: [], |
| 108 | toolCallStates: [toolCallState], |
| 109 | }); |
| 110 | |
| 111 | return newHistory; |
| 112 | }); |
| 113 | }, |
| 114 | |
| 115 | onToolResult: (result: string, toolName: string, status: ToolStatus) => { |
| 116 | // When service is ready, it updates tool results; avoid duplicate local updates |
| 117 | const svc = services.chatHistory; |
| 118 | const useService = typeof svc?.isReady === "function" && svc.isReady(); |
| 119 | if (useService) return; |
| 120 | |
| 121 | // Fallback (service not ready): update local UI-only state |
| 122 | setChatHistory((prev) => { |
| 123 | const newHistory = [...prev]; |
| 124 | |
| 125 | for (let i = newHistory.length - 1; i >= 0; i--) { |
| 126 | const item = newHistory[i]; |
| 127 | if (item.toolCallStates) { |
| 128 | const toolState = item.toolCallStates.find( |
| 129 | (ts) => |
| 130 | ts.toolCall.function.name === toolName && |
| 131 | (ts.status === "calling" || ts.status === "generated"), |
| 132 | ); |
| 133 | |
| 134 | if (toolState) { |
| 135 | toolState.status = status; |
| 136 | toolState.output = [ |
| 137 | { |
| 138 | content: result, |
| 139 | name: `Tool Result: ${toolName}`, |
| 140 | description: "Tool execution result", |
| 141 | }, |
| 142 | ]; |
| 143 | break; |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | return newHistory; |
| 149 | }); |
| 150 | }, |
| 151 | |
| 152 | onToolError: (error: string, toolName?: string) => { |
| 153 | // When service is ready, handleToolCalls adds error entries; avoid duplicate local updates |
| 154 | const svc = services.chatHistory; |
| 155 | const useService = typeof svc?.isReady === "function" && svc.isReady(); |
| 156 | if (useService) return; |
| 157 | |
| 158 | setChatHistory((prev) => { |
| 159 | const newHistory = [...prev]; |
| 160 | |
| 161 | if (toolName) { |
| 162 | for (let i = newHistory.length - 1; i >= 0; i--) { |
| 163 | const item = newHistory[i]; |
| 164 | if (item.toolCallStates) { |
| 165 | const toolState = item.toolCallStates.find( |
| 166 | (ts) => |
| 167 | ts.toolCall.function.name === toolName && |
| 168 | (ts.status === "calling" || ts.status === "generated"), |
| 169 | ); |
| 170 | |
| 171 | if (toolState) { |
| 172 | toolState.status = "errored"; |
| 173 | toolState.output = [ |
| 174 | { |
| 175 | content: error, |
| 176 | name: `Tool Error: ${toolName}`, |
| 177 | description: "Tool execution error", |
| 178 | }, |
| 179 | ]; |
| 180 | break; |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | } else { |
| 185 | // General error message |
| 186 | newHistory.push({ |
| 187 | message: { |
| 188 | role: "system", |
| 189 | content: error, |
| 190 | }, |
| 191 | contextItems: [], |
| 192 | }); |
| 193 | } |
| 194 | |
| 195 | return newHistory; |
| 196 | }); |
| 197 | }, |
| 198 | |
| 199 | onToolPermissionRequest: ( |
| 200 | toolName: string, |
| 201 | toolArgs: any, |
| 202 | requestId: string, |
| 203 | toolCallPreview?: any[], |
| 204 | ) => { |
| 205 | // Check if this tool has dynamic evaluation |
| 206 | const tool = getAllBuiltinTools().find((t: any) => t.name === toolName); |
| 207 | const hasDynamicEvaluation = !!tool?.evaluateToolCallPolicy; |
| 208 | |
| 209 | setActivePermissionRequest({ |
| 210 | toolName, |
| 211 | toolArgs, |
| 212 | requestId, |
| 213 | toolCallPreview, |
| 214 | hasDynamicEvaluation, |
| 215 | }); |
| 216 | }, |
| 217 | |
| 218 | onSystemMessage: (message: string) => { |
| 219 | try { |
| 220 | const svc = services.chatHistory; |
| 221 | if (typeof svc?.isReady === "function" && svc.isReady()) { |
| 222 | svc.addSystemMessage(message); |
| 223 | return; |
| 224 | } |
| 225 | } catch {} |
| 226 | // Fallback to local state if service unavailable |
| 227 | setChatHistory((prev) => [ |
| 228 | ...prev, |
| 229 | { |
| 230 | message: { |
| 231 | role: "system", |
| 232 | content: message, |
| 233 | }, |
| 234 | contextItems: [], |
| 235 | }, |
| 236 | ]); |
| 237 | }, |
| 238 | }; |
| 239 | } |
| 240 | |
| 241 | interface ExecuteStreamingOptions { |
| 242 | chatHistory: ChatHistoryItem[]; |
| 243 | model: any; |
| 244 | llmApi: any; |
| 245 | controller: AbortController; |
| 246 | streamCallbacks: any; |
| 247 | currentCompactionIndex: number | null; |
| 248 | } |
| 249 | |
| 250 | /** |
| 251 | * Execute streaming chat response |
| 252 | */ |
| 253 | export async function executeStreaming({ |
| 254 | chatHistory, |
| 255 | model, |
| 256 | llmApi, |
| 257 | controller, |
| 258 | streamCallbacks, |
| 259 | currentCompactionIndex, |
| 260 | }: ExecuteStreamingOptions): Promise<void> { |
| 261 | const { getHistoryForLLM } = await import("../../compaction.js"); |
| 262 | const { streamChatResponse } = await import( |
| 263 | "../../stream/streamChatResponse.js" |
| 264 | ); |
| 265 | |
| 266 | if (model && llmApi) { |
| 267 | if ( |
| 268 | currentCompactionIndex !== null && |
| 269 | currentCompactionIndex !== undefined |
| 270 | ) { |
| 271 | const historyForLLM = getHistoryForLLM( |
| 272 | chatHistory, |
| 273 | currentCompactionIndex, |
| 274 | ); |
| 275 | |
| 276 | await streamChatResponse( |
| 277 | historyForLLM, |
| 278 | model, |
| 279 | llmApi, |
| 280 | controller, |
| 281 | streamCallbacks, |
| 282 | ); |
| 283 | |
| 284 | // Service-driven streaming; history updates occur via ChatHistoryService |
| 285 | } else { |
| 286 | await streamChatResponse( |
| 287 | chatHistory, |
| 288 | model, |
| 289 | llmApi, |
| 290 | controller, |
| 291 | streamCallbacks, |
| 292 | ); |
| 293 | } |
| 294 | } |
| 295 | } |