| 858 | } |
| 859 | |
| 860 | async function chunksToMessages(chunks: UIMessageChunk[]): Promise<UIMessage[]> { |
| 861 | if (!chunks.length) { |
| 862 | return []; |
| 863 | } |
| 864 | const stream = simulateReadableStream<UIMessageChunk>({ chunks }); |
| 865 | const iterator = readUIMessageStream({ stream }); |
| 866 | const snapshots: UIMessage[] = []; |
| 867 | for await (const message of iterator) { |
| 868 | snapshots.push(message); |
| 869 | } |
| 870 | const latestById = new Map<string, UIMessage>(); |
| 871 | const orderedIds: string[] = []; |
| 872 | for (const snapshot of snapshots) { |
| 873 | const key = snapshot.id ?? `message-${orderedIds.length}`; |
| 874 | if (!latestById.has(key)) { |
| 875 | orderedIds.push(key); |
| 876 | } |
| 877 | latestById.set(key, snapshot); |
| 878 | } |
| 879 | return orderedIds |
| 880 | .map((id) => latestById.get(id)) |
| 881 | .filter((message): message is UIMessage => Boolean(message)); |
| 882 | } |
| 883 | |
| 884 | function deriveAgentSteps(parts: AgentTraceChunk[]): AgentDerivedStep[] { |
| 885 | if (!parts.length) { |