Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

7.9 KB
Raw Blame
import { getGroupMemberAnchorIndex } from '@lobechat/types';

import { buildHelperMaps } from './indexing';
import { buildIdTree } from './structuring';
import { Transformer } from './transformation';
import type { Message, MessageGroupMetadata, ParseOptions, ParseResult } from './types';

/**
 * Group-member anchors are server bookkeeping under a multi-member group tool
 * call. No assistant lists them in `tools[]`, so left in they surface as orphan
 * tool calls. The group tool's own render shows member progress from the raw rows.
 */
const withoutGroupMemberAnchors = (messages: Message[]): Message[] => {
  const roleById = new Map(messages.map((message) => [message.id, message.role]));
  const isAnchor = (message: Message) =>
    getGroupMemberAnchorIndex(
      message,
      message.parentId ? roleById.get(message.parentId) : undefined,
    ) !== undefined;

  return messages.some(isAnchor) ? messages.filter((message) => !isAnchor(message)) : messages;
};

/**
 * Main parse function - the brain of the conversation flow engine
 *
 * Converts a flat array of messages into:
 * 1. messageMap - for O(1) message access
 * 2. displayTree - semantic tree structure for navigation
 * 3. flatList - flattened array optimized for virtual list rendering
 *
 * Uses a three-phase parsing strategy:
 * 1. Indexing - build helper maps for efficient querying
 * 2. Structuring - convert flat data to tree structure
 * 3. Transformation - apply business logic to create semantic nodes and flat list
 *
 * @param messages - Flat array of messages from backend
 * @param messageGroups - Optional array of message group metadata for compare/manual grouping
 * @param options - `threadId` scopes the flat list to the main flow (`null`) or to one thread
 * @returns ParseResult containing messageMap, displayTree, and flatList
 */
export function parse(
  messages: Message[],
  messageGroups?: MessageGroupMetadata[],
  options?: ParseOptions,
): ParseResult {
  // Pre-processing: Transform sub_agent messages before building helper maps
  // This ensures FlatListBuilder and MessageCollector see the correct agentId
  // and won't merge messages from different agents into the same group
  // Only applies to scope: 'sub_agent' (agent-to-agent calls, not group orchestration)
  const processedMessages = withoutGroupMemberAnchors(messages).map((msg) => {
    if (msg.metadata?.scope === 'sub_agent' && msg.metadata?.subAgentId) {
      return { ...msg, agentId: msg.metadata.subAgentId };
    }
    return msg;
  });

  // Phase 1: Indexing
  // Build helper maps for O(1) access patterns
  const helperMaps = buildHelperMaps(processedMessages, messageGroups, options?.threadId);

  // Phase 2: Structuring
  // Convert flat parent-child relationships to tree structure
  // Separates main flow from threaded conversations
  const idTree = buildIdTree(helperMaps);

  // Phase 3: Transformation
  // Apply priority-based pattern matching to create semantic display nodes
  const transformer = new Transformer(helperMaps);
  const contextTree = transformer.transformAll(idTree);

  // Phase 3b: Generate flatList for virtual list rendering
  // Implements RFC priority-based pattern matching
  const flatList = transformer.flatten(processedMessages);

  // Convert messageMap from Map to plain object for serialization
  // Clean up metadata for assistant messages with tools
  const messageMapObj: Record<string, Message> = {};
  const usagePerformanceFields = new Set([
    'acceptedPredictionTokens',
    'cost',
    'duration',
    'inputAudioTokens',
    'inputCacheMissTokens',
    'inputCachedTokens',
    'inputCitationTokens',
    'inputImageTokens',
    'inputTextTokens',
    'inputVideoTokens',
    'inputToolTokens',
    'inputWriteCacheTokens',
    'latency',
    'outputAudioTokens',
    'outputImageTokens',
    'outputReasoningTokens',
    'outputTextTokens',
    // Nested canonical shape β€” executors write `metadata.usage` / `metadata.performance`
    // as objects; treat them as part of the usage/performance set alongside the legacy flat keys.
    'performance',
    'rejectedPredictionTokens',
    'totalInputTokens',
    'totalOutputTokens',
    'totalTokens',
    'tps',
    'ttft',
    'usage',
  ]);

  helperMaps.messageMap.forEach((message, id) => {
    let processedMessage = message;

    // Transform supervisor messages: convert role from 'assistant' to 'supervisor'
    // This enables UI to render supervisor messages differently from regular assistant messages
    // Note: context-engine has SupervisorRoleRestoreProcessor to restore role='assistant' before model API call
    if (message.role === 'assistant' && message.metadata?.isSupervisor) {
      processedMessage = { ...message, role: 'supervisor' as const };
    }

    // Note: sub_agent scope transformation is done in pre-processing phase (before buildHelperMaps)
    // No need to transform agentId here since it's already been transformed

    // For assistant messages with tools, clean metadata to keep only usage/performance fields
    if (
      processedMessage.role === 'assistant' &&
      processedMessage.tools &&
      processedMessage.tools.length > 0 &&
      processedMessage.metadata
    ) {
      const cleanedMetadata: Record<string, any> = {};
      Object.entries(processedMessage.metadata).forEach(([key, value]) => {
        if (usagePerformanceFields.has(key)) {
          cleanedMetadata[key] = value;
        }
      });
      messageMapObj[id] = {
        ...processedMessage,
        metadata: Object.keys(cleanedMetadata).length > 0 ? cleanedMetadata : undefined,
      };
    } else {
      messageMapObj[id] = processedMessage;
    }
  });

  // Transform supervisor messages in flatList
  // For non-grouped supervisor messages (e.g., supervisor summary without tools)
  // Note: sub_agent scope transformation is done in pre-processing phase (before buildHelperMaps)
  const processedFlatList = flatList.map((msg) => {
    let next = msg;

    // Transform supervisor messages
    if (next.role === 'assistant' && next.metadata?.isSupervisor) {
      next = { ...next, role: 'supervisor' as const };
    }

    // Promote `metadata.usage` (canonical storage) onto the top-level `usage`
    // field that UIChatMessage consumers (Extras token badge, tokenCounter,
    // etc.) read from. The DB layer stores token usage inside the metadata
    // JSONB column β€” executors on every path (Gateway, hetero-agent CLI) write
    // there β€” but no server-side transform lifts it out. Doing it here keeps
    // the promotion in one place, close to where display shapes are built,
    // and works for both desktop (local PGlite) and web (remote Postgres).
    if (!next.usage && next.metadata?.usage) {
      next = { ...next, usage: next.metadata.usage };
    }

    return next;
  });

  // Historical data can contain a taskCallback and a tool result as
  // sibling branches under the same assistant tool-use shell. Normal branch
  // resolution must keep choosing one conversational continuation, but hiding
  // the inactive callback also hides the only user-visible record that a task
  // finished. Recover only those callback cards into the render list; do not
  // pull their assistant descendants across branches (they may contradict the
  // active continuation).
  const visibleIds = new Set(processedFlatList.map((message) => message.id));
  const recoveredFlatList = [...processedFlatList];
  const hiddenTaskCallbacks = processedMessages
    .filter((message) => message.role === 'taskCallback' && !visibleIds.has(message.id))
    .toSorted((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());

  for (const callback of hiddenTaskCallbacks) {
    const callbackTime = new Date(callback.createdAt).getTime();
    const insertAt = recoveredFlatList.findIndex(
      (message) => new Date(message.createdAt).getTime() > callbackTime,
    );
    if (insertAt === -1) recoveredFlatList.push(callback);
    else recoveredFlatList.splice(insertAt, 0, callback);
  }

  return {
    contextTree,
    flatList: recoveredFlatList,
    messageMap: messageMapObj,
  };
}