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.

21.4 KB
Raw Blame
import { type AgentState, selectToolSourceMap } from '@lobechat/agent-runtime';
import { formatWebOnboardingStateMessage } from '@lobechat/builtin-tool-web-onboarding/utils';
import {
  resolveUninstalledBuiltinTools,
  type UninstalledBuiltinToolsScope,
} from '@lobechat/builtin-tools';
import { AGENT_PLAN_FILE_TYPE } from '@lobechat/const';
import type { AvailablePluginInfo } from '@lobechat/context-engine';
import {
  type AgentContextDocument,
  agentDocumentChangesByMessage,
  type AgentDocumentIndexSnapshot,
  agentDocumentsFromSnapshot,
  reusablePinnedAgentDocumentIndex,
} from '@lobechat/context-engine/agent-document';
import type { ContextFactProviders, ContextFactRequest } from '@lobechat/mecha';
import {
  agentShareDocumentAccessScope,
  getOptedInPluginIds,
  isLiveAgentAccount,
  ordinaryDocumentAccessScope,
} from '@lobechat/types';

import { loadModels } from '@/business/client/model-bank/loadModels';
import { composioEnv } from '@/config/composio';
import { AgentModel } from '@/database/models/agent';
import { AgentAccountModel } from '@/database/models/agentAccount';
import { AgentDocumentModel } from '@/database/models/agentDocuments';
import { AiModelModel } from '@/database/models/aiModel';
import { ChatGroupModel } from '@/database/models/chatGroup';
import { ConnectorModel } from '@/database/models/connector';
import { FileModel } from '@/database/models/file';
import { MessageModel } from '@/database/models/message';
import { PluginModel } from '@/database/models/plugin';
import { TopicModel } from '@/database/models/topic';
import { TopicDocumentModel } from '@/database/models/topicDocument';
import { UserModel } from '@/database/models/user';
import { UserPersonaModel } from '@/database/models/userMemory/persona';
import { WorkspaceModel } from '@/database/models/workspace';
import { appEnv } from '@/envs/app';
import { loadConnectedComposioIds } from '@/server/modules/AgentRuntime/adapters/composioConnectedIds';
import type { RuntimeExecutorContext } from '@/server/modules/AgentRuntime/context';
import { buildPostProcessUrl, log } from '@/server/modules/AgentRuntime/executorHelpers';
import { AgentDocumentsService } from '@/server/services/agentDocuments';
import { findRevokedDocumentReads } from '@/server/services/agentDocuments/revokedReads';
import { AgentInboxService } from '@/server/services/agentIdentity/inbox';
import { MarketService } from '@/server/services/market';
import { OnboardingService } from '@/server/services/onboarding';
import { resolveSandboxSessionConfig } from '@/server/services/sandbox';
import { toAgentContextDocuments } from '@/utils/agentDocumentContextMapping';

import { type AgentDocumentIndexTurn, resolveServerAgentDocumentIndex } from './agentDocumentIndex';

export interface ServerContextFactSource {
  ctx: RuntimeExecutorContext;
  /**
   * The step's conversation and provider cache TTL. With it the documents
   * index renders from a snapshot kept across warm turns; without it, from
   * the live documents.
   */
  documentIndexTurn?: AgentDocumentIndexTurn;
  state: AgentState;
}

/** Which connector families this deployment offers (mirrors the global config). */
export const resolveServerConnectorFeatures = (): ContextFactRequest['features'] => ({
  composio: !!composioEnv.COMPOSIO_API_KEY,
  lobehubSkill: !!(appEnv.MARKET_TRUSTED_CLIENT_SECRET && appEnv.MARKET_TRUSTED_CLIENT_ID),
});

const toIsoString = (value: Date | string | null | undefined): string =>
  value instanceof Date ? value.toISOString() : (value ?? '');

const getAppUrl = (): string | undefined => {
  try {
    return appEnv.APP_URL;
  } catch {
    return process.env.APP_URL;
  }
};

/**
 * How the server fetches the facts the shared context rules ask for. Every
 * method is a plain lookup against the database, the market service or the
 * run's own tool set; which facts a turn needs, and what a share visitor may
 * see, is decided by `gatherContextFacts` in `@lobechat/mecha`.
 */
export const createServerContextFactProviders = ({
  ctx,
  documentIndexTurn,
  state,
}: ServerContextFactSource): ContextFactProviders => {
  const { serverDB, userId } = ctx;
  if (!serverDB || !userId) return {};
  const db = serverDB;
  const workspaceId = state.origin?.workspaceId ?? ctx.workspaceId;
  const documentAccessScope = ctx.agentShareVisitor
    ? agentShareDocumentAccessScope({
        shareId: ctx.agentShareVisitor.shareId,
        topicId: state.origin?.topicId ?? ctx.topicId ?? '',
        visitorUserId: ctx.agentShareVisitor.visitorUserId,
      })
    : ordinaryDocumentAccessScope;

  // `listAgentDocuments` and `listAgentDocumentChanges` must render from the
  // same snapshot, and resolving one may write it, so resolve once per agent.
  const agentDocumentIndexes = new Map<
    string,
    Promise<{ docs: AgentContextDocument[]; snapshot?: AgentDocumentIndexSnapshot }>
  >();
  const loadAgentDocumentIndex = (agentId: string) => {
    let pending = agentDocumentIndexes.get(agentId);
    if (!pending) {
      pending = (async () => {
        // A later step of a run renders the index from the snapshot its first
        // step pinned, so it needs no progressive document. Skip reading them:
        // an agent can hold over 10k, and every step used to read them all.
        const pinned = documentIndexTurn
          ? reusablePinnedAgentDocumentIndex({
              messages: documentIndexTurn.messages,
              pinned: state.binding?.agentDocumentIndex,
            })
          : undefined;
        const docs = toAgentContextDocuments(
          await new AgentDocumentsService(
            db,
            userId,
            workspaceId,
            undefined,
            documentAccessScope,
          ).getAgentContextDocuments(agentId, { excludeProgressive: !!pinned }),
        );
        if (pinned) return { docs, snapshot: pinned };
        if (!documentIndexTurn) return { docs };
        try {
          const snapshot = await resolveServerAgentDocumentIndex({
            agentId,
            ctx,
            docs,
            state,
            turn: documentIndexTurn,
          });
          return { docs, snapshot };
        } catch (error) {
          // A snapshot only saves cache; never lose the documents over it.
          log('Agent-document index snapshot failed, rendering live documents: %O', error);
          return { docs };
        }
      })();
      agentDocumentIndexes.set(agentId, pending);
    }
    return pending;
  };

  return {
    findAgentDocument: async (agentId, documentId) => {
      const doc = await new AgentDocumentsService(
        db,
        userId,
        workspaceId,
        undefined,
        documentAccessScope,
      ).getDocumentById(documentId, agentId);
      return doc ? { content: doc.content, title: doc.title } : null;
    },

    findRevokedDocumentReads: async (agentId, documentIds) =>
      findRevokedDocumentReads(
        new AgentDocumentModel(db, userId, workspaceId, documentAccessScope),
        agentId,
        documentIds,
      ),

    findTopic: async (topicId) => {
      const topic = await new TopicModel(db, userId, ctx.workspaceId).findById(topicId);
      if (!topic) return null;
      return {
        agentId: topic.agentId,
        groupId: topic.groupId,
        historySummary: topic.historySummary,
        id: topic.id,
        senderId: topic.senderId,
        title: topic.title,
      };
    },

    getAgentDefinition: async (agentId) => {
      const config = (await new AgentModel(db, userId, ctx.workspaceId).getAgentConfigById(
        agentId,
      )) as Record<string, any> | null;
      if (!config) return null;
      return {
        ...config,
        plugins: getOptedInPluginIds(Array.isArray(config.plugins) ? config.plugins : undefined),
      };
    },

    getGroup: async (groupId) => {
      const chatGroupModel = new ChatGroupModel(db, userId, ctx.workspaceId);
      const [group, roster] = await Promise.all([
        chatGroupModel.findById(groupId),
        chatGroupModel.getGroupAgentsWithMeta(groupId),
      ]);
      if (!group) return null;
      return {
        config: group.config,
        content: group.content,
        members: roster.map((member) => ({
          agentId: member.agentId,
          description: member.description,
          role: member.role === 'supervisor' ? 'supervisor' : 'participant',
          title: member.title,
        })),
        title: group.title,
      };
    },

    getOnboardingContext: async () => {
      const onboardingService = new OnboardingService(db, userId);
      const docService = new AgentDocumentsService(db, userId, workspaceId);
      const personaModel = new UserPersonaModel(db, userId);

      const [onboardingState, soulDoc, persona, userInfo] = await Promise.all([
        onboardingService.getState(),
        onboardingService
          .getInboxAgentId()
          .then((inboxAgentId) =>
            inboxAgentId ? docService.getDocumentByFilename(inboxAgentId, 'SOUL.md') : null,
          )
          .catch((error) => {
            log('Failed to fetch SOUL.md for onboarding context: %O', error);
            return null;
          }),
        personaModel.getLatestPersonaDocument().catch((error) => {
          log('Failed to fetch user persona for onboarding context: %O', error);
          return null;
        }),
        onboardingService.getInitialUserInfo().catch((error) => {
          log('Failed to fetch initial user info for onboarding context: %O', error);
          return undefined;
        }),
      ]);

      return {
        discoveryUserMessageCount: onboardingState.discoveryUserMessageCount,
        personaContent: persona?.persona ?? null,
        phaseGuidance: formatWebOnboardingStateMessage(onboardingState),
        remainingDiscoveryExchanges: onboardingState.remainingDiscoveryExchanges,
        soulContent: soulDoc?.content ?? null,
        userInfo,
      };
    },

    getPlanDocument: async (topicId) => {
      const [planDocument] = await new TopicDocumentModel(db, userId, workspaceId).findByTopicId(
        topicId,
        { type: AGENT_PLAN_FILE_TYPE },
      );
      if (!planDocument) return null;
      return {
        content: planDocument.content,
        createdAt: toIsoString(planDocument.createdAt),
        description: planDocument.description,
        id: planDocument.id,
        metadata: planDocument.metadata as { todos?: unknown } | null,
        title: planDocument.title,
        updatedAt: toIsoString(planDocument.updatedAt),
      };
    },

    getUserInfo: async (targetUserId) => {
      const info = await UserModel.getInfoForAIGeneration(db, targetUserId ?? userId);
      return { language: info.preferredReplyLanguage, username: info.userName };
    },

    getWorkspaceContext: async (targetWorkspaceId) => {
      const appUrl = getAppUrl();
      if (!targetWorkspaceId) return { appUrl };
      const workspace = await new WorkspaceModel(db, userId).findById(targetWorkspaceId);
      if (!workspace?.slug)
        log('Workspace %s has no slug; skipping workspace context', targetWorkspaceId);
      return { appUrl, slug: workspace?.slug ?? undefined };
    },

    /**
     * The agent's own identity as first-class state: the live addresses it owns
     * and how much is unread in its inbox (never the messages themselves). Read
     * on every step so a message that landed mid-conversation is visible on the
     * next one β€” this is what the runtime relies on instead of carrying an
     * always-on mailbox tool.
     *
     * A share visitor never gets the agent's identity: it is the creator's.
     */
    listAgentAccountContext: async (agentId) => {
      const targetAgentId = agentId ?? state.origin?.agentId;
      if (!targetAgentId || ctx.agentShareVisitor) return undefined;

      const accounts = await new AgentAccountModel(db, userId, undefined, workspaceId).query({
        agentId: targetAgentId,
        liveOnly: true,
      });
      if (accounts.length === 0) return undefined;

      // `liveOnly` already drops retired kinds in SQL; re-assert it here so the
      // identity block can only ever name a kind the runtime has a provider for.
      const liveAccounts = accounts.filter(isLiveAgentAccount);
      if (liveAccounts.length === 0) return undefined;

      const summary = await AgentInboxService.summary(db, targetAgentId);

      return {
        accounts: liveAccounts.map((account) => ({
          capabilities: account.capabilities,
          displayName: account.displayName,
          identifier: account.identifier,
          kind: account.kind,
          provider: account.provider,
          status: account.status,
        })),
        inbox: summary,
      };
    },

    listAgentDocumentChanges: async (agentId) => {
      const index = await loadAgentDocumentIndex(agentId);
      return index.snapshot && agentDocumentChangesByMessage(index.snapshot);
    },

    listAgentDocuments: async (agentId) => {
      const { docs, snapshot } = await loadAgentDocumentIndex(agentId);
      // The index renders the snapshot, so documents created, edited or
      // deleted since do not rewrite the prompt prefix behind it; the change
      // notes (`listAgentDocumentChanges`) tell the model about them.
      return snapshot ? agentDocumentsFromSnapshot(docs, snapshot) : docs;
    },

    // Connected = ACTIVE Composio connections across BOTH the legacy plugin
    // projection AND the connector table, plus the LobeHub skill providers
    // discovered for this run (their manifests are only fetched for connected
    // providers, so presence in the tool set is the connection).
    listConnectedConnectorIds: async (agentId) => {
      const connected = await loadConnectedComposioIds(db, userId, ctx.workspaceId, {
        agentId,
        topicId: ctx.topicId,
      });
      const sourceMap = selectToolSourceMap(state);
      for (const [identifier, source] of Object.entries(sourceMap)) {
        if (source === 'lobehubSkill') connected.add(identifier);
      }
      return connected;
    },

    listCredentials: async ({ workspaceId: scopeWorkspaceId }) => {
      // Frozen when the operation was created, so a run renders {{CREDS_LIST}}
      // without a Market round trip per step. The scope must match: inside a
      // workspace the agent only sees that workspace's shared credentials.
      const frozen = state.operationCredentials;
      if (frozen && frozen.workspaceId === scopeWorkspaceId) return frozen.credentials;

      // Read market accessToken from DB so the server-side runtime can
      // authenticate with the Market API instead of falling back to an
      // anonymous trustedClientToken (which 401s on creds endpoints).
      let marketAccessToken: string | undefined;
      try {
        const settings = await new UserModel(db, userId).getUserSettings();
        marketAccessToken = (settings?.market as any)?.accessToken;
      } catch {
        // non-fatal β€” MarketService will fall back to trustedClientToken
      }
      const marketService = new MarketService({
        accessToken: marketAccessToken,
        userInfo: { userId },
      });
      // Inside a workspace, the agent must only see the workspace's shared
      // organization credentials β€” personal creds are not visible there.
      const result = scopeWorkspaceId
        ? await marketService.market.organizations.creds({ workspaceId: scopeWorkspaceId }).list()
        : await marketService.market.creds.list();
      const creds = (result as any)?.data ?? [];
      log('Fetched %d creds for {{CREDS_LIST}} substitution', creds.length);
      return creds.map((cred: any) => ({
        description: cred.description,
        key: cred.key,
        name: cred.name,
        ownerDisplayName: cred.ownerDisplayName,
        ownerType: cred.ownerType,
        type: cred.type,
      }));
    },

    // Custom MCP servers the user installed, beyond the shared catalog: custom
    // connectors (every install now) and the custom plugin rows older installs
    // left, one entry per identifier. Read from the tables: the run's tool
    // source map only classifies skill / Composio / client tools, so it cannot
    // tell a custom connector apart, and one the agent has not pinned yet must
    // still be offered to createAgent / updateAgent.
    listCustomPlugins: async () => {
      const [connectors, installed] = await Promise.all([
        new ConnectorModel(db, userId, ctx.workspaceId).queryPublic(),
        new PluginModel(db, userId, ctx.workspaceId).query(),
      ]);
      const plugins = new Map<string, AvailablePluginInfo>();
      for (const connector of connectors) {
        if (connector.sourceType !== 'custom') continue;
        plugins.set(connector.identifier, {
          description: connector.description ?? undefined,
          identifier: connector.identifier,
          name: connector.name || connector.identifier,
          type: 'custom',
        });
      }
      for (const plugin of installed) {
        if (plugin.type !== 'customPlugin' || plugins.has(plugin.identifier)) continue;
        plugins.set(plugin.identifier, {
          description: plugin.manifest?.meta?.description,
          identifier: plugin.identifier,
          name: plugin.manifest?.meta?.title || plugin.identifier,
          type: 'custom',
        });
      }
      return [...plugins.values()];
    },

    listEnabledProviders: async () => {
      const [allUserModels, builtinModels] = await Promise.all([
        new AiModelModel(db, userId).getAllModels(),
        loadModels(),
      ]);
      const providerMap = new Map<
        string,
        {
          id: string;
          models: { abilities?: any; description?: string; id: string; name: string }[];
          name: string;
        }
      >();
      for (const userModel of allUserModels) {
        if (!userModel.enabled || userModel.type !== 'chat') continue;
        const modelInfo = builtinModels.find(
          (m) => m.id === userModel.id && m.providerId === userModel.providerId,
        );
        if (!providerMap.has(userModel.providerId)) {
          providerMap.set(userModel.providerId, {
            id: userModel.providerId,
            models: [],
            name: userModel.providerId,
          });
        }
        providerMap.get(userModel.providerId)!.models.push({
          abilities: userModel.abilities || modelInfo?.abilities,
          description: modelInfo?.description,
          id: userModel.id,
          name: userModel.displayName || modelInfo?.displayName || userModel.id,
        });
      }
      return [...providerMap.values()];
    },

    listRecentAgents: async (limit) =>
      (await new AgentModel(db, userId, ctx.workspaceId).queryAgents({ limit })).map((a) => ({
        description: a.description,
        id: a.id,
        name: a.name,
        title: a.title,
      })),

    // The uninstalled list lives on the user's tool settings, one slot per
    // workspace plus the personal one β€” the same slot the tool store reads.
    listUninstalledBuiltinIds: async () => {
      const settings = await new UserModel(db, userId).getUserSettings();
      return resolveUninstalledBuiltinTools(
        settings?.tool as UninstalledBuiltinToolsScope | undefined,
        workspaceId,
      );
    },

    listSandboxFiles: async (topicId) =>
      new FileModel(db, userId).findFilesToInitInSandbox(topicId),

    // Resolved from the same inputs the cloud-sandbox runtime uses, so the model
    // is never told its files persist while its tools write to a directory that
    // does not β€” or the reverse. Keyed on `ctx.workspaceId` for the same reason
    // the runtime is: that is the workspace the trust token carries, and the
    // entitlement has to agree with the token that presents it.
    resolveSandboxPersistence: async () => {
      const { mode, cwd, claim, initialization, workingDir } = await resolveSandboxSessionConfig({
        isShareVisitorRun: Boolean(ctx.agentShareVisitor),
        serverDB: db,
        topicId: ctx.topicId ?? state.origin?.topicId,
        userId,
        // The run's workspace, the same one every other fact here is scoped to.
        // Reading the raw context instead looked the topic up in the personal
        // scope on any path that does not carry the id, found nothing, and
        // described a disposable sandbox to a run that had a persistent one β€”
        // so the model was told its files would not survive and worked in /tmp.
        workspaceId,
      });

      // What the topic's environment checks out, for the model to be told where
      // each repository is β€” on any sandbox, persistent or not.
      const repositories = (initialization?.sources ?? []).map((source) => ({
        ...(source.path && source.path !== '.' && { folder: source.path }),
        ...(source.ref && { ref: source.ref }),
        repository: source.url
          .replace(/^https:\/\/(www\.)?github\.com\//, '')
          .replace(/\.git$/, '')
          .replace(/\/$/, ''),
      }));

      if (claim) return { cwd, mode, workingDir, ...(repositories.length && { repositories }) };
      return repositories.length ? { mode: 'ephemeral' as const, repositories } : undefined;
    },

    listTopicMessages: async (topic) => {
      const messages = await new MessageModel(db, userId, ctx.workspaceId).query(
        {
          agentId: topic.agentId ?? undefined,
          groupId: topic.groupId ?? undefined,
          topicId: topic.id,
        },
        // The shared rules already proved a visitor may see this topic, so
        // the creator-facing agent-share exclusion must not apply here.
        { allowShareVisitor: true, postProcessUrl: buildPostProcessUrl(ctx) },
      );
      return messages.map((message) => ({
        content: typeof message.content === 'string' ? message.content : '',
        role: message.role,
      }));
    },
  };
};