(events: StreamEvent[])
| 157 | // -- Builder -- |
| 158 | |
| 159 | export function buildPartsFromEvents(events: StreamEvent[]): MessagePart[] { |
| 160 | const parts: MessagePart[] = []; |
| 161 | let suppressTextAfterPlayTool = false; |
| 162 | |
| 163 | /** Find the last tool part that is still "running". */ |
| 164 | function findRunningTool(): ToolExecution | undefined { |
| 165 | for (let i = parts.length - 1; i >= 0; i--) { |
| 166 | const p = parts[i]; |
| 167 | if (p.type === "tool" && p.execution.status === "running") return p.execution; |
| 168 | } |
| 169 | return undefined; |
| 170 | } |
| 171 | |
| 172 | function appendThinking(content: string): void { |
| 173 | const last = parts[parts.length - 1]; |
| 174 | if (last?.type === "thinking") { |
| 175 | last.content += content; |
| 176 | } else { |
| 177 | parts.push({ type: "thinking", content, streaming: false }); |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | for (const event of events) { |
| 182 | switch (event.type) { |
| 183 | case "thinking:start": { |
| 184 | parts.push({ type: "thinking", content: "", streaming: true }); |
| 185 | break; |
| 186 | } |
| 187 | |
| 188 | case "thinking:delta": { |
| 189 | // Append to last thinking part |
| 190 | const last = parts[parts.length - 1]; |
| 191 | if (last?.type === "thinking") { |
| 192 | last.content += event.text; |
| 193 | } |
| 194 | break; |
| 195 | } |
| 196 | |
| 197 | case "thinking:end": { |
| 198 | const last = parts[parts.length - 1]; |
| 199 | if (last?.type === "thinking") { |
| 200 | last.streaming = false; |
| 201 | } |
| 202 | break; |
| 203 | } |
| 204 | |
| 205 | case "draft:delta": { |
| 206 | if (suppressTextAfterPlayTool) { |
| 207 | if (event.text.trim()) appendThinking(event.text); |
| 208 | break; |
| 209 | } |
| 210 | // Append to last text part, or create a new one |
| 211 | const last = parts[parts.length - 1]; |
| 212 | if (last?.type === "text") { |
| 213 | last.content += event.text; |
| 214 | } else { |
| 215 | parts.push({ type: "text", content: event.text }); |
| 216 | } |
no test coverage detected