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.

5.4 KB
Raw Blame
import debug from 'debug';

import { appEnv } from '@/envs/app';

import { AgentStateManager } from './AgentStateManager';
import { GatewayStreamNotifier, type GatewayStreamNotifierOptions } from './GatewayStreamNotifier';
import { inMemoryAgentStateManager } from './InMemoryAgentStateManager';
import { inMemoryStreamEventManager } from './InMemoryStreamEventManager';
import { getAgentRuntimeRedisClient } from './redis';
import { StreamEventManager } from './StreamEventManager';
import { type IAgentStateManager, type IStreamEventManager } from './types';

const log = debug('lobe-server:agent-runtime:factory');

/**
 * Check if Redis is available for Agent Runtime
 */
export const isRedisAvailable = (): boolean => {
  return getAgentRuntimeRedisClient() !== null;
};

/**
 * Check if queue-based agent runtime is enabled
 * Controls execution scheduling independently of the state/stream storage backend
 */
const isQueueModeEnabled = (): boolean => {
  return appEnv.enableQueueAgentRuntime === true;
};

/**
 * Create AgentStateManager based on configuration
 */
export const createAgentStateManager = (): IAgentStateManager => {
  // Share state and interrupt sentinels across web/worker replicas even when
  // execution stays inline. Storage selection must match the shared stream bus.
  if (isRedisAvailable()) {
    log('Redis available, using AgentStateManager');
    return new AgentStateManager();
  }

  if (!isQueueModeEnabled()) {
    log('Redis unavailable and queue mode disabled, using InMemoryAgentStateManager');
    return inMemoryAgentStateManager;
  }

  throw new Error('Redis is required when AGENT_RUNTIME_MODE=queue. Please configure `REDIS_URL`.');
};

/**
 * Create StreamEventManager based on configuration
 *
 * - If Redis is available: RedisStreamEventManager
 * - If Redis is unavailable and enableQueueAgentRuntime=false (default): InMemoryStreamEventManager
 * - If Redis is unavailable and enableQueueAgentRuntime=true: throw
 *
 * Pass `inner` to supply the manager yourself — the gateway notifier still wraps
 * it, so the gateway keeps seeing the events while the caller keeps whatever
 * delivery it chose (see `CreateStreamEventManagerOptions.inner`).
 */
export interface CreateStreamEventManagerOptions extends GatewayStreamNotifierOptions {
  /**
   * The manager events are published to and read back from, instead of the
   * config-driven default. For a caller that owns a per-invocation subscription:
   * the streaming Responses route consumes the run's events from the same
   * process that produces them, so it passes a private in-memory manager rather
   * than taking a second Redis subscriber's connection per request — while the
   * wrapping notifier still carries every event to the gateway.
   */
  inner?: IStreamEventManager;
}

const createDefaultStreamEventManager = (): IStreamEventManager => {
  // Prefer Redis whenever it is available so the runtime worker and SSE route
  // can communicate through the same stream bus even in local mode.
  if (isRedisAvailable()) {
    log('Redis available, using StreamEventManager');
    return new StreamEventManager();
  }

  if (!isQueueModeEnabled()) {
    log('Redis unavailable and queue mode disabled, using InMemoryStreamEventManager');
    return inMemoryStreamEventManager;
  }

  throw new Error('Redis is required when AGENT_RUNTIME_MODE=queue. Please configure `REDIS_URL`.');
};

export const createStreamEventManager = (
  options?: CreateStreamEventManagerOptions,
): IStreamEventManager => {
  const { inner, ...notifierOptions } = options ?? {};
  const manager = inner ?? createDefaultStreamEventManager();

  // Wrap with Gateway notifier when configured. Server pushes prefer the internal
  // URL: the public one is what browsers open, which a container may not reach.
  const gatewayUrl = appEnv.AGENT_GATEWAY_INTERNAL_URL || appEnv.AGENT_GATEWAY_URL;
  if (gatewayUrl && appEnv.AGENT_GATEWAY_SERVICE_TOKEN) {
    log('Wrapping with GatewayStreamNotifier (%s)', gatewayUrl);
    // Resolver lets a queue worker (which never ran the member op's init) mirror
    // its stream events onto the supervisor channel by reading the persisted
    // `mirrorToOperationId` from op metadata. Shares the same state manager
    // backing the runtime (Redis when configured, otherwise the in-memory singleton).
    const stateManager = createAgentStateManager();
    return new GatewayStreamNotifier(
      manager,
      gatewayUrl,
      appEnv.AGENT_GATEWAY_SERVICE_TOKEN,
      async (operationId) => {
        const meta = await stateManager.getOperationMetadata(operationId);
        return meta?.mirrorToOperationId ?? undefined;
      },
      // Same reasoning as the mirror resolver above, but for share-visitor
      // detection: a queue worker that never ran `publishAgentRuntimeInit` for
      // this op still needs to know whether its events must be scrubbed of the
      // creator's identity.
      async (operationId) => {
        const meta = await stateManager.getOperationMetadata(operationId);
        return !!meta?.streamOwnerUserId;
      },
      {
        ...notifierOptions,
        // Same again for the supervisor's `member_runtime_end` declaration: the
        // worker mirroring a member's terminal may never have seen its init.
        resolveAcceptsMemberRuntimeEnd: async (operationId) => {
          const meta = await stateManager.getOperationMetadata(operationId);
          return meta?.acceptsMemberRuntimeEnd === true;
        },
      },
    );
  }

  return manager;
};