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.0 KB
Raw Blame
import type {
  ConversationContext,
  HeterogeneousProviderConfig,
  UIChatMessage,
} from '@lobechat/types';

import type { ChatStore } from '@/store/chat/store';

import {
  type AgentInvocationIntent,
  type AgentRuntimeType,
  selectRuntimeType,
} from './agentDispatcher';

/**
 * Execution context supplied by the caller at dispatch time.
 * Carries the runtime-selection inputs and client-mode extras that the
 * dispatcher needs but that do not belong in the intent itself.
 */
export interface NonHeteroSubAgentDispatchContext {
  /** Device bound by the parent agent execution switcher. */
  boundDeviceId?: string;
  /** Conversation context of the *parent* agent (agentId = parent agent). */
  conversationContext: ConversationContext;
  /** Per-agent heterogeneous provider config used for runtime resolution. */
  heterogeneousProvider?: HeterogeneousProviderConfig;
  /**
   * Whether the sub-agent runs inside a portal thread.
   * Client mode only β€” has no effect in gateway mode.
   */
  inPortalThread?: boolean;
  /** Current gateway mode status (`chatStore.isGatewayModeEnabled()`). */
  isGatewayMode: boolean;
  /**
   * Messages passed to the client-side runner.
   * Typically the current conversation messages plus a virtual instruction
   * message prepended by the caller. Only consumed when runtime = 'client'.
   */
  messages?: UIChatMessage[];
  /**
   * Parent operation ID to link the sub-agent operation as a child.
   * Optional β€” only provided when the caller has an active operation to chain.
   */
  parentOperationId?: string;
  /**
   * Explicit runtime inherited from the parent operation.
   * When set, `selectRuntimeType` returns this value immediately, preserving
   * the parent's execution environment for the child invocation.
   */
  parentRuntime?: AgentRuntimeType;
  /** Parent agent's shared-row coercion flag β€” see `RuntimeSelectionContext.workspaceScoped`. */
  workspaceScoped?: boolean;
}

/**
 * Unified dispatcher for non-hetero, non-group sub-agent invocations ().
 *
 * Resolves the child runtime by inheriting from the parent (via
 * `selectRuntimeType` with `parentRuntime`), then routes to the correct
 * executor. Replaces the per-entry-point runtime selection and client-only
 * fallback that previously lived in `callAgent` and `#executeDirectMentionRoute`.
 *
 * Runtime routing rules (same as top-level `selectRuntimeType`):
 *   `parentRuntime` wins β†’ otherwise hetero β†’ gateway β†’ client
 *
 * Context semantics by runtime:
 *   - client: `agentId` = parent agent (for message key), `subAgentId` = target
 *   - gateway: `agentId` = target agent (gateway runs this agent), `subAgentId` = target
 *
 * Explicitly excluded:
 *   - `hetero` runtime β†’ throws (handled by the heterogeneous pipeline)
 *   - group orchestration β†’ not routed here (callers guard this upstream)
 */
export async function dispatchNonHeteroSubAgent(
  intent: AgentInvocationIntent,
  ctx: NonHeteroSubAgentDispatchContext,
  store: Pick<ChatStore, 'executeClientAgent' | 'executeGatewayAgent'>,
): Promise<void> {
  const runtimeType = selectRuntimeType({
    boundDeviceId: ctx.boundDeviceId,
    heterogeneousProvider: ctx.heterogeneousProvider,
    isGatewayMode: ctx.isGatewayMode,
    parentRuntime: ctx.parentRuntime,
    workspaceScoped: ctx.workspaceScoped,
  });

  switch (runtimeType) {
    case 'client': {
      // Keep agentId as the parent agent so the message map key is correct.
      // subAgentId selects the target agent's config (effectiveAgentId = subAgentId).
      await store.executeClientAgent({
        context: {
          ...ctx.conversationContext,
          scope: 'sub_agent',
          subAgentId: intent.targetAgentId,
        },
        inPortalThread: ctx.inPortalThread,
        messages: ctx.messages ?? [],
        parentMessageId: intent.parentMessageId,
        parentMessageType: 'tool',
        parentOperationId: ctx.parentOperationId,
      });
      break;
    }

    case 'gateway': {
      // Execute with the target agent, but route persisted/streamed messages to
      // the parent conversation. This keeps speaker identity and conversation
      // ownership separate instead of hiding cross-agent replies in another
      // messageMap bucket.
      await store.executeGatewayAgent({
        context: {
          ...ctx.conversationContext,
          agentId: intent.targetAgentId,
          scope: 'sub_agent',
          subAgentId: intent.targetAgentId,
        },
        message: intent.instruction,
        messageContext: ctx.conversationContext,
        parentOperationId: ctx.parentOperationId,
      });
      break;
    }

    case 'hetero': {
      // Hetero sub-agent invocation is out of scope for .
      // Hetero agents are dispatched through a dedicated heterogeneous pipeline
      // (`executeHeterogeneousAgent`) and must not fall through to client mode.
      throw new Error(
        `[dispatchNonHeteroSubAgent] Hetero runtime is not supported for ` +
          `non-hetero sub-agent dispatch. ` +
          `kind=${intent.kind}, targetAgentId=${intent.targetAgentId}`,
      );
    }
  }
}