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.

20.5 KB
Raw Blame
import { type AgentStreamEventType } from '@lobechat/agent-gateway-client';
import { type ChatToolPayload } from '@lobechat/types';
import { isRecord } from '@lobechat/utils/object';
import debug from 'debug';
import { type Redis } from 'ioredis';

import { getAgentRuntimeRedisClient } from './redis';
import { type PublishAgentRuntimeEndParams } from './types';

const log = debug('lobe-server:agent-runtime:stream-event-manager');
const timing = debug('lobe-server:agent-runtime:timing');

const extractReasonFromError = (error: any): string | undefined => {
  if (!error) return undefined;

  // ChatMessageError format: { body: { error: { message } }, message, type }
  if (error.body?.error?.message) return error.body.error.message;
  if (error.body?.message) return error.body.message;

  // ChatCompletionErrorPayload format: { error: { message }, errorType }
  if (error.error?.error?.message) return error.error.error.message;
  if (error.error?.message) return error.error.message;

  // Direct message (skip "[object Object]")
  if (error.message && error.message !== '[object Object]' && error.message !== 'error') {
    return error.message;
  }

  return error.type || error.errorType || undefined;
};

export const getDefaultReasonDetail = (finalState: any, reason?: string): string => {
  if (reason === 'error') {
    return extractReasonFromError(finalState?.error) || 'Agent runtime failed';
  }

  if (reason === 'interrupted') {
    return extractReasonFromError(finalState?.error) || 'Agent runtime interrupted';
  }

  return 'Agent runtime completed successfully';
};

/**
 * Drop reconstructible / heavy fields from an `AgentState` before
 * serializing it into a Redis stream event. `messages` is the size
 * driver β€” long topics with `compressedGroup` envelopes can push a
 * single `xadd` past Upstash's 10 MB request limit, manifesting on
 * the gateway as a misleading watchdog "Operation idle" timeout.
 *
 * The dropped fields are all reconstructible:
 *
 * - `messages` β€” canonical copy lives in the DB (UIChatMessage rows)
 *   and the runtime in-memory state; in-process consumers that need
 *   it (e.g. `execSubAgent.onComplete`) receive the full state
 *   via the local `HookContext` channel, not via the stream.
 * - `operationToolSet`, `toolManifestMap`, `toolSourceMap`, `tools`
 *   β€” operation-level snapshot; the four top-level names are the legacy
 *   mirrors of the slot, kept here for operations that still carry them.
 * - `world.expertise` β€” immutable operation-level snapshot retained in working
 *   state. The rest of `world` stays: the client renders from it.
 *
 * Mirrors the `done`-event strip in `OperationTraceRecorder.appendStep`;
 * keep the two lists in sync if either set changes.
 */
const stripStateForStream = <T extends Record<string, any>>(
  state: T | undefined,
): T | undefined => {
  if (!state) return state;
  const {
    expertise: _expertise,
    messages: _messages,
    operationToolSet: _operationToolSet,
    toolManifestMap: _toolManifestMap,
    toolSourceMap: _toolSourceMap,
    tools: _tools,
    world,
    ...rest
  } = state;
  // `world` had to be destructured to reach its expertise snapshot, so it must be
  // put back: everything else on it (agent, group, channel …) has to survive.
  if (!world || typeof world !== 'object') return rest as T;
  if (!('expertise' in world)) return { ...rest, world } as unknown as T;
  const { expertise: _worldExpertise, ...worldRest } = world as Record<string, unknown>;
  return { ...rest, world: worldRest } as unknown as T;
};

/**
 * Chokepoint helper applied inside every stream-event publish site.
 * Step completion events omit finalState unless the persisted run host opts in,
 * and step start events omit their `uiMessages` snapshot. For other events carrying a `finalState`, strip `expertise`, `messages`,
 * and the tool-set group off it (see `stripStateForStream` for the rationale).
 *
 * Centralizing the strip here means new callers β€” including direct
 * `publishStreamEvent` users (e.g. `RuntimeExecutors`, the per-step
 * publish in `AgentRuntimeService.executeStep`) β€” get the size
 * protection automatically, with no per-site bookkeeping.
 *
 * Returns the original reference when no stripping is needed so the
 * common path stays allocation-free.
 */
export const stripFinalStateInEventData = (data: unknown, eventType?: unknown): unknown => {
  if (!data || typeof data !== 'object') return data;
  const record = data as Record<string, unknown>;
  const state = record.finalState;
  const includeFinalState =
    isRecord(state) && isRecord(state.host) && state.host.includeFinalState === true;
  if (eventType === 'step_complete' && !includeFinalState) {
    const { finalState: _finalState, ...rest } = record;
    return rest;
  }
  // A step_start snapshot is the whole message list (megabytes on a long topic),
  // one per step. Clients take it from the gateway push, which publishes the
  // event before this strip; nothing reads it back from the stream (the SSE
  // route serves the CLI, which ignores it), so a stored copy per step only
  // grew the stream and every replay of it.
  if (eventType === 'step_start' && 'uiMessages' in record) {
    const { uiMessages: _uiMessages, ...rest } = record;
    return rest;
  }
  const finalState = record.finalState;
  if (!finalState || typeof finalState !== 'object') return data;
  return { ...record, finalState: stripStateForStream(finalState as Record<string, any>) };
};

/**
 * Server-side stream event shape. Wire-compatible with `AgentStreamEvent` in
 * `@lobechat/agent-gateway-client` (the type union is the single source of
 * truth) β€” heterogeneous CLI agents that ingest via `aiAgent.heteroIngest`
 * republish their events through this same manager unchanged.
 */
export interface StreamEvent {
  data: any;
  id?: string; // Redis Stream event ID
  operationId: string;
  stepIndex: number;
  timestamp: number;
  type: AgentStreamEventType;
}

export interface StreamHistoryPage {
  available: boolean;
  events: StreamEvent[];
  hasMore: boolean;
  nextCursor: string;
}

export interface StreamChunkData {
  chunkType:
    | 'text'
    | 'reasoning'
    | 'tools_calling'
    | 'image'
    | 'grounding'
    | 'base64_image'
    | 'content_part'
    | 'reasoning_part';
  content?: string;
  /** Multimodal content parts (text + images) */
  contentParts?: Array<{ text: string; type: 'text' } | { image: string; type: 'image' }>;
  /** Grounding/search data */
  grounding?: any;
  /** Image list for base64_image chunks */
  imageList?: any[];
  images?: any[];
  reasoning?: string;
  /** Multimodal reasoning parts (text + images) */
  reasoningParts?: Array<{ text: string; type: 'text' } | { image: string; type: 'image' }>;
  /** Relayed LLM attempt this chunk re-publishes; the executor client skips its own echo. */
  relayCallId?: string;
  toolsCalling?: ChatToolPayload[];
}

const STREAM_ID = /^(\d+)(?:-(\d+))?$/;

/**
 * Order two Redis stream ids (`<ms>-<seq>`): negative when `a` is older,
 * positive when newer, `NaN` when either is not a stream id (client-supplied
 * cursors are untrusted), so every `< 0` / `> 0` check fails closed.
 */
export const compareStreamIds = (a: string, b: string): number => {
  const ma = STREAM_ID.exec(a);
  const mb = STREAM_ID.exec(b);
  if (!ma || !mb) return Number.NaN;
  const ms = BigInt(ma[1]) - BigInt(mb[1]);
  if (ms !== 0n) return ms < 0n ? -1 : 1;
  const seq = BigInt(ma[2] ?? '0') - BigInt(mb[2] ?? '0');
  return seq === 0n ? 0 : seq < 0n ? -1 : 1;
};

/** Decode one Redis stream entry (`[id, [field, value, ...]]`) into a `StreamEvent`. */
const parseStreamEntry = (id: string, fields: string[]): StreamEvent => {
  const eventData: any = {};
  for (let i = 0; i < fields.length; i += 2) {
    const key = fields[i];
    const value = fields[i + 1];
    if (key === 'data') {
      eventData[key] = JSON.parse(value);
    } else if (key === 'stepIndex' || key === 'timestamp') {
      eventData[key] = parseInt(value);
    } else {
      eventData[key] = value;
    }
  }
  return { ...eventData, id } as StreamEvent;
};

export class StreamEventManager {
  private redis: Redis;
  private readonly STREAM_PREFIX = 'agent_runtime_stream';
  private readonly STREAM_RETENTION = 2 * 3600; // 2 hours

  constructor() {
    const redisClient = getAgentRuntimeRedisClient();
    if (!redisClient) {
      throw new Error('Redis is not available. Please configure REDIS_URL environment variable.');
    }
    this.redis = redisClient;
  }

  /**
   * Run blocking reads on a short-lived duplicated connection. ioredis
   * executes commands on one connection strictly in order, so an
   * `XREAD BLOCK` issued on the shared client parks the connection for up to
   * the block timeout and every concurrent command (XADD / EXPIRE, plus any
   * other module sharing the client) queues behind it β€” with an SSE
   * subscriber attached, each publish paid up to ~1s, serializing streaming
   * into a chunk-per-second drip.
   *
   * The connection is scoped to the read rather than the instance: managers
   * are constructed per request (`createStreamEventManager()`) and most
   * callers never `disconnect()`, so an instance-held duplicate would leak a
   * socket per request. Scoping also lets concurrent blocking readers block
   * independently instead of queueing on one shared blocking connection.
   */
  private async withBlockingConnection<T>(fn: (conn: Redis) => Promise<T>): Promise<T> {
    const conn = this.redis.duplicate();
    try {
      return await fn(conn);
    } finally {
      conn.disconnect();
    }
  }

  /**
   * Publish stream event to Redis Stream
   */
  async publishStreamEvent(
    operationId: string,
    event: Omit<StreamEvent, 'operationId' | 'timestamp'>,
  ): Promise<string> {
    const streamKey = `${this.STREAM_PREFIX}:${operationId}`;

    const eventData: StreamEvent = {
      ...event,
      // Chokepoint strip β€” every event passing through here gets its
      // `data.finalState` removed for step_complete, otherwise trimmed, before
      // serialization so a single xadd can't blow past Upstash's 10 MB
      // request limit on long topics.
      data: stripFinalStateInEventData(event.data, event.type),
      operationId,
      timestamp: Date.now(),
    };

    try {
      const xaddStart = Date.now();
      const eventId = await this.redis.xadd(
        streamKey,
        // Retain every event until the stream's inactivity TTL expires.
        // Count trimming makes a reconnect silently lose earlier output.
        '*', // Auto-generate ID
        'type',
        eventData.type,
        'stepIndex',
        eventData.stepIndex.toString(),
        'operationId',
        eventData.operationId,
        'data',
        JSON.stringify(eventData.data),
        'timestamp',
        eventData.timestamp.toString(),
      );
      const xaddEnd = Date.now();

      // Set expiration time
      await this.redis.expire(streamKey, this.STREAM_RETENTION);

      log(
        'Published event %s for operation %s:%d',
        eventData.type,
        operationId,
        eventData.stepIndex,
      );

      timing(
        '[%s:%d] Redis XADD %s at %d, took %dms',
        operationId,
        eventData.stepIndex,
        eventData.type,
        xaddStart,
        xaddEnd - xaddStart,
      );

      return eventId as string;
    } catch (error) {
      console.error('[StreamEventManager] Failed to publish stream event:', error);
      throw error;
    }
  }

  async deleteStreamEvents(operationId: string, eventIds: string[]): Promise<void> {
    if (eventIds.length === 0) return;
    await this.redis.xdel(`${this.STREAM_PREFIX}:${operationId}`, ...eventIds);
  }

  /**
   * Publish stream content chunk
   */
  async publishStreamChunk(
    operationId: string,
    stepIndex: number,
    chunkData: StreamChunkData,
  ): Promise<string> {
    return this.publishStreamEvent(operationId, {
      data: chunkData,
      stepIndex,
      type: 'stream_chunk',
    });
  }

  /**
   * Publish Agent runtime initialization event
   */
  async publishAgentRuntimeInit(operationId: string, initialState: any): Promise<string> {
    return this.publishStreamEvent(operationId, {
      data: initialState,
      stepIndex: 0,
      type: 'agent_runtime_init',
    });
  }

  /**
   * Publish Agent runtime end event
   */
  async publishAgentRuntimeEnd({
    operationId,
    stepIndex,
    finalState,
    messagePatchMode,
    messageRevision,
    reason,
    reasonDetail,
    uiMessages,
  }: PublishAgentRuntimeEndParams): Promise<string> {
    // `finalState.messages` + tool-set fields are stripped centrally
    // inside `publishStreamEvent`; callers stay dumb. `reasonDetail`
    // derivation below uses the un-stripped in-process `finalState`
    // so the error message remains available.
    return this.publishStreamEvent(operationId, {
      data: {
        ...(!messagePatchMode && { finalState }),
        ...(messagePatchMode && { messagePatchMode: true, messageRevision }),
        operationId,
        phase: 'execution_complete',
        reason: reason || 'completed',
        reasonDetail: reasonDetail || getDefaultReasonDetail(finalState, reason),
        ...(uiMessages !== undefined && { uiMessages }),
      },
      stepIndex,
      type: 'agent_runtime_end',
    });
  }

  /**
   * Subscribe to stream events (for WebSocket/SSE)
   */
  async subscribeStreamEvents(
    operationId: string,
    lastEventId: string = '0',
    onEvents: (events: StreamEvent[]) => void,
    signal?: AbortSignal,
  ): Promise<void> {
    const streamKey = `${this.STREAM_PREFIX}:${operationId}`;
    let currentLastId = lastEventId;

    log('Starting subscription for operation %s from %s', operationId, lastEventId);

    // One dedicated connection for the whole subscription loop.
    await this.withBlockingConnection(async (conn) => {
      while (!signal?.aborted) {
        try {
          const xreadStart = Date.now();
          const results = await conn.xread(
            'BLOCK',
            1000, // 1 second timeout
            'STREAMS',
            streamKey,
            currentLastId,
          );
          const xreadEnd = Date.now();

          if (results && results.length > 0) {
            const [, messages] = results[0];
            const events: StreamEvent[] = [];

            for (const [id, fields] of messages) {
              events.push(parseStreamEntry(id, fields));

              currentLastId = id;
            }

            if (events.length > 0) {
              const now = Date.now();
              // Calculate latency from event publication to read
              for (const event of events) {
                const latency = now - event.timestamp;
                timing(
                  '[%s:%d] XREAD %s, published at %d, read at %d, latency %dms, xread took %dms',
                  operationId,
                  event.stepIndex,
                  event.type,
                  event.timestamp,
                  now,
                  latency,
                  xreadEnd - xreadStart,
                );
              }
              onEvents(events);
            }
          }
        } catch (error) {
          if (signal?.aborted) {
            break;
          }

          console.error('[StreamEventManager] Stream subscription error:', error);
          // Retry after brief delay
          await new Promise((resolve) => {
            setTimeout(resolve, 1000);
          });
        }
      }
    });

    log('Subscription ended for operation %s', operationId);
  }

  /**
   * Single bounded read β€” the long-poll primitive (see `IStreamEventManager`).
   * One `XREAD BLOCK`, no loop: returns events after `lastEventId` (blocking up
   * to `blockMs` for the first), or an empty list on timeout. The returned
   * `lastEventId` is always a CONCRETE stream id, never the `'$'` sentinel β€” the
   * caller threads it into its next call to stay gap-free.
   *
   * `lastEventId` defaults to `'$'` (only events published after this call
   * lands) so a fresh poll doesn't replay history. We resolve `'$'` to the
   * stream's current tail id BEFORE blocking, because Redis re-evaluates `'$'`
   * as "the tail at read time" on every `XREAD`: returning `'$'` unchanged on a
   * timeout would re-anchor the next poll to whatever the tail is by then,
   * silently skipping any event published in the gap between this call resolving
   * and the next one being issued. Pinning a concrete id (the last entry now, or
   * `'0'` on an empty/absent stream) closes that gap.
   */
  async readEventsOnce(
    operationId: string,
    lastEventId: string = '$',
    blockMs: number = 25_000,
  ): Promise<{ events: StreamEvent[]; lastEventId: string }> {
    const streamKey = `${this.STREAM_PREFIX}:${operationId}`;

    // Resolve the '$' sentinel to a concrete tail id up front (see doc above).
    // A timeout on a blocking XREAD means nothing was appended after this id, so
    // it is still the true tail β€” safe to hand back for the next poll.
    let fromId = lastEventId;
    if (fromId === '$') {
      const tail = await this.redis.xrevrange(streamKey, '+', '-', 'COUNT', 1);
      fromId = tail.length > 0 ? tail[0][0] : '0';
    }

    const results = await this.withBlockingConnection((conn) =>
      conn.xread('BLOCK', blockMs, 'STREAMS', streamKey, fromId),
    );
    if (!results || results.length === 0) return { events: [], lastEventId: fromId };

    const [, messages] = results[0];
    const events: StreamEvent[] = [];
    let currentLastId = fromId;

    for (const [id, fields] of messages) {
      events.push(parseStreamEntry(id, fields));
      currentLastId = id;
    }

    return { events, lastEventId: currentLastId };
  }

  /**
   * Get stream event history
   */
  async getStreamHistory(operationId: string, count: number = 100): Promise<StreamEvent[]> {
    const streamKey = `${this.STREAM_PREFIX}:${operationId}`;

    try {
      const results = await this.redis.xrevrange(streamKey, '+', '-', 'COUNT', count);

      return results.map(([id, fields]) => parseStreamEntry(id, fields));
    } catch (error) {
      console.error('[StreamEventManager] Failed to get stream history:', error);
      return [];
    }
  }

  /** Forward, exclusive-cursor replay; never substitute a truncated suffix for full history. */
  async getStreamHistoryPage(
    operationId: string,
    cursor = '0',
    limit = 200,
  ): Promise<StreamHistoryPage> {
    const key = `${this.STREAM_PREFIX}:${operationId}`;
    const unavailable = { available: false, events: [], hasMore: false, nextCursor: cursor };
    let cursorRemoved = false;
    if (cursor !== '0') {
      const previous = await this.redis.xrange(key, cursor, cursor, 'COUNT', 1);
      if (previous.length === 0) {
        // A missing cursor is either lost history (expired stream, legacy
        // trimmed prefix) or a superseded snapshot removed by
        // `deleteStreamEvents`. Removal only happens mid-stream: the stream
        // still starts at its init and a newer entry follows the cursor.
        const [first] = await this.redis.xrange(key, '-', '+', 'COUNT', 1);
        const anchored =
          !!first &&
          parseStreamEntry(first[0], first[1]).type === 'agent_runtime_init' &&
          compareStreamIds(first[0], cursor) < 0;
        if (!anchored) return unavailable;
        cursorRemoved = true;
      }
    }
    const rows = await this.redis.xrange(
      key,
      cursor === '0' ? '-' : `(${cursor}`,
      '+',
      'COUNT',
      limit + 1,
    );
    if (cursorRemoved && rows.length === 0) return unavailable;
    const events = rows.slice(0, limit).map(([id, fields]) => parseStreamEntry(id, fields));
    // Legacy streams may already have been trimmed before this deployment.
    if (cursor === '0' && events[0]?.type !== 'agent_runtime_init') return unavailable;
    return {
      available: true,
      events,
      hasMore: rows.length > limit,
      nextCursor: events.at(-1)?.id ?? cursor,
    };
  }

  /**
   * Clean up stream data for operation
   */
  async cleanupOperation(operationId: string): Promise<void> {
    const streamKey = `${this.STREAM_PREFIX}:${operationId}`;

    try {
      await this.redis.del(streamKey);
      log('Cleaned up operation %s', operationId);
    } catch (error) {
      console.error('[StreamEventManager] Failed to cleanup operation:', error);
    }
  }

  /**
   * Get count of active operations
   */
  async getActiveOperationsCount(): Promise<number> {
    try {
      const pattern = `${this.STREAM_PREFIX}:*`;
      const keys = await this.redis.keys(pattern);
      return keys.length;
    } catch (error) {
      console.error('[StreamEventManager] Failed to get active operations count:', error);
      return 0;
    }
  }

  /**
   * Close Redis connection
   */
  async disconnect(): Promise<void> {
    await this.redis.quit();
  }
}