UNPKG

@mastra/core

Version:
596 lines • 29.1 kB
import type { Chat, Adapter, Message, Thread } from 'chat'; import type { Agent } from '../agent/agent.js'; import type { MastraProviderMetadata } from '../agent/message-list/state/types.js'; import type { AgentSignalContents, AgentSignalInput } from '../agent/signals.js'; import type { IMastraLogger } from '../logger/logger.js'; import type { Mastra } from '../mastra/index.js'; import type { MastraMemory } from '../memory/memory.js'; import type { StorageThreadType } from '../memory/types.js'; import type { InputProcessor, InputProcessorOrWorkflow, OutputProcessor, OutputProcessorOrWorkflow } from '../processors/index.js'; import { RequestContext } from '../request-context/index.js'; import type { ApiRoute } from '../server/types.js'; import type { ChatChannelRenderContext } from './output-processor.js'; import type { ThreadHistoryLogContext } from './thread-history.js'; import type { ChannelAdapterConfig, ChannelConfig, ChannelContext } from './types.js'; /** Structured fields for {@link AgentChannels.log}. */ export interface ChannelLogContext { /** Prefixes the message as `[platform]`. */ platform?: string; /** `Error` instances are normalized with `getErrorFromUnknown` so they serialize. */ error?: unknown; [key: string]: unknown; } type ChannelAgent = Pick<Agent<any, any, any, any>, 'id' | 'getMastraInstance' | 'sendMessage' | 'approveToolCall' | 'declineToolCall' | 'listSuspendedRuns' | 'getMemory' | 'getWorkspace'>; /** * Manages a single Chat SDK instance for an agent, wiring all adapters * to the Mastra pipeline (thread mapping → agent.stream → thread.post). * * One AgentChannels = one bot identity across multiple platforms. * * @internal Created automatically by the Agent when `channels` config is provided. */ export declare class AgentChannels { readonly adapters: Record<string, Adapter>; private chat; /** Stored initialization promise so webhook handlers can await readiness on serverless cold starts. */ private initPromise; private agent; private dispatchAgent?; private logger?; private customState; private stateAdapter; private userName; /** Normalized per-adapter configs (gateway flags, hooks, etc.). */ private adapterConfigs; /** Handler overrides from config. */ private handlerOverrides; /** Additional Chat SDK options. */ private chatOptions; /** Thread context config for fetching prior messages. */ private threadContext; /** Determines whether a mime type should be sent inline to the model. */ private shouldInline; /** Inline-link rules for promoting URLs in message text to file parts. */ private inlineLinkRules; /** Total bytes of attachments that may be stored under `channel-attachments/`. */ private maxAttachmentStorageBytes; /** Whether channel tools (reactions, etc.) are enabled. */ private toolsEnabled; /** Optional hook to resolve the memory resourceId (owner) for newly-created channel threads. */ private resolveResourceId; /** Memoized bot display name lookups, keyed by platform. */ private botDisplayNames; /** Optional hook to resolve the internal thread id for newly-created channel threads. */ private resolveThreadId; /** * The original `ChannelConfig` passed to the constructor. * * Useful for rebuilding `AgentChannels` while preserving existing adapters/handlers, * e.g. when a `ChannelProvider` wants to inject its own adapter without clobbering * adapters configured by the agent author: * * @example * ```ts * const existing = agent.getChannels(); * const next = new AgentChannels({ * ...existing?.channelConfig, * adapters: { ...existing?.channelConfig.adapters, slack: slackAdapter }, * }); * agent.setChannels(next); * ``` */ readonly channelConfig: ChannelConfig; /** Channel tool names whose effects are already visible on the platform (skip rendering cards). */ private channelToolNames; /** Platforms whose routes are managed externally (e.g., by SlackProvider). */ private externallyManagedPlatforms; /** * Tool-approval cards that have been posted and are awaiting user action. When the user * clicks approve/decline, the `onAction` handler looks up the card's `messageId` and * tool metadata here so it can edit the card in place and resume the run with the right * context. Entries are removed after the resume completes. */ private pendingApprovalCards; /** * Approval state per card (thread, card message, toolCallId). A click that * misses `pendingApprovalCards` may have to read the whole thread, so the * result is kept: repeat clicks (including rejected ones from other users) * reuse it with no storage read. Cards whose resume fails because the run was * already answered are marked here too. Bounded by `APPROVAL_LOOKUP_CACHE_SIZE`; * entries expire per the `APPROVAL_LOOKUP_*_TTL_MS` constants. */ private approvalLookups; /** * Cards a click is answering right now: from its card edit until its resume * is dispatched. Another click on the same card meanwhile is ignored, so it * cannot overwrite the card with a decision core is about to refuse. */ private approvalsInFlight; /** Lookups in progress, so concurrent clicks on one card share one read. */ private approvalLookupsInFlight; /** * Platforms we've already warned about for misconfigured `toolDisplay` (e.g. * `'timeline'` without `streaming: true`). Keeps log output to one warn per * platform per AgentChannels instance. */ private warnedToolDisplayFallback; constructor(config: ChannelConfig); /** * Bind the owning agent used for webhook paths and stored-thread ownership. * Called by Agent construction and setChannels; changing the owner resets dispatch. * Durable wrappers set a separate dispatch target without changing ownership. * @internal */ __setAgent(agent: ChannelAgent): void; /** Set the execution target without changing channel ownership. @internal */ __setDispatchAgent(agent: ChannelAgent): void; private getDispatchAgent; /** * Set the logger. Called by Mastra.addAgent. * @internal */ __setLogger(logger: IMastraLogger): void; /** * Register an adapter dynamically. * When `managesRoutes` is true, AgentChannels will NOT create webhook routes for this platform * (the ChannelProvider handles routing and calls handleWebhookEvent directly). * @internal */ __registerAdapter(platform: string, adapter: Adapter, config?: ChannelAdapterConfig, options?: { managesRoutes?: boolean; }): void; /** * Id of the entity that owns this channels instance, used in webhook route * paths. Returns `null` when no owner is bound yet, in which case * `getWebhookRoutes()` returns no routes. */ protected getOwnerId(): string | null; /** Base path for webhook routes, e.g. `/api/agents/{agentId}`. */ protected getWebhookBasePath(): string; /** Resolve the Mastra instance from the bound owner. */ protected getMastra(): Mastra | undefined; /** * The memory resourceId (owner) used when `processChatMessage` creates a new * channel-backed thread. Returns a thunk when a `resolveResourceId` hook is * configured so the hook only runs when a new thread is actually created, * never when reusing an existing one (which keeps its stored owner). */ protected resolveChannelResourceId(args: { platform: string; chatThread: Thread; message: Message; defaultResourceId: string; requestContext: RequestContext; }): string | (() => string | Promise<string>); /** * Route an inbound chat message into the owning agent's signal pipeline. * The message either gets delivered into an already-running agent loop or * wakes the thread with an idle stream. */ protected dispatchInboundMessage(args: { signalContents: AgentSignalContents; attributes: Record<string, string | undefined>; signalMetadata: Record<string, unknown>; providerOptions: MastraProviderMetadata; requestContext: RequestContext; /** The mapped Mastra thread for the chat thread this message arrived on. */ thread: StorageThreadType; memory: { thread: string; resource: string; }; /** Set when the adapter can't render approval buttons, to avoid runs parking forever. */ autoResumeSuspendedTools: true | undefined; }): Promise<void>; /** * Resume a suspended run with an approval and drive the resumed stream to * completion (serverless safety). */ protected dispatchApproval(args: { runId: string; toolCallId: string; requestContext: RequestContext; memory: { thread: string; resource: string; }; }): Promise<void>; /** * Resume a suspended run with a denial and drive the resumed stream to * completion (serverless safety). */ protected dispatchDecline(args: { runId: string; toolCallId: string; requestContext: RequestContext; memory: { thread: string; resource: string; }; }): Promise<void>; /** * Check if an adapter is registered for the given platform. */ hasAdapter(platform: string): boolean; /** * Get the underlying Chat SDK instance. * Available after Mastra initialization. Use this to register additional * event handlers or access adapter-specific methods. * * @example * ```ts * agent.getChannels()?.sdk?.onReaction((thread, reaction) => { * console.log('Reaction received:', reaction); * }); * ``` */ get sdk(): Chat | null; /** * Initialize the Chat SDK, register handlers, and start gateway listeners. * Called by Mastra.addAgent after the server is ready. */ initialize(mastra: Mastra): Promise<void>; /** * Returns API routes for receiving webhook events from each adapter. * One POST route per adapter at `/api/agents/{agentId}/channels/{platform}/webhook`. * Skips platforms that are externally managed (e.g., by SlackProvider). */ getWebhookRoutes(): ApiRoute[]; /** * Handle a webhook event from an external source (e.g., SlackProvider). * Use this when a ChannelProvider manages its own routes but wants AgentChannels * to process the actual message handling (threading, agent responses, etc.). * * @param platform - The platform name (e.g., 'slack') * @param request - The raw HTTP request * @param options - Optional execution context for serverless environments * @returns The response from the Chat SDK webhook handler */ handleWebhookEvent(platform: string, request: Request, options?: { waitUntil?: (p: Promise<unknown>) => void; }): Promise<Response>; /** * Returns channel input processors (e.g. system prompt injection). * * - Skipped entirely when `channels.threadContext.addSystemMessage` is `false`. * - Skipped if the user already added a processor with the same id. */ getInputProcessors(configuredProcessors?: InputProcessorOrWorkflow[]): InputProcessor[]; /** Whether the Slack adapter opted into `generativeUI` (the only platform it supports). */ private get generativeUIEnabled(); /** * Returns channel output processors that render the agent's stream to the * originating chat platform. The processor resolves its render context from * the inbound `requestContext` marker set by `processChatMessage` when * present, and otherwise reconstructs it from the run's thread via the bound * `AgentChannels` (so schedule / Studio / custom-UI runs on a channel-backed * thread still post back). Non-channel runs pass through untouched. * * Skipped if the user already added a processor with the same id. */ /** * @deprecated No longer needed — `AgentChannels` no longer holds stateful resources that require cleanup. * Kept as a no-op for backwards compatibility with existing `ChannelProvider` implementations. */ close(): void; getOutputProcessors(configuredProcessors?: OutputProcessorOrWorkflow[]): OutputProcessor[]; /** * Returns generic channel tools (add_reaction, remove_reaction) that resolve * the target adapter from the current request context. * * These are not injected into the agent automatically — pass them explicitly * if the agent should react to channel messages: * * ```ts * const agent = new Agent({ * channels, * tools: { ...channels.getTools() }, * }); * ``` * * Replies don't need a tool: the agent's response streams back to the * channel through the output processor. */ getTools(): Record<string, unknown>; /** * Resolve the adapter and chat thread for the current conversation. A run * started by an inbound message carries them on request context. Any other * run (a schedule, Studio, a woken run) finds them through its memory * thread's persisted channel coordinates, the same way * `ChatChannelOutputProcessor` posts its reply. */ private getAdapterFromContext; /** * Derive the three per-event shapes we hand off to downstream systems from one set of * inputs. Keeping this in one place ensures the LLM (`attributes`), input processors * (`requestContext`), and memory (`metadata`) all see consistent author / thread facts. * * - `channelContext` — goes on `requestContext` under the 'channel' key, consumed by * `ChatChannelProcessor` and other input processors. * - `attributes` — serialized as XML on the user message element the LLM sees (e.g. on * `<user messageId=... authorId=... />`). Strings only. * - `providerOptions` — written to the stored message's `content.providerMetadata` * under `mastra.channels.<platform>` so UI/query callers can read author/channel * facts off the message (e.g. show a Slack icon + author name) without unpacking * the signal envelope. The LLM ignores `providerOptions.mastra.*` since only * provider-keyed entries (openai, anthropic, …) are forwarded to the model. */ /** * Resolve the external thread id to use when looking up a Mastra thread for * a tool-approval flow. Dispatches to per-platform compat shims that work * around quirks in how adapters surface threading on inbound action events. * Add new platform branches here as their compat shims land in `./compat/*`. */ private resolveExternalThreadId; /** * Resolve the bot's current profile display name through the adapter, once per platform and bot user. * Keyed by `botUserId` because one adapter can serve several installations, each with its own bot. * Adapters may report a stale handle as `userName` (e.g. Slack `auth.test` keeps the original * username after an app rename) while inbound mentions render the current display name. */ private resolveBotDisplayName; private buildEventContext; /** * Default handler behind Chat SDK's onDirectMessage, onNewMention, and * onSubscribedMessage. Dispatches one sender's run (the message plus that * sender's earlier batched messages in `skipped`), streaming the Mastra agent * response and updating the channel message in real-time via edits. Never * throws to the host: run failures are logged or posted by `handleRunError`. */ private handleChatMessage; private handleRunError; private processChatMessage; /** A message with neither text nor attachments gives the agent nothing to run on. */ private isContentlessMessage; /** * Route attachments based on `inlineMedia` config (see DEFAULT_INLINE_MEDIA_TYPES). * Inline types are sent as file parts (the LLM adapter converts image/* to * image content automatically). Non-inline text-like types (text/*, JSON, * YAML, XML, …) that come with an authenticated `fetchData` are decoded and * sent as text. Other non-inline types are described as text * metadata so the agent is aware of them without crashing models that * reject unsupported media (e.g. OpenAI rejects video/mp4). When the agent * has a writable workspace, those with `fetchData` are saved there and the * description carries the workspace path instead of the URL. */ private attachmentsToParts; /** * The agent's workspace filesystem when one is configured and writable, and * the workspace lets the agent write files without approval. Saving follows * the same policy as the write tool so a deployer who disables or gates * writes doesn't get channel participants' files written anyway. */ private resolveAttachmentFilesystem; /** * Save an attachment under `channel-attachments/<hash>/<name>` (inside the * first writable mount of a composite filesystem) and return * the path, or undefined when it cannot be downloaded or written, or when * it would push the folder over `maxAttachmentStorageBytes`. The folder * hashes the URL so history walks reuse a saved file without refetching; * attachments without a URL hash their downloaded bytes, so different * files never share a path. */ private saveAttachmentToWorkspace; /** * Build the history rows, in order: root, gap marker (when messages were * omitted), then the recent window oldest first. Each row carries the same * attribution the live path emits plus `source: 'thread-history'`, its * platform timestamp, and its attachments routed like live attachments. */ private buildThreadHistorySignals; /** * Persist the history rows into the Mastra thread without waking the agent. * Returns `false` when the rows were not persisted (the agent has no * memory, or the write failed), in which case the caller falls back to the * legacy text block. History is only collected on the first mention; the * thread is subscribed right after, so a failure here is the only chance * the agent gets at this context. `buildSignals` downloads attachments, so * it is only called once persistence is known to be possible. A failure * building the rows logs and still returns `true`: the legacy block could * not be built from the same input either. The deterministic row ids keep * deliveries that race before the subscription lands from duplicating rows. * * The rows are written straight to memory in one batch rather than sent * through `agent.sendSignal(..., { behavior: 'persist' })`: the runtime * rebroadcasts every persisted signal as a short pseudo-run, and a thread * subscriber that observes it marks the thread active, so the trigger that * follows would attach to that pseudo-run instead of waking the agent. * * Overridden by `AgentControllerChannels`, which resolves memory through its * session's agent and never reads `this.agent`. */ protected persistThreadHistorySignals(args: { /** Builds the rows (downloads attachments); call only after deciding persistence is possible. */ buildSignals: () => Promise<AgentSignalInput[]>; requestContext: RequestContext; thread: StorageThreadType; memory: { thread: string; resource: string; }; /** Platform and message identifiers for log lines. */ logContext: ThreadHistoryLogContext; }): Promise<boolean>; /** * Builds the rows and writes them to `memory` in one batch. Never throws. * Returns `false` only when the write itself failed. The rows may then be * missing, so the caller falls back to the legacy text block; a store that * applied part of the batch before failing shows some history twice, which * beats losing it. */ protected saveThreadHistorySignals(args: { buildSignals: () => Promise<AgentSignalInput[]>; memory: MastraMemory; target: { thread: string; resource: string; }; logContext: ThreadHistoryLogContext; }): Promise<boolean>; /** * Build the per-event render dependencies stashed on `requestContext` for * `ChatChannelOutputProcessor`. Captures the adapter, driver mode, * tool-display config, approval-card stash callbacks, and the typing-status * wrapper as a callable so the processor can apply it after the queue is * created. The returned object is plain data — no streams, no promises — * so it's safe to stash on `requestContext` for the processor to read later. * * @internal Used by `processChatMessage` and the approve/decline paths. */ _buildRenderContext(chatThread: Thread, platform: string, { approvalContext, requesterId, }?: { approvalContext?: { toolCallId: string; messageId: string; }; requesterId?: string; }): ChatChannelRenderContext; /** * Whether a `tool-call-approval` chunk for `toolName` should render * Approve/Deny controls in the chat. The base class always renders them; * subclasses that resolve approval policy themselves (e.g. an agent * controller auto-approving `allow` tools) return `false` when no human * decision is actually pending. * * @internal */ shouldRenderToolApproval(_requestContext: RequestContext | undefined, _toolName: string): Promise<boolean>; /** * Reconstruct a {@link ChatChannelRenderContext} for a Mastra thread that is * backed by a channel, without an inbound platform event. * * The inbound webhook paths (`processChatMessage`, approve/decline) stash a * render context on `requestContext` because they already hold the live * `Thread` handle from `event.thread`. Runs that did NOT originate from a * platform message (schedule fires, Studio, custom UI, user code) have no such * handle, so `ChatChannelOutputProcessor` calls this to rebuild it from the * thread's persisted channel coordinates. * * Returns `null` when the thread is not channel-backed (no `channel_platform` * metadata) or its platform adapter isn't configured on this instance — the * processor then passes the run through untouched. * * Delegates to the same {@link _buildRenderContext} used by the inbound paths, * so both paths produce an identical render context (single source of truth). * The only per-fire inputs are `platform` (a persisted string) and the live * `Thread` handle, which the Chat SDK materializes from the stored external id * via `chat.thread(externalThreadId)`. */ buildRenderContextForThread(threadId: string): Promise<ChatChannelRenderContext | null>; /** * The channel context and render context for a run on a channel-backed * thread that did not start from a platform message. The channel context is * built exactly as an inbound message's would be, around the thread's last * sender, so `ChatChannelProcessor` gives both kinds of run the same system * prompt and a host switching between them keeps its prompt cache. */ buildChannelContextForThread(threadId: string): Promise<{ channel: ChannelContext; render: ChatChannelRenderContext; } | null>; private loadChannelThread; /** * Remembers who last wrote in a channel-backed thread and whether it is a * DM, so a run on it that didn't start from a message gets the same prompt * and replies the same way an inbound one would (see * {@link buildChannelContextForThread}). Writes only when either changes. */ private rememberThreadFacts; /** * Normalize the per-adapter `streaming` option (`boolean | { updateIntervalMs? }`) * into a flat `{ enabled, options }` shape so call-sites don't have to * re-derive both from the raw union. */ private resolveStreaming; /** * Pass-through async generator that yields chunks unchanged but emits * typing-status updates (`startTyping`) along the way. Lives outside the * drivers so both drivers benefit from the same dedup + gate logic. * * The streaming driver flips `typingGate.active = true` while a * `StreamingPlan` post is in flight — Slack's `assistant.threads.setStatus` * (what `startTyping` maps to) only auto-clears on `chat.postMessage`, not * on `chat.stopStream`, so a status set during streaming would stick after * the run ends. The static driver leaves the gate `false` so typing works * normally in cards/hidden modes. * * When the run's stream ends, an empty status is sent to clear any status * this run set, so runs that end without posting a message (e.g. terminated * by `stopWhen` on a tool call, or aborted) don't leave a stale status * pinned to the thread. */ private withTypingStatus; /** * Find a pending tool approval in Memory for a click that missed the * in-memory card cache (e.g. after a rebuild or restart). Results are cached * per card and concurrent lookups for the same card share one read, so * repeated clicks cannot each force a history scan. */ private lookupPersistedApproval; /** * Whether a card's tool call was answered elsewhere: its run is suspended * again, but on other tool calls. A target from the lookup cache or from * posting the card can outlive its approval, and a history scan can race * another instance's answer; a `DurableAgent` resume would then apply the old * answer to the run's newer tool call. One read of the thread's suspended * runs, no history scan. * * A run that is not suspended (finished, aborted, still resuming, or whose * suspension is not stored yet) is left to the resume, which reports those * cases itself. This matches core's own rule for a stale `toolCallId`. */ private isAnsweredElsewhere; /** The cached entry for a card, or undefined when missing or expired. */ private getApprovalLookup; private setApprovalLookup; /** * Read history newest-first, one page at a time, until the approval and the * user turn that triggered it are found. Storage cannot filter on the nested * `pendingToolApprovals` entries, so this scans. There is deliberately no page * cap: any fixed limit would strand approvals behind it again (#29186). The * cost is bounded instead by `lookupPersistedApproval`, which runs this at * most once per card per `APPROVAL_LOOKUP_TTL_MS` for pending or answered * approvals and per `APPROVAL_LOOKUP_MISSING_TTL_MS` for unknown ones. */ private readPersistedApproval; /** * Look up a channel-backed Mastra thread and retain the store/metadata needed * by the create path when no mapping exists. */ private findThreadMapping; /** * Resolves an existing Mastra thread for the given external IDs, or creates one. */ private getOrCreateThread; /** * Generate generic channel tools that resolve the adapter from request context. * Tool names are platform-agnostic (e.g. `add_reaction`, not `discord_add_reaction`). */ private makeChannelTools; /** * Persistent reconnection loop for Gateway-based adapters (e.g. Discord). */ private startGatewayLoop; /** * Resolve the tool-display mode for a run. * * - `'timeline'` / `'grouped'` push `task_update` chunks into a streaming * Plan widget, so they require `streaming: true`. Without streaming we * fall back to `'cards'`. * - `'cards'` posts discrete Block-Kit cards via `chatThread.post`/`edit`, * which the streaming driver doesn't render (everything inside a * `StreamingPlan` post is one message). With streaming enabled we fall * back to `'timeline'`. * * Both fallbacks log a one-time warning per platform so the misconfiguration * is visible without spamming on every run. */ private resolveToolDisplay; /** * Single entry point for channel logs. `fields.platform` also prefixes the * message as `[platform]`, and `fields.error` is normalized so it serializes * with its message, code and cause instead of as `{}`. */ protected log(level: 'info' | 'warn' | 'error' | 'debug', message: string, fields?: ChannelLogContext): void; } export {}; //# sourceMappingURL=agent-channels.d.ts.map