| 600 | } |
| 601 | |
| 602 | export function normalizeMessage(raw: Record<string, unknown>): PersistedMessage { |
| 603 | const msg: PersistedMessage = { |
| 604 | id: (raw.id as string) ?? generateId(), |
| 605 | role: (raw.role as 'user' | 'assistant') ?? 'assistant', |
| 606 | content: (raw.content as string) ?? '', |
| 607 | timestamp: (raw.timestamp as string) ?? new Date().toISOString(), |
| 608 | } |
| 609 | |
| 610 | if (raw.requestId && typeof raw.requestId === 'string') { |
| 611 | msg.requestId = raw.requestId |
| 612 | } |
| 613 | |
| 614 | const rawBlocks = raw.contentBlocks as RawBlock[] | undefined |
| 615 | const rawToolCalls = raw.toolCalls as LegacyToolCall[] | undefined |
| 616 | const hasBlocks = Array.isArray(rawBlocks) && rawBlocks.length > 0 |
| 617 | const hasToolCalls = Array.isArray(rawToolCalls) && rawToolCalls.length > 0 |
| 618 | |
| 619 | if (hasBlocks) { |
| 620 | msg.contentBlocks = normalizeBlocks(rawBlocks!, msg.content) |
| 621 | const contentBlocksAlreadyContainTools = blocksContainTools(rawBlocks!) |
| 622 | if (hasToolCalls && !contentBlocksAlreadyContainTools) { |
| 623 | msg.contentBlocks.push(...rawToolCalls!.map(normalizeLegacyToolCall)) |
| 624 | } |
| 625 | } else if (hasToolCalls) { |
| 626 | msg.contentBlocks = rawToolCalls!.map(normalizeLegacyToolCall) |
| 627 | if (msg.content.trim()) { |
| 628 | msg.contentBlocks.push({ |
| 629 | type: MothershipStreamV1EventType.text, |
| 630 | channel: MothershipStreamV1TextChannel.assistant, |
| 631 | content: msg.content, |
| 632 | }) |
| 633 | } |
| 634 | } |
| 635 | |
| 636 | const rawAttachments = raw.fileAttachments as PersistedFileAttachment[] | undefined |
| 637 | if (Array.isArray(rawAttachments) && rawAttachments.length > 0) { |
| 638 | msg.fileAttachments = rawAttachments |
| 639 | } |
| 640 | |
| 641 | const rawContexts = raw.contexts as PersistedMessageContext[] | undefined |
| 642 | if (Array.isArray(rawContexts) && rawContexts.length > 0) { |
| 643 | msg.contexts = rawContexts.map((c) => ({ |
| 644 | kind: c.kind, |
| 645 | label: c.label, |
| 646 | ...(c.workflowId ? { workflowId: c.workflowId } : {}), |
| 647 | ...(c.knowledgeId ? { knowledgeId: c.knowledgeId } : {}), |
| 648 | ...(c.tableId ? { tableId: c.tableId } : {}), |
| 649 | ...(c.fileId ? { fileId: c.fileId } : {}), |
| 650 | ...(c.folderId ? { folderId: c.folderId } : {}), |
| 651 | ...(c.chatId ? { chatId: c.chatId } : {}), |
| 652 | })) |
| 653 | } |
| 654 | |
| 655 | return msg |
| 656 | } |