| 1 | import type { |
| 2 | ChatHistoryItem, |
| 3 | Session, |
| 4 | ToolCallState, |
| 5 | ToolStatus, |
| 6 | } from "core/index.js"; |
| 7 | |
| 8 | import { streamChatResponse } from "../stream/streamChatResponse.js"; |
| 9 | import { StreamCallbacks } from "../stream/streamChatResponse.types.js"; |
| 10 | |
| 11 | // Modified version of streamChatResponse that supports interruption |
| 12 | export async function streamChatResponseWithInterruption( |
| 13 | state: ServerState, |
| 14 | llmApi: any, |
| 15 | abortController: AbortController, |
| 16 | shouldInterrupt: () => boolean, |
| 17 | ): Promise<string> { |
| 18 | // Import the original streamChatResponse logic but add interruption checks |
| 19 | // Create a wrapper that checks for interruption |
| 20 | const originalSignal = abortController.signal; |
| 21 | const checkInterruption = () => { |
| 22 | if (shouldInterrupt() && !originalSignal.aborted) { |
| 23 | abortController.abort(); |
| 24 | } |
| 25 | }; |
| 26 | |
| 27 | // Set up periodic interruption checks |
| 28 | const interruptionChecker = setInterval(checkInterruption, 100); |
| 29 | |
| 30 | let currentStreamingItem: ChatHistoryItem | null = null; |
| 31 | |
| 32 | // Create callbacks to capture tool events |
| 33 | const callbacks: StreamCallbacks = { |
| 34 | onContent: (content: string) => { |
| 35 | if (!currentStreamingItem) { |
| 36 | currentStreamingItem = { |
| 37 | message: { role: "assistant", content: "" }, |
| 38 | contextItems: [], |
| 39 | }; |
| 40 | state.session.history.push(currentStreamingItem); |
| 41 | } |
| 42 | currentStreamingItem.message.content = |
| 43 | (currentStreamingItem.message.content as string) + content; |
| 44 | }, |
| 45 | onContentComplete: (content: string) => { |
| 46 | if (currentStreamingItem) { |
| 47 | currentStreamingItem.message.content = content; |
| 48 | currentStreamingItem = null; |
| 49 | } else { |
| 50 | // Add complete assistant message |
| 51 | state.session.history.push({ |
| 52 | message: { role: "assistant", content: content }, |
| 53 | contextItems: [], |
| 54 | }); |
| 55 | } |
| 56 | }, |
| 57 | onToolStart: (toolName: string, toolArgs?: any) => { |
| 58 | // If there was streaming content, finalize it first |
| 59 | if (currentStreamingItem && currentStreamingItem.message.content) { |
| 60 | currentStreamingItem = null; |
| 61 | } |
| 62 | |
| 63 | // Always create a new assistant message for each tool call |
| 64 | const toolCallId = `tool_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`; |
| 65 | const toolCallState: ToolCallState = { |
| 66 | toolCallId: toolCallId, |
| 67 | toolCall: { |
| 68 | id: toolCallId, |
| 69 | type: "function", |
| 70 | function: { |
| 71 | name: toolName, |
| 72 | arguments: JSON.stringify(toolArgs || {}), |
| 73 | }, |
| 74 | }, |
| 75 | status: "calling", |
| 76 | parsedArgs: toolArgs, |
| 77 | }; |
| 78 | |
| 79 | state.session.history.push({ |
| 80 | message: { role: "assistant", content: "" }, |
| 81 | contextItems: [], |
| 82 | toolCallStates: [toolCallState], |
| 83 | }); |
| 84 | }, |
| 85 | onToolResult: (result: string, toolName: string, status: ToolStatus) => { |
| 86 | // Find and update the corresponding tool call state |
| 87 | for (let i = state.session.history.length - 1; i >= 0; i--) { |
| 88 | const item = state.session.history[i]; |
| 89 | if (item.toolCallStates) { |
| 90 | const toolState = item.toolCallStates.find( |
| 91 | (ts: ToolCallState) => |
| 92 | ts.toolCall.function.name === toolName && ts.status === "calling", |
| 93 | ); |
| 94 | if (toolState) { |
| 95 | toolState.status = status; |
| 96 | toolState.output = [ |
| 97 | { |
| 98 | content: result, |
| 99 | name: `Tool Result: ${toolName}`, |
| 100 | description: "Tool execution result", |
| 101 | }, |
| 102 | ]; |
| 103 | return; |
| 104 | } |
| 105 | } |
| 106 | } |
| 107 | }, |
| 108 | onToolError: (error: string, toolName?: string) => { |
| 109 | if (toolName) { |
| 110 | // Find and update the corresponding tool call state |
| 111 | for (let i = state.session.history.length - 1; i >= 0; i--) { |
| 112 | const item = state.session.history[i]; |
| 113 | if (item.toolCallStates) { |
| 114 | const toolState = item.toolCallStates.find( |
| 115 | (ts: ToolCallState) => |
| 116 | ts.toolCall.function.name === toolName && |
| 117 | ts.status === "calling", |
| 118 | ); |
| 119 | if (toolState) { |
| 120 | toolState.status = "errored"; |
| 121 | toolState.output = [ |
| 122 | { |
| 123 | content: error, |
| 124 | name: `Tool Error: ${toolName}`, |
| 125 | description: "Tool execution error", |
| 126 | }, |
| 127 | ]; |
| 128 | return; |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | // Generic error if tool not found |
| 134 | state.session.history.push({ |
| 135 | message: { role: "system", content: error }, |
| 136 | contextItems: [], |
| 137 | }); |
| 138 | }, |
| 139 | onToolPermissionRequest: ( |
| 140 | toolName: string, |
| 141 | toolArgs: any, |
| 142 | requestId: string, |
| 143 | ) => { |
| 144 | // Set pending permission state |
| 145 | state.pendingPermission = { |
| 146 | toolName, |
| 147 | toolArgs, |
| 148 | requestId, |
| 149 | timestamp: Date.now(), |
| 150 | }; |
| 151 | |
| 152 | // Add a system message indicating permission is needed |
| 153 | state.session.history.push({ |
| 154 | message: { |
| 155 | role: "system", |
| 156 | content: `WARNING: Tool ${toolName} requires permission`, |
| 157 | }, |
| 158 | contextItems: [], |
| 159 | }); |
| 160 | |
| 161 | // Don't wait here - the streamChatResponse will handle waiting |
| 162 | }, |
| 163 | }; |
| 164 | |
| 165 | try { |
| 166 | const response = await streamChatResponse( |
| 167 | state.session.history, |
| 168 | state.model, |
| 169 | llmApi, |
| 170 | abortController, |
| 171 | callbacks, |
| 172 | ); |
| 173 | return response || ""; |
| 174 | } finally { |
| 175 | clearInterval(interruptionChecker); |
| 176 | // Ensure any streaming message is finalized |
| 177 | if (currentStreamingItem !== null) { |
| 178 | currentStreamingItem = null; |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | export interface PendingPermission { |
| 184 | toolName: string; |
| 185 | toolArgs: any; |
| 186 | requestId: string; |
| 187 | timestamp: number; |
| 188 | } |
| 189 | |
| 190 | export interface ServerState { |
| 191 | session: Session; |
| 192 | config: any; |
| 193 | model: any; |
| 194 | isProcessing: boolean; |
| 195 | lastActivity: number; |
| 196 | messageQueue: string[]; |
| 197 | currentAbortController: AbortController | null; |
| 198 | shouldInterrupt: boolean; |
| 199 | serverRunning: boolean; |
| 200 | pendingPermission: PendingPermission | null; |
| 201 | systemMessage?: string; |
| 202 | } |