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 { RequestTrigger } from '@lobechat/types';

import type { AgentAccountView } from '@/database/models/agentAccount';
import type { AgentInboxEntry } from '@/database/models/agentInbox';
import { AgentInboxModel } from '@/database/models/agentInbox';
import { TopicModel } from '@/database/models/topic';
import type { LobeChatDatabase } from '@/database/type';
import { AiAgentService } from '@/server/services/aiAgent';
import { TopicStartReservationError } from '@/server/services/aiAgent/topicStartReservation';

import type { AgentInboundWakeInput, AgentInboundWaker } from './inbound';
import {
  createOwnerChannelReportHook,
  INBOX_RUN_INTERVENTION,
  INBOX_RUN_PLUGIN_IDS,
  OWNER_CHANNEL_INSTRUCTION,
} from './ownerChannel';
import { buildInboxTopicTitle, fenceUntrustedInbox, toUntrustedInboxEntry } from './untrusted';

/** Body budget for the wake prompt; the full text stays readable through the tool. */
const WAKE_BODY_PREVIEW_CHARS = 2000;

/**
 * The prompt the woken agent sees. Only the first sentence is ours; the
 * message itself is attacker-controlled, so it rides on the user side inside
 * an `<untrusted_inbox>` fence and never reaches the system prompt.
 */
export const buildInboundPrompt = (account: AgentAccountView, message: AgentInboxEntry): string =>
  [
    `A new message arrived for your ${account.kind} account ${account.identifier}. Decide whether it needs anything from you.`,
    OWNER_CHANNEL_INSTRUCTION,
    fenceUntrustedInbox([
      toUntrustedInboxEntry(message, { maxBodyChars: WAKE_BODY_PREVIEW_CHARS }),
    ]),
  ].join('\n\n');

/**
 * Production waker: starts a normal agent run on the account's owner, stamped
 * with {@link RequestTrigger.Inbox} so completion push and spend attribution
 * treat it as an external event rather than a user turn.
 *
 * The run is started on the owner's `userId` β€” the webhook has no caller
 * identity, and the message belongs to whoever owns the account.
 */
export const createAgentInboundWaker = (db: LobeChatDatabase): AgentInboundWaker => ({
  wake: async ({ account, message }: AgentInboundWakeInput) => {
    const service = new AiAgentService(db, account.userId, {
      workspaceId: account.workspaceId ?? undefined,
    });

    // A reply in an ongoing thread continues the conversation the earlier
    // message started, instead of opening one topic per email.
    const threadTopicId = message.threadKey
      ? await AgentInboxModel.findThreadTopicId(db, {
          accountId: account.id,
          threadKey: message.threadKey,
        })
      : undefined;

    // Returns once the operation exists (`ExecAgentResult` is "started", not
    // "finished"), so the webhook answers the provider promptly while the run
    // continues in the background.
    const start = (topicId?: string) =>
      service.execAgent({
        agentId: account.agentId,
        appContext: { scope: 'agent', topicId },
        exclusivePluginIds: INBOX_RUN_PLUGIN_IDS,
        hooks: [createOwnerChannelReportHook(db, account.id)],
        prompt: buildInboundPrompt(account, message),
        title: buildInboxTopicTitle([message]),
        trigger: RequestTrigger.Inbox,
        userInterventionConfig: INBOX_RUN_INTERVENTION,
      });

    /**
     * Continue the thread in its topic. A topic the user deleted since is
     * refused by the start's reservation β€” thrown before anything of the run is
     * written β€” and a fresh topic beats never waking. A topic that still exists
     * but is busy is left alone: forking the thread into a second topic is
     * worse than the provider retrying the delivery a moment later.
     */
    const startInThread = async () => {
      if (!threadTopicId) return start();

      try {
        const inThread = await start(threadTopicId);
        return inThread.error ? start() : inThread;
      } catch (error) {
        if (!(error instanceof TopicStartReservationError)) throw error;

        const topicModel = new TopicModel(db, account.userId, account.workspaceId ?? undefined);
        if (await topicModel.findById(threadTopicId))
          return { error: error.message, topicId: undefined };
        return start();
      }
    };

    const result = await startInThread();

    if (result.error) {
      console.error(
        '[agentInbound] run did not start for account %s: %s',
        account.id,
        result.error,
      );
      return { reason: 'start-failed', started: false };
    }

    // The run exists from here on. A failure to record that must not be
    // reported as a failed wake: that would hand the claim back and let the
    // provider's retry start a second run for the same delivery. The row keeps
    // its wake claim, so retries see it as already handled.
    try {
      await AgentInboxModel.markWoken(db, message.id, result.topicId);
    } catch (error) {
      console.error(
        '[agentInbound] run started but marking message %s woken failed:',
        message.id,
        error,
      );
    }

    return { reason: 'started', started: true, topicId: result.topicId };
  },
});