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.

16.8 KB
Raw Blame
import type {
  AgentAccountInboundEvent,
  AgentAccountInboundMessage,
  AgentAccountInboundRequest,
} from '@lobechat/types';

import type { AgentAccountView } from '@/database/models/agentAccount';
import { AgentAccountModel } from '@/database/models/agentAccount';
import type { AgentInboxEntry } from '@/database/models/agentInbox';
import { AgentInboxModel } from '@/database/models/agentInbox';
import { SignalModel } from '@/database/models/signal';
import type { LobeChatDatabase } from '@/database/type';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';

import { AgentInboxService } from './inbox';
import { AgentAccountService } from './index';
import { createDefaultAgentAccountRegistry } from './providers';
import type { ResolvedWakeConfig } from './wake/config';
import type { MailWakeAction, MailWakePlan } from './wake/decide';
import { planMailWake, recordMailWakeDecision } from './wake/decide';
import { holdForDigest, isDigestAvailable } from './wake/digest';
import { createAgentInboundWaker } from './waker';

/**
 * What the agent should do about a delivery that just landed.
 *
 * Injected rather than imported so the inbound route can be exercised without
 * standing up the whole run pipeline: production wires {@link
 * createAgentInboundWaker}, tests wire a recorder. The contract is deliberately
 * tiny β€” "a message arrived for this agent's account; do whatever waking means"
 * β€” so the waker can grow (share gating, budget, quiet hours) without the
 * webhook knowing.
 */
export interface AgentInboundWakeInput {
  account: AgentAccountView;
  message: AgentInboxEntry;
}

export interface AgentInboundWakeResult {
  /** Human-auditable reason the waker recorded (e.g. `started`, `no-agent`). */
  reason: string;
  /** Whether a run was actually started. */
  started: boolean;
  /** The topic the run landed in, so later mail on the same thread can join it. */
  topicId?: string;
}

export interface AgentInboundWaker {
  wake: (input: AgentInboundWakeInput) => Promise<AgentInboundWakeResult>;
}

/** The decision the webhook route turns into an HTTP status. */
export type AgentInboundResult =
  | {
      accountId: string;
      created: boolean;
      messageId: string;
      outcome: 'delivered';
      /**
       * 503 when the message is stored but its wake failed transiently: the
       * replay claim is released so the provider's retry wakes it then.
       */
      status: 200 | 503;
      wake: AgentInboundWakeResult;
    }
  | { accountId?: string; outcome: 'ignored'; status: 200 }
  | { accountId?: string; outcome: 'rejected'; status: 401 }
  | { outcome: 'unknown-account' | 'unroutable'; status: 404 };

/** Where a delivery the wake rules hold back goes: the account's next digest. */
export interface AgentInboundDigest {
  /** Books the digest flush for the window this delivery arrived in. */
  hold: (account: AgentAccountView, config: ResolvedWakeConfig) => Promise<void>;
  /** Without a durable delay queue there is no digest; held deliveries wake at once instead. */
  isAvailable: () => boolean;
}

const DEFAULT_DIGEST: AgentInboundDigest = { hold: holdForDigest, isAvailable: isDigestAvailable };

export interface AgentInboundServiceOptions {
  /** The account service that owns signature verification. */
  accountService: AgentAccountService;
  /** Defaults to the QStash-backed digest. */
  digest?: AgentInboundDigest;
  /** Defaults to a no-op waker that reports `not-configured`. */
  waker?: AgentInboundWaker;
}

/**
 * Wake budget. Every delivery is still recorded β€” the limit only decides
 * whether it may start a run. Without it, anyone who knows the address can
 * start unbounded runs on the owner's account (and spend) just by mailing it.
 * Counted from the inbox itself, so the limit holds across instances with no
 * extra store.
 */
export const INBOUND_WAKE_LIMITS = {
  /** Deliveries per account in {@link windowMs} that may wake the agent. */
  perAccount: 30,
  /** Deliveries per (account, sender) in {@link windowMs} that may wake the agent. */
  perSender: 5,
  windowMs: 60 * 60 * 1000,
} as const;

/**
 * Wake outcomes worth a provider retry: the run pipeline failed, not a
 * deliberate decision (rate limit, missing agent, no waker configured).
 */
const RETRYABLE_WAKE_REASONS = new Set(['start-failed', 'wake-failed']);

const NOOP_WAKER: AgentInboundWaker = {
  wake: async () => ({ reason: 'waker-not-configured', started: false }),
};

/** A signal's payload is the source's own event; anything else is wrapped. */
const toSignalPayload = (payload: unknown): Record<string, unknown> =>
  payload && typeof payload === 'object' && !Array.isArray(payload)
    ? (payload as Record<string, unknown>)
    : { value: payload ?? null };

/**
 * The inbound edge: one provider webhook delivery becomes one signal, one mail,
 * one inbox item and (optionally) one agent wake.
 *
 * It composes the pieces that must stay separate:
 *
 * 1. **Verify** β€” {@link AgentAccountService.handleInbound} routes by an
 *    untrusted identifier and verifies the signature; only a `delivered`
 *    outcome is trusted.
 * 2. **Persist** β€” every authentic delivery is recorded as a signal (what the
 *    outside world sent, kept with how its processing ended); a delivered one
 *    is then recorded as an `agent_mails` row and put in the inbox. Each step
 *    is idempotent, so a provider retry returns the same item with
 *    `created: false` instead of duplicating it or waking the agent twice.
 * 3. **Decide** β€” the account's wake rules ({@link planMailWake}) say whether
 *    the delivery wakes the agent now, waits for the digest, or neither; the
 *    decision is recorded against the signal either way.
 * 4. **Wake** β€” a delivery the rules let through wakes the agent through the
 *    injected waker, within {@link INBOUND_WAKE_LIMITS}. A duplicate of a
 *    message that was already woken never reaches this step; a wake that failed
 *    transiently answers 503 and releases the replay claim, so the provider's
 *    retry wakes the still-unread message then.
 */
export class AgentInboundService {
  private readonly db: LobeChatDatabase;
  private readonly options: AgentInboundServiceOptions;

  constructor(db: LobeChatDatabase, options: AgentInboundServiceOptions) {
    this.db = db;
    this.options = options;
  }

  handle = async (
    provider: string,
    request: AgentAccountInboundRequest,
  ): Promise<AgentInboundResult> => {
    // A webhook URL for a provider this deployment never configured is a 404,
    // not the registry's thrown error surfacing as a 500.
    if (!this.options.accountService.hasProvider(provider)) {
      return { outcome: 'unroutable', status: 404 };
    }

    const decision = await this.options.accountService.handleInbound(provider, request);

    switch (decision.outcome) {
      case 'rejected': {
        return { accountId: decision.accountId, outcome: 'rejected', status: 401 };
      }
      case 'ignored': {
        // A duplicate is a signal already on record; anything else authentic is
        // a new one that deliberately produced nothing, kept with the reason.
        if (decision.reason !== 'duplicate') {
          await this.recordIgnored(provider, decision.accountId, decision.event, decision.reason);
        }
        return { accountId: decision.accountId, outcome: 'ignored', status: 200 };
      }
      case 'unknown-account':
      case 'unroutable': {
        return { outcome: decision.outcome, status: 404 };
      }
      default: {
        const { eventId } = decision.event;
        let result: AgentInboundResult;
        try {
          result = await this.deliver(
            provider,
            decision.accountId,
            decision.event,
            decision.message,
          );
        } catch (error) {
          // The event id is already claimed: without giving it back, every
          // retry during the claim's lifetime would be acknowledged as a
          // duplicate and the message never stored.
          await this.options.accountService
            .releaseInbound(provider, eventId)
            .catch(() => undefined);
          throw error;
        }
        // Stored but not woken for a transient reason: forget the replay claim
        // so the provider's retry is processed and wakes the agent then.
        if (result.status === 503) {
          await this.options.accountService.releaseInbound(provider, eventId);
        }
        return result;
      }
    }
  };

  /**
   * Persist a verified message and, if it is new, wake the agent.
   *
   * The account row is read through the *owner's* scope, so a message can only
   * ever land in the inbox of the user who owns the account β€” the webhook has
   * no caller identity to borrow.
   */
  private deliver = async (
    provider: string,
    accountId: string,
    event: AgentAccountInboundEvent,
    message: AgentAccountInboundMessage,
  ): Promise<AgentInboundResult> => {
    const account = await this.loadAccount(accountId);
    if (!account) return { outcome: 'unknown-account', status: 404 };

    const { signal } = await this.recordSignal(provider, account, event);

    try {
      const result = await this.deliverMail(account, message, signal.id);
      if (result.status === 503) {
        await SignalModel.markFailed(this.db, signal.id, `wake: ${result.wake.reason}`);
      } else {
        await SignalModel.markProcessed(this.db, signal.id);
      }
      return result;
    } catch (error) {
      await SignalModel.markFailed(
        this.db,
        signal.id,
        error instanceof Error ? error.message : String(error),
      ).catch(() => undefined);
      throw error;
    }
  };

  /** Record the mail and its inbox item, then wake the agent if the item is new. */
  private deliverMail = async (
    account: AgentAccountView,
    message: AgentAccountInboundMessage,
    signalId: string,
  ): Promise<AgentInboundResult> => {
    const accountId = account.id;
    const inbox = new AgentInboxService(this.db, account.userId, account.workspaceId ?? undefined);

    const { created, entry: row } = await inbox.recordInboundMail({ account, message, signalId });

    // Idempotent ack: the provider retried a delivery we already handled, so
    // there is nothing new to wake the agent about. A stored row that is still
    // unread was never woken (a started wake marks it read) β€” that is the retry
    // of a failed wake, so it gets its wake now instead.
    if (!created && row.readAt) {
      return {
        accountId,
        created: false,
        messageId: row.id,
        outcome: 'delivered',
        status: 200,
        wake: { reason: 'duplicate-delivery', started: false },
      };
    }

    const delivered = (wake: AgentInboundWakeResult, status: 200 | 503 = 200) =>
      ({
        accountId,
        created,
        messageId: row.id,
        outcome: 'delivered',
        status,
        wake,
      }) satisfies AgentInboundResult;

    const plan = await this.planWake(account, row);
    const record = (action: MailWakeAction, reason?: string, topicId?: string) =>
      recordMailWakeDecision(this.db, { account, action, plan, reason, signalId, topicId });

    if (plan.action === 'skip') {
      await record('skip');
      return delivered({ reason: plan.reason, started: false });
    }

    // The `defer` row is what puts the message in the digest, so it must be on
    // record before the flush is booked; a failure throws, and the provider's
    // retry holds the message again.
    const hold = async (reason?: string) => {
      if (!(await record('defer', reason))) throw new Error('the defer decision was not recorded');
      await this.digest.hold(account, plan.config);
      return delivered({ reason: 'held-for-digest', started: false });
    };

    if (plan.action === 'defer') return hold();

    if (await this.overWakeBudget(accountId, row.from)) {
      // A delivery past the budget waits for the digest instead of never
      // running; only without a digest is it dropped.
      if (this.digest.isAvailable()) return hold('rate-limited');
      await record('skip', 'rate-limited');
      return delivered({ reason: 'rate-limited', started: false });
    }

    // The unique insert only dedupes storage: two workers handling the same
    // delivery can both see the row unread. The wake itself is claimed
    // atomically on the row, so exactly one of them starts a run.
    if (!(await AgentInboxModel.claimWake(this.db, row.id))) {
      return delivered({ reason: 'duplicate-delivery', started: false });
    }

    const wake = await this.wake(account, row);
    // A transient failure gives the claim back so the provider's retry wakes it.
    if (RETRYABLE_WAKE_REASONS.has(wake.reason)) {
      await AgentInboxModel.releaseWake(this.db, row.id);
      return delivered(wake, 503);
    }

    await (wake.started ? record('wake', undefined, wake.topicId) : record('skip', wake.reason));
    return delivered(wake);
  };

  /**
   * The wake rules' plan for a delivery. Without a digest to hold it for, a
   * delivery the rules would defer wakes the agent at once instead, so nothing
   * is held where no flush will ever come.
   */
  private planWake = async (
    account: AgentAccountView,
    entry: AgentInboxEntry,
  ): Promise<MailWakePlan> => {
    const plan = await planMailWake(this.db, account, entry);
    if (plan.action !== 'defer' || this.digest.isAvailable()) return plan;

    return { ...plan, action: 'wake', reason: 'digest-unavailable' };
  };

  private get digest(): AgentInboundDigest {
    return this.options.digest ?? DEFAULT_DIGEST;
  }

  /** Record an authentic delivery as a signal, owned by the account's owner. */
  private recordSignal = (
    provider: string,
    account: AgentAccountView,
    event: AgentAccountInboundEvent,
  ) =>
    SignalModel.record(
      this.db,
      {
        accountId: account.id,
        agentId: account.agentId,
        externalId: event.eventId,
        occurredAt: event.occurredAt,
        payload: toSignalPayload(event.payload),
        source: provider,
        type: event.type ?? 'unknown',
      },
      { userId: account.userId, workspaceId: account.workspaceId ?? undefined },
    );

  /** Keep an authentic delivery that produced nothing, with why. */
  private recordIgnored = async (
    provider: string,
    accountId: string,
    event: AgentAccountInboundEvent,
    reason: string,
  ): Promise<void> => {
    const account = await this.loadAccount(accountId);
    if (!account) return;

    const { signal } = await this.recordSignal(provider, account, event);
    await SignalModel.markIgnored(this.db, signal.id, reason);
  };

  /**
   * Whether this account (or this sender on it) already used up its wake
   * budget. The just-recorded row counts, so the limit is the number of
   * deliveries that may wake per window.
   */
  private overWakeBudget = async (accountId: string, from: string): Promise<boolean> => {
    const since = new Date(Date.now() - INBOUND_WAKE_LIMITS.windowMs);
    const [fromSender, total] = await Promise.all([
      AgentInboxModel.countRecent(this.db, { accountId, from, since }),
      AgentInboxModel.countRecent(this.db, { accountId, since }),
    ]);

    return fromSender > INBOUND_WAKE_LIMITS.perSender || total > INBOUND_WAKE_LIMITS.perAccount;
  };

  /**
   * One wake attempt. A thrown waker becomes the fixed `wake-failed` reason,
   * which {@link deliver} answers with a retryable status; the stored row stays
   * unread, so the provider's retry wakes it instead of reading as a duplicate.
   */
  private wake = async (
    account: AgentAccountView,
    message: AgentInboxEntry,
  ): Promise<AgentInboundWakeResult> => {
    const waker = this.options.waker ?? NOOP_WAKER;
    try {
      return await waker.wake({ account, message });
    } catch (error) {
      // The reason travels back to the provider in the webhook response, so it
      // stays a fixed code; the detail goes to the server log only.
      console.error('[agentInbound] wake failed for account %s:', account.id, error);
      return { reason: 'wake-failed', started: false };
    }
  };

  /** Read one account by id, unscoped (the webhook has no user to scope by). */
  private loadAccount = (accountId: string): Promise<AgentAccountView | undefined> =>
    AgentAccountModel.findByIdUnscoped(this.db, accountId);
}

/**
 * Assemble the inbound edge the way the webhook route runs it: the deployment's
 * real provider registry (so an unconfigured deployment answers 404 instead of
 * verifying nothing), a real KeyVaults gatekeeper (so signatures over an
 * account's stored secret can be verified), and the production waker.
 */
export const createAgentInboundService = async (
  db: LobeChatDatabase,
): Promise<AgentInboundService> => {
  const accountService = new AgentAccountService(db, '', {
    gateKeeper: await KeyVaultsGateKeeper.initWithEnvKey(),
    registry: createDefaultAgentAccountRegistry(),
  });

  return new AgentInboundService(db, {
    accountService,
    waker: createAgentInboundWaker(db),
  });
};