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.

9.1 KB
Raw Blame
import type {
  MessageTransport,
  QueryMessagesInput,
  QueryMessagesOptions,
  RuntimeMessageRef,
  RuntimeToolMessage,
  UpdateToolMessageInput,
} from '@lobechat/agent-runtime';
import { omitToolWorkRegistration } from '@lobechat/agent-runtime';
import type {
  ChatMessagePluginError,
  CreateMessageParams,
  UIChatMessage,
  UpdateMessageParams,
} from '@lobechat/types';
import { ChatErrorType } from '@lobechat/types';
import { nanoid } from '@lobechat/utils';

import { type MessageBatchOperation, messageService } from '@/services/message';
import {
  mergeStoredToolPayloads,
  selectProjectedToolIds,
  type StoredToolPayload,
} from '@/services/message/hydrateProjectedTools';
import type { ChatStore } from '@/store/chat/store';

/** Client message adapter backed by the optimistic chat store. */
export class ClientMessageTransport implements MessageTransport {
  /** Stored tool payloads refilled for this run — see `withStoredToolPayloads`. */
  private readonly storedToolPayloads = new Map<string, StoredToolPayload>();

  constructor(
    private readonly get: () => ChatStore,
    private readonly messageKey: string,
    private readonly operationId: string,
  ) {}

  createAssistantMessage(params: CreateMessageParams): Promise<RuntimeMessageRef> {
    const operation = this.get().operations[this.operationId];
    if (!operation) throw new Error(`Operation not found: ${this.operationId}`);

    const { agentId, groupId, isSupervisor, scope, subAgentId, threadId, topicId } =
      operation.context;
    const effectiveAgentId = subAgentId && scope !== 'sub_agent' ? subAgentId : agentId;
    const metadata = {
      ...params.metadata,
      ...(isSupervisor && { isSupervisor: true }),
      ...(scope === 'sub_agent' && subAgentId && { scope, subAgentId }),
    };

    return this.createMessage({
      ...params,
      ...(effectiveAgentId && { agentId: effectiveAgentId }),
      ...(groupId && { groupId }),
      ...(Object.keys(metadata).length > 0 && { metadata }),
      ...(threadId && { threadId }),
      ...(topicId && { topicId }),
    });
  }

  createToolMessage(params: CreateMessageParams): Promise<RuntimeMessageRef> {
    return this.createToolMessageForOperation(params, this.operationId);
  }

  createToolMessageForOperation(
    params: CreateMessageParams,
    operationId: string,
  ): Promise<RuntimeMessageRef> {
    return this.createMessage(
      {
        ...params,
        ...(params.pluginIntervention && {
          pluginIntervention: { ...params.pluginIntervention, runtimeType: 'client' },
        }),
      },
      operationId,
    );
  }

  async deleteMessage(id: string): Promise<void> {
    await this.get().optimisticDeleteMessage(id, { operationId: this.operationId });
  }

  async findById(id: string): Promise<RuntimeMessageRef | undefined> {
    for (const message of this.getMessages()) {
      if (message.id === id) return message;

      const compressedMessage = message.compressedMessages?.find((item) => item.id === id);
      if (compressedMessage) return compressedMessage;
    }

    return undefined;
  }

  async getToolMessage(id: string): Promise<RuntimeToolMessage | undefined> {
    const messages = await this.withStoredToolPayloads(this.getMessages());
    const message = messages.find((message) => message.id === id && message.role === 'tool');
    if (message?.payloadOmitted && !this.storedToolPayloads.has(id)) {
      throw new Error(`Cannot restore tool result for ${id}`);
    }
    return message;
  }

  async query(
    _params?: QueryMessagesInput,
    _options?: QueryMessagesOptions,
  ): Promise<UIChatMessage[]> {
    return (await this.withStoredToolPayloads(this.getMessages())).map(omitToolWorkRegistration);
  }

  async update(id: string, params: Partial<UpdateMessageParams>): Promise<void> {
    const store = this.get();
    const optimisticContext = { operationId: this.operationId };

    store.internal_dispatchMessage(
      { id, type: 'updateMessage', value: params as Partial<UIChatMessage> },
      optimisticContext,
    );

    await this.persist([{ id, type: 'updateMessage', value: params }]);
  }

  async updatePluginState(id: string, state: Record<string, any>): Promise<void> {
    this.get().internal_dispatchMessage(
      { id, type: 'updateMessage', value: { pluginState: state } },
      { operationId: this.operationId },
    );

    await this.persist([{ id, type: 'updateToolMessage', value: { pluginState: state } }]);
  }

  async updateToolIntervention(id: string, intervention: Record<string, any>): Promise<void> {
    // `optimisticUpdateMessagePlugin` also mirrors the change onto the calling
    // assistant's `tools[]` entry, which is what the intervention card reads
    // once the conversation has been folded — updating only the tool row would
    // clear the state in the store while the card kept rendering.
    await this.get().optimisticUpdateMessagePlugin(id, { intervention } as any, {
      operationId: this.operationId,
    });
  }

  async updateToolMessage(id: string, params: UpdateToolMessageInput): Promise<void> {
    const store = this.get();
    const optimisticContext = { operationId: this.operationId };
    const pluginError = params.pluginError as ChatMessagePluginError | null | undefined;

    store.internal_dispatchMessage(
      {
        id,
        type: 'updateMessage',
        value: {
          content: params.content,
          metadata: params.metadata,
          pluginState: params.pluginState,
        },
      },
      optimisticContext,
    );

    if (pluginError !== undefined) {
      store.internal_dispatchMessage(
        { id, type: 'updateMessagePlugin', value: { error: pluginError } },
        optimisticContext,
      );
    }

    await this.persist([
      {
        id,
        type: 'updateToolMessage',
        value: { ...params, pluginError },
      },
    ]);
  }

  private async createMessage(
    params: CreateMessageParams,
    operationId = this.operationId,
  ): Promise<RuntimeMessageRef> {
    const store = this.get();
    const id = params.id ?? nanoid();
    const message = { ...params, id };
    const optimisticContext = { operationId };

    store.internal_dispatchMessage(
      { id, type: 'createMessage', value: { ...message } },
      optimisticContext,
      { creationOrigin: 'client' },
    );

    try {
      await this.persist([{ message, type: 'createMessage' }]);
    } catch (error) {
      const createError = new Error(`Failed to create ${params.role} message`, { cause: error });
      store.internal_dispatchMessage(
        {
          id,
          type: 'updateMessage',
          value: {
            error: {
              body: error,
              message: createError.message,
              type: ChatErrorType.CreateMessageError,
            },
          },
        },
        optimisticContext,
      );
      throw createError;
    }
    store.internal_confirmClientMessages([id]);

    return message;
  }

  async findToolMessageIdByToolCallId(
    toolCallId: string,
    parentMessageId: string,
  ): Promise<string | undefined> {
    // Deliberately the store, not the database: client rows are created
    // optimistically and may not have been persisted yet, so a DB read would
    // miss exactly the row this lookup exists to find.
    const match = this.getMessages().find(
      (message) =>
        message.role === 'tool' &&
        message.tool_call_id === toolCallId &&
        message.parentId === parentMessageId,
    );

    return match?.id;
  }

  private async persist(operations: MessageBatchOperation[]): Promise<void> {
    await messageService.batchMutateOrThrow(operations);
  }

  private getMessages(): UIChatMessage[] {
    return this.get().dbMessagesMap[this.messageKey] ?? [];
  }

  /**
   * Put the stored tool payloads back before this list becomes an LLM context.
   *
   * A browser-executed run reads its history from the same store the UI
   * renders, and that store can be holding a list fetched while the read path
   * was projecting tool payloads to view models (`payloadOmitted`) — Gateway
   * mode was on for this agent when the list was cached and has since been
   * turned off, or another surface seeded the bucket. Rendering is happy with
   * the view model; the model is not, and would silently lose the tool output
   * it is supposed to reason about.
   *
   * The fetched payloads are cached per operation: a run queries once per step,
   * the map is keyed by row id and so stays valid as the conversation grows. A
   * failed refill leaves the row projected — a degraded context still beats a
   * step that cannot run at all.
   */
  private async withStoredToolPayloads(messages: UIChatMessage[]): Promise<UIChatMessage[]> {
    const missing = selectProjectedToolIds(messages).filter(
      (id) => !this.storedToolPayloads.has(id),
    );

    if (missing.length > 0) {
      try {
        const fetched = await messageService.getToolResultPayloads(missing);
        for (const [id, payload] of Object.entries(fetched)) {
          this.storedToolPayloads.set(id, payload);
        }
      } catch (error) {
        console.error('[ClientMessageTransport] failed to restore tool payloads:', error);
      }
    }

    return mergeStoredToolPayloads(messages, Object.fromEntries(this.storedToolPayloads)).messages;
  }
}