Create an SSE streaming Response that reads from a live bridge.
( bridge: ReturnType<typeof spawnBridge>, heartbeatTimer: NodeJS.Timeout, blobStore: Map<string, Uint8Array>, mcpTools: McpToolDefinition[], modelId: string, bridgeKey: string, convKey: string, )
| 1147 | |
| 1148 | /** Create an SSE streaming Response that reads from a live bridge. */ |
| 1149 | function createBridgeStreamResponse( |
| 1150 | bridge: ReturnType<typeof spawnBridge>, |
| 1151 | heartbeatTimer: NodeJS.Timeout, |
| 1152 | blobStore: Map<string, Uint8Array>, |
| 1153 | mcpTools: McpToolDefinition[], |
| 1154 | modelId: string, |
| 1155 | bridgeKey: string, |
| 1156 | convKey: string, |
| 1157 | ): Response { |
| 1158 | const completionId = `chatcmpl-${crypto.randomUUID().replace(/-/g, "").slice(0, 28)}`; |
| 1159 | const created = Math.floor(Date.now() / 1000); |
| 1160 | |
| 1161 | const stream = new ReadableStream({ |
| 1162 | start(controller) { |
| 1163 | const encoder = new TextEncoder(); |
| 1164 | let closed = false; |
| 1165 | const sendSSE = (data: object) => { |
| 1166 | if (closed) return; |
| 1167 | controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`)); |
| 1168 | }; |
| 1169 | const sendDone = () => { |
| 1170 | if (closed) return; |
| 1171 | controller.enqueue(encoder.encode("data: [DONE]\n\n")); |
| 1172 | }; |
| 1173 | const closeController = () => { |
| 1174 | if (closed) return; |
| 1175 | closed = true; |
| 1176 | controller.close(); |
| 1177 | }; |
| 1178 | |
| 1179 | const makeChunk = ( |
| 1180 | delta: Record<string, unknown>, |
| 1181 | finishReason: string | null = null, |
| 1182 | ) => ({ |
| 1183 | id: completionId, |
| 1184 | object: "chat.completion.chunk", |
| 1185 | created, |
| 1186 | model: modelId, |
| 1187 | choices: [{ index: 0, delta, finish_reason: finishReason }], |
| 1188 | }); |
| 1189 | |
| 1190 | const makeUsageChunk = () => { |
| 1191 | const { prompt_tokens, completion_tokens, total_tokens } = computeUsage(state); |
| 1192 | return { |
| 1193 | id: completionId, |
| 1194 | object: "chat.completion.chunk", |
| 1195 | created, |
| 1196 | model: modelId, |
| 1197 | choices: [], |
| 1198 | usage: { prompt_tokens, completion_tokens, total_tokens }, |
| 1199 | }; |
| 1200 | }; |
| 1201 | |
| 1202 | const state: StreamState = { |
| 1203 | toolCallIndex: 0, |
| 1204 | pendingExecs: [], |
| 1205 | outputTokens: 0, |
| 1206 | totalTokens: 0, |
no outgoing calls
no test coverage detected