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.2 KB
Raw Blame
import type { AgentInboxSourceType, AgentMailAddress, AgentMailAttachment } from './agentMail';

/**
 * Agent accounts β€” the identity assets an agent owns.
 *
 * An agent may hold several accounts: a `mail` address, a `wallet`, or a
 * third-party `service` login. Each one is its own row, belongs
 * to the agent (not to a workspace integration), and may carry credentials.
 *
 * Kinds and statuses are growing domains, so they are plain unions here and the
 * columns stay plain `text` typed by them β€” onboarding a kind is a type-only
 * change with no migration.
 */

/** The sorts of identity an agent can own today β€” what a caller may create. */
export const AGENT_ACCOUNT_KINDS = ['mail', 'wallet', 'service'] as const;
export type AgentAccountKind = (typeof AGENT_ACCOUNT_KINDS)[number];

/**
 * Every kind a persisted row β€” and therefore a read response β€” can still carry.
 *
 * `kind` is a plain text column, so a kind the product retired outlives the
 * code that minted it: the agent-owned `phone` (now a messenger channel) keeps
 * its rows. An unfiltered read deliberately leaves those rows visible so their
 * owner can still revoke them, which means every read shape has to admit a
 * value that the validators and the live-runtime filter never accept.
 */
export const AGENT_ACCOUNT_PERSISTED_KINDS = [...AGENT_ACCOUNT_KINDS, 'phone'] as const;
export type AgentAccountPersistedKind = (typeof AGENT_ACCOUNT_PERSISTED_KINDS)[number];

/**
 * Whether a persisted kind is one the product still opens.
 *
 * Reads that must only see live identities use this as a type guard, so the
 * runtime context cannot claim an account kind it has no provider for.
 */
export const isAgentAccountKind = (kind: AgentAccountPersistedKind): kind is AgentAccountKind =>
  (AGENT_ACCOUNT_KINDS as readonly string[]).includes(kind);

/**
 * Narrow an account-shaped value to one whose kind is still open.
 *
 * Object-level, not kind-level, so it can be handed straight to
 * `Array.prototype.filter` β€” a predicate on `.kind` alone leaves the element
 * type untouched.
 */
export const isLiveAgentAccount = <T extends { kind: AgentAccountPersistedKind }>(
  account: T,
): account is T & { kind: AgentAccountKind } => isAgentAccountKind(account.kind);

/** Lifecycle of one account. */
export const AGENT_ACCOUNT_STATUSES = ['provisioning', 'active', 'suspended', 'revoked'] as const;
export type AgentAccountStatus = (typeof AGENT_ACCOUNT_STATUSES)[number];

/**
 * What the account can do, declared by whoever provisions it rather than
 * inferred from its kind: a `service` account may be login-only, a `mail`
 * account may be receive-only during warm-up.
 */
export interface AgentAccountCapabilities {
  /** The credential can be used to log in to a third-party service. */
  login?: boolean;
  /** Messages can arrive at this account. */
  receive: boolean;
  /** The agent can send from this account. */
  send: boolean;
  /** The agent can sign with this account (on-chain wallet, later). */
  sign?: boolean;
}

/**
 * How inbound messages wake the agent.
 *
 * - `on` (the default): the wake rules decide. A message they let through β€” a
 *   listed sender, a reply in a thread the agent wrote to β€” wakes the agent at
 *   once; everything else waits for the digest, one run that goes through all
 *   of it together.
 * - `off`: messages are stored in the inbox and never wake the agent.
 */
export const AGENT_ACCOUNT_WAKE_MODES = ['on', 'off'] as const;
export type AgentAccountWakeMode = (typeof AGENT_ACCOUNT_WAKE_MODES)[number];

/** Shortest and longest digest window, in minutes. */
export const AGENT_ACCOUNT_DIGEST_MINUTES_RANGE = { max: 24 * 60, min: 5 } as const;

/** The owner's wake rules for one account. Every field is optional; defaults apply when read. */
export interface AgentAccountWakeSettings {
  /** Minutes the digest collects held messages before one run goes through them. Default 60. */
  digestMinutes?: number;
  mode?: AgentAccountWakeMode;
  /**
   * Senders whose messages wake the agent at once: full addresses
   * (`ceo@example.com`) or whole domains (`@example.com`).
   */
  wakeSenders?: string[];
}

/**
 * The owner's settings for one account. Unlike `metadata`, which a managed
 * provider owns, these belong to the person and are always patchable.
 */
export interface AgentAccountSettings {
  wake?: AgentAccountWakeSettings;
}

/**
 * Non-secret facts about the stored credential, safe to return from any read
 * API: enough for a person to recognise *which* secret is installed and when it
 * expires, never enough to use it.
 *
 * The secret itself lives as ciphertext in `agent_accounts.credentials` and is
 * never read back out.
 */
export interface AgentAccountCredentialHint {
  /** ISO timestamp after which the credential stops being valid. */
  expiresAt?: string;
  /** Masked tail safe to display, e.g. `β€’β€’β€’β€’ 4242`. */
  masked?: string;
  /** ISO timestamp of the last write or rotation. */
  rotatedAt?: string;
  /** Login the credential belongs to, when it is a username/password pair. */
  username?: string;
}

/** An attachment carried by an inbound or outbound account message. */
export interface AgentAccountAttachment {
  mimeType: string;
  name?: string;
  size?: number;
  url: string;
}

/**
 * A message addressed **to** the agent's account, normalized by its provider.
 * This is the shape every transport converges on, so the inbox and the runtime
 * never learn platform-specific semantics.
 */
export interface AgentAccountInboundMessage {
  attachments?: AgentAccountAttachment[];
  /** Address the message came from. */
  from: string;
  /**
   * Mail-only detail a mail provider supplies on top of the transport-neutral
   * fields, so the full message (addressing, RFC threading headers, attachment
   * descriptors) can be recorded as an `agent_mails` row.
   */
  mail?: AgentAccountInboundMailDetail;
  /** Provider-side message id, used for dedupe and idempotent replies. */
  providerMessageId: string;
  receivedAt: Date;
  subject?: string;
  text: string;
  /**
   * Provider-normalized thread key (`undefined` = a fresh thread). Providers
   * derive it themselves; nothing platform-specific leaks past this field.
   */
  threadKey?: string;
  /** Address it was delivered to β€” the agent's own identifier. */
  to: string;
}

/** What a mail provider knows about an inbound mail beyond the neutral message. */
export interface AgentAccountInboundMailDetail {
  /** Attachment descriptors; the bytes stay with the provider. */
  attachments: AgentMailAttachment[];
  cc: AgentMailAddress[];
  fromName?: string;
  /** RFC 5322 `In-Reply-To`. */
  inReplyTo?: string;
  /** RFC 5322 `Message-ID`. */
  messageId?: string;
  /** RFC 5322 `References`, oldest first. */
  references: string[];
  replyTo: AgentMailAddress[];
  to: AgentMailAddress[];
}

/**
 * A message the agent received on one of its accounts, persisted as the
 * agent's **own first-class inbox** β€” not a channel message and not a tool
 * result.
 *
 * This is what makes "the agent has an inbox" a state the runtime and the
 * model can read without paying an always-on tool slot for it: each inbound
 * delivery becomes one of these rows, and the runtime hands the unread ones to
 * the model as context.
 */
export interface AgentInboxMessage {
  /** The account it arrived at, when the channel has one. */
  accountId: string | null;
  agentId: string;
  /** What the sender attached, as the provider holds it (descriptors only). */
  attachments: AgentMailAttachment[];
  /** Verification codes pulled out of the body (4–8 digits), for the `wait` primitive. */
  codes: string[];
  createdAt: Date;
  /** Who it is from. */
  from: string;
  id: string;
  /** Short plain-text preview the inbox list shows. */
  preview: string | null;
  /** When it was first read; `null` while unread. */
  readAt: Date | null;
  receivedAt: Date;
  /** What the item is (`mail` today). */
  sourceType: AgentInboxSourceType;
  /** Its title (a mail's subject). */
  subject: string | null;
  text: string;
  /** Conversation key within the account, when the source supplies one. */
  threadKey: string | null;
  /** Where it was delivered β€” the agent's own address. */
  to: string;
}

/** One inbox row as a list shows it: who, what and when, without the content. */
export type AgentInboxMessageSummary = Pick<
  AgentInboxMessage,
  | 'accountId'
  | 'agentId'
  | 'createdAt'
  | 'from'
  | 'id'
  | 'preview'
  | 'readAt'
  | 'receivedAt'
  | 'sourceType'
  | 'subject'
  | 'threadKey'
>;

/**
 * The inbox as one glance: how much is waiting. Injected into the model's
 * context so it knows it has mail without querying.
 *
 * Deliberately carries no message content. Sender, subject and body are
 * written by whoever emails or texts the agent, so they must never reach the
 * system prompt β€” the model reads them on demand through the account tool,
 * fenced as untrusted input.
 */
export interface AgentInboxSummary {
  unreadCount: number;
}

/** One account as the runtime context shows it β€” credential-safe by construction. */
export interface AgentAccountContextItem {
  capabilities: AgentAccountCapabilities;
  displayName?: string | null;
  /** The handle the outside world reaches the agent at. */
  identifier: string;
  kind: AgentAccountKind;
  provider: string;
  status: AgentAccountStatus;
}

/**
 * The agent's identity as first-class runtime state: which addresses it owns
 * and what is waiting in its inbox. This is what replaces a resident
 * `lobe-mailbox` tool slot β€” the model is *told* who it is instead of having
 * to ask through a tool every turn.
 */
export interface AgentAccountContext {
  accounts: AgentAccountContextItem[];
  inbox: AgentInboxSummary;
  /**
   * Whether the account tool is in this step's final tool set. Some modes
   * leave it out; the identity block then must not tell the model to use it.
   */
  toolAvailable?: boolean;
}

/** A message the agent sends from one of its accounts. */
export interface AgentAccountOutboundMessage {
  attachments?: AgentAccountAttachment[];
  /**
   * Provider-side message id this send answers β€” the `providerMessageId` of the
   * inbound message being replied to. A transport that threads by id (mail's
   * `replyToMessage`) answers inside that message's thread; one that threads by
   * key ignores it and uses {@link threadKey} instead.
   */
  replyToProviderMessageId?: string;
  subject?: string;
  text: string;
  /** Reply within this thread when the provider supports it. */
  threadKey?: string;
  to: string;
}

/**
 * A persisted account, as a provider needs to act on it.
 *
 * `credential` is the one field that is not part of a normal read: the service
 * supplies the decrypted secret only on the paths allowed to use it (sending,
 * inbound signature verification) and never on list/detail.
 */
export interface AgentAccountRef {
  /** Decrypted credential, present only on trusted internal paths. */
  credential?: Record<string, string> | null;
  id: string;
  /** The handle that routes to this account: address, login. */
  identifier: string;
  /**
   * The kind the row was written with. Widened past {@link AgentAccountKind}
   * because a legacy row is still readable β€” and must stay releasable.
   */
  kind: AgentAccountPersistedKind;
  /** Provider-side non-secret handles (inboxId, chatId, …). */
  metadata: Record<string, unknown>;
  provider: string;
}

/** Who the account is being opened for. */
export interface AgentAccountProvisionInput {
  agentId: string;
  /** Human label for the new account, when the provider can set one. */
  displayName?: string;
  /**
   * Whether a live account already routes on `identifier` for this provider.
   * An idempotent provider (Agent Mail keys inboxes by agent) can be handed back
   * the resource a committed row already holds after a lost response; this
   * tells it not to mint a second credential for that resource.
   */
  isIdentifierHeld?: (identifier: string) => Promise<boolean>;
  /**
   * Preferred handle the caller asks for, when the provider can honour it β€”
   * the local part of a `mail` address, for example. A provider that cannot
   * honour a preference ignores it and mints its own identifier; a provider
   * that can either returns the requested prefix or fails, never a silent
   * substitute.
   */
  prefix?: string;
  userId: string;
  workspaceId?: string;
}

/**
 * What provisioning produced.
 *
 * `credential` is returned only when the provider mints a per-account secret
 * (an inbox webhook signing key, for example); the caller encrypts it with the
 * KeyVaults gatekeeper and never hands it back to a read.
 */
export interface AgentAccountProvisionResult {
  credential?: Record<string, string>;
  /** Non-secret display facts for the stored credential. */
  credentialHint?: AgentAccountCredentialHint;
  displayName?: string;
  identifier: string;
  metadata?: Record<string, unknown>;
}

/**
 * A raw inbound delivery, before any trust decision.
 *
 * `body` is the exact bytes the signature covers β€” parsing it for routing is
 * allowed, trusting it is not.
 */
export interface AgentAccountInboundRequest {
  body: string;
  headers: Record<string, string | undefined>;
}

/** A delivery whose signature has been verified, still in provider shape. */
export interface AgentAccountInboundEvent {
  /**
   * The signature is valid but this delivery id was already accepted β€” a
   * provider retry or a captured request played back. It is acknowledged
   * without producing a message, so a legitimate retry is not read as forged.
   */
  duplicate?: boolean;
  /** Provider delivery id; the replay-dedupe key. */
  eventId: string;
  /** When the provider says the event happened, when it says so. */
  occurredAt?: Date;
  payload: unknown;
  /** What happened, in the provider's vocabulary (e.g. `message.received`). */
  type?: string;
}

/**
 * The narrow contract a transport implements so an agent can own an address
 * with it.
 *
 * Deliberately small: there is no typing / read-receipt / reaction / capability
 * matrix / bot-credential surface here, because an account is the agent's own
 * identity rather than a bot inside someone else's platform. Anything a
 * provider needs beyond this lives in its own `metadata`.
 */
export interface AgentAccountProvider<K extends AgentAccountKind = AgentAccountKind> {
  /** What the account can do β€” declared here and persisted onto the account. */
  readonly capabilities: AgentAccountCapabilities;
  /** The account kind this provider issues. */
  readonly kind: K;
  /** Normalize a verified delivery into the transport-neutral message. */
  normalizeInbound: (
    event: AgentAccountInboundEvent,
    ref: AgentAccountRef,
  ) => Promise<AgentAccountInboundMessage | null>;

  /** Stable provider id (`agent-mail`, …); the account's `provider` value. */
  readonly provider: string;

  /** Idempotent open. Runs before the account row exists. */
  provision: (input: AgentAccountProvisionInput) => Promise<AgentAccountProvisionResult>;

  /** Idempotent release. Called while revoking, before the row is marked revoked. */
  release: (ref: AgentAccountRef) => Promise<void>;

  /**
   * Forget the replay claim {@link verifyInbound} took for a delivery, so the
   * provider's retry of it is processed instead of acknowledged as a
   * duplicate. Called when handling a verified delivery failed transiently and
   * the webhook answers with a retryable status. Optional: a provider that
   * keeps no claim has nothing to release.
   */
  releaseInbound?: (eventId: string) => Promise<void>;

  /**
   * Extract the routing key (the account `identifier`) from an *untrusted*
   * delivery, so the account can be found and its credential used to verify.
   * Returning `undefined` means the delivery cannot be routed at all.
   */
  resolveInboundIdentifier: (request: AgentAccountInboundRequest) => string | undefined;

  send: (
    ref: AgentAccountRef,
    message: AgentAccountOutboundMessage,
  ) => Promise<{ providerMessageId: string }>;

  /**
   * Verify the signature over the raw body and recognise replays. Returns
   * `null` for anything forged, so the caller answers 401 without the provider
   * leaking which check failed; an authentic delivery id seen before comes back
   * flagged `duplicate` and is acknowledged without producing a message.
   */
  verifyInbound: (
    request: AgentAccountInboundRequest,
    ref: AgentAccountRef,
  ) => Promise<AgentAccountInboundEvent | null>;
}