UNPKG

@mastra/core

Version:
306 lines (305 loc) • 12.5 kB
import { $c as ChannelSessionRejectedError, Gc as AgentChannels } from "./run-registry-Ca8idv6o.js"; import { i as MastraFGAPermissions } from "./ee-iTj2bRDt-By_B9ngH.js"; // src/channels/agent-controller-channels.ts /** * Runs an AgentController inside chat channels (Slack, Discord, ...). * * Extends {@link AgentChannels} so all inbound machinery (thread mapping, * history, attachments, event context) and all outbound rendering * (`ChatChannelOutputProcessor` with native streaming, tool cards, typing * status) are reused unchanged. Only the dispatch seams differ: instead of * routing into a bare agent, inbound messages route into a controller * `Session` — one durable session per chat thread, keyed by the mapped * Mastra thread's `resourceId`. * * V1 targets long-lived servers: controller sessions are in-memory objects * and do not survive process restarts. */ var AgentControllerChannels = class extends AgentChannels { controller = null; /** * Session resourceIds whose adapter can't render approval buttons, so their * runs must auto-approve tools (`requireToolApproval: false`) instead of * parking forever on an approval nobody can answer. Kept outside session * state on purpose: state is validated against the controller's * `stateSchema`, which would strip (or reject) an injected flag. Refreshed * on every inbound message; in-memory only, matching the v1 long-lived * server scope. */ autoApproveResourceIds = /* @__PURE__ */ new Set(); /** See {@link AgentControllerChannelsConfig.onSessionStart}. */ onSessionStart; /** See {@link AgentControllerChannelsConfig.resolveSession}. */ resolveSession; /** See {@link AgentControllerChannelsConfig.onStaleToolApproval}. */ onStaleToolApproval; /** * One start-hook invocation per session resourceId. A map of promises rather * than a set of ids: concurrent messages on a new thread must all WAIT for * the hook, not just skip it, or the losers dispatch on an unconfigured * session. In-memory, matching the v1 scope where sessions themselves don't * survive a restart: a session rebuilt after a restart is a new session and * gets configured again. Keyed by session rather than by thread because a * `resolveSession` host can hand back a different session for the same thread * (per-principal routing), and each of those is a session that has never been * configured. */ sessionStartRuns = /* @__PURE__ */ new WeakMap(); constructor(config) { super(config); this.onSessionStart = config.onSessionStart; this.resolveSession = config.resolveSession; this.onStaleToolApproval = config.onStaleToolApproval; } /** @internal Called by AgentController's constructor to bind itself. */ __setController(controller) { this.controller = controller; } /** * @internal Consulted by the controller's run-option builder: `true` when * the session's channel adapter can't render approval buttons and tool * calls must auto-approve (the session-side equivalent of the base agent * path's `autoResumeSuspendedTools`). */ __isAutoApproveResource(resourceId) { return this.autoApproveResourceIds.has(resourceId); } /** * @internal No-op override. The controller attaches this instance to its * mode agents via `Agent.setChannels`, which calls `__setAgent(agent)` — * with multiple mode agents the last one would win. Every `this.agent` use * is overridden in this subclass, so keep the base field unset rather than * holding a misleading ref. */ __setAgent(_agent) {} getOwnerId() { return this.controller?.id ?? null; } getWebhookBasePath() { return `/api/agent-controllers/${this.getOwnerId()}`; } getMastra() { return this.controller?.getMastra(); } /** * One session per chat thread: unless the user supplied a custom * `resolveResourceId`, key new Mastra threads (and therefore controller * sessions) off the platform + external thread id. */ resolveChannelResourceId(args) { const base = super.resolveChannelResourceId(args); if (typeof base === "function") return base; return `channel:${args.chatThread.id}`; } /** * Route an inbound chat message into the controller session bound to this * chat thread. Output renders back to the platform through the channels * output processor: the `requestContext` built by the base class (carrying * the channel context and render context) flows through the session into * the run. */ async dispatchInboundMessage(args) { const { signalContents, attributes, signalMetadata, providerOptions, requestContext, thread, autoResumeSuspendedTools } = args; const session = await this.getSessionForThread(thread, requestContext); const sessionResourceId = thread.resourceId; if (autoResumeSuspendedTools) this.autoApproveResourceIds.add(sessionResourceId); else this.autoApproveResourceIds.delete(sessionResourceId); await session.sendSignal({ type: "user", tagName: "user", contents: signalContents, attributes, ...Object.keys(signalMetadata).length > 0 ? { metadata: signalMetadata } : {}, providerOptions }, { requestContext, requireDelivery: true, untilIdle: true }).accepted; } /** * Persist first-mention thread history into the controller session's own * thread. The session is resolved once, before the rows are built, and is * not guarded: a `resolveSession` refusal or resource mismatch propagates * out of the hook to the handler's error boundary exactly as it would from * the trigger dispatch a moment later. `onSessionStart` therefore runs * before the history rows rather than at trigger dispatch. * * Rows are written straight to the session agent's memory (see the base * class for why `session.sendSignal` cannot be used). Like the base class, * a session agent without memory or a failed write returns `false` so the * history still reaches the agent as the legacy text block. */ async persistThreadHistorySignals(args) { const session = await this.getSessionForThread(args.thread, args.requestContext); const memory = await session.machinery.getAgent().getMemory({ requestContext: args.requestContext }); if (!memory) return false; return this.saveThreadHistorySignals({ buildSignals: args.buildSignals, memory, target: { thread: session.thread.getId() ?? args.memory.thread, resource: session.identity.getResourceId() }, logContext: args.logContext }); } /** * Resolve an approval-card "approve" action against the controller session's * parked tool-approval gate. The run engine — awaiting the gate inside its * stream-consumer loop — performs the actual resume itself and keeps * consuming, so the continuation renders through the output processor. */ async dispatchApproval(args) { await this.respondToSessionApproval({ decision: "approve", ...args }); } /** * Resolve an approval-card "deny" action against the controller session's * parked tool-approval gate (see {@link dispatchApproval}). */ async dispatchDecline(args) { await this.respondToSessionApproval({ decision: "decline", ...args }); } /** * Shared approve/decline path. Never calls the session's internal * `approveToolCall`/`declineToolCall` executors directly — the engine parked * at the gate owns the resume. `respondToToolApproval` is a silent no-op * when nothing is armed or the toolCallId mismatches, so staleness is * pre-checked explicitly (an armed gate does not survive process restarts, * so restart-recovered approvals are always stale — consistent with the * v1 long-lived-server scope). */ async respondToSessionApproval({ decision, runId, toolCallId, requestContext, memory }) { const session = await this.getSessionForThread({ id: memory.thread, resourceId: memory.resource }, requestContext, { bindThread: false }); if (!(session.thread.getId() === memory.thread) || !session.approval.isArmed({ toolCallId })) { this.log("info", `Ignoring stale tool ${decision === "approve" ? "approval" : "denial"} action (no matching parked approval)`, { threadId: memory.thread, toolCallId }); await this.onStaleToolApproval?.({ decision, toolCallId, runId, currentRunId: session.getCurrentRunId(), requestContext, memory, session }); return; } session.respondToToolApproval({ decision, toolCallId, requestContext }); } /** * Get-or-create the durable controller session for a mapped channel thread * and bind it to that thread. Keyed off the thread's own `resourceId` so * pre-existing threads (custom resolveResourceId, or created before this * feature) always pass the session's thread-ownership check. */ async getSessionForThread(thread, requestContext, { bindThread = true } = {}) { const controller = this.requireController(); const channelResourceId = thread.resourceId; if (this.resolveSession || !bindThread) await controller.requireAgentControllerFGA({ permission: MastraFGAPermissions.AGENT_CONTROLLER_EXECUTE, requestContext, resourceId: channelResourceId }); if (!bindThread) { const existing = await controller.getSession(channelResourceId, requestContext); if (existing && existing.identity.getResourceId() === channelResourceId && (!this.resolveSession || existing.thread.getId() !== thread.id)) return existing; } const session = this.resolveSession ? await this.resolveChannelSession({ controller, thread, requestContext }) : await controller.createSession({ resourceId: channelResourceId, id: channelResourceId, ownerId: controller.id, ...bindThread ? { threadId: thread.id } : { resumeOnly: true }, requestContext }); if (this.resolveSession && session.identity.getResourceId() !== channelResourceId) throw new Error(`resolveSession returned a session for resourceId="${session.identity.getResourceId()}", but the mapped channel thread belongs to resourceId="${channelResourceId}". A session can only bind threads it owns — resolve the session under the thread's resourceId, or map the thread onto the session's resourceId with the channels \`resolveResourceId\` option.`); if (!bindThread) return session; if (session.thread.getId() !== thread.id) await session.thread.switch({ threadId: thread.id, requestContext }); await this.runSessionStartHook(session, thread, requestContext); return session; } /** * Only render Approve/Deny controls when the session actually arms a human * gate. `allow` tools auto-approve and `deny` tools auto-decline inside the * session run, so a card for them would offer a decision nobody is waiting * on. The session is looked up in the controller's live registry by the * run's session id; when it isn't live, controls are rendered as a fallback. * * @internal */ async shouldRenderToolApproval(requestContext, toolName) { const ctx = requestContext?.get("controller"); if (!this.controller || !ctx?.sessionId) return true; const session = await this.controller.getSession(ctx.sessionId, requestContext); if (!session) return true; return session.resolveToolApproval(toolName, requestContext) === "ask"; } /** * Call the host's resolver and tag anything it throws as a refusal. Covers * synchronous throws too — the hook may return a `Session` directly, so a * plain `.catch()` on the return value would miss them. */ async resolveChannelSession(ctx) { try { return await this.resolveSession(ctx); } catch (cause) { throw new ChannelSessionRejectedError(cause); } } /** * Run the configured session-start hook at most once per session. Fires after * the thread binding above, so a hook that persists session settings writes * them to the thread the session actually ends up on. */ async runSessionStartHook(session, thread, requestContext) { const onSessionStart = this.onSessionStart; if (!onSessionStart) return; let run = this.sessionStartRuns.get(session); if (!run) { run = (async () => { try { await onSessionStart({ session, thread, requestContext }); } catch (error) { this.log("error", "Channel session-start hook failed", { resourceId: thread.resourceId, error }); } })(); this.sessionStartRuns.set(session, run); } await run; } requireController() { if (!this.controller) throw new Error("AgentControllerChannels is not bound to an AgentController. Pass it via `channels` in AgentControllerConfig."); return this.controller; } }; export { AgentControllerChannels as t }; //# sourceMappingURL=channels-un4Kcr34.js.map