UNPKG

@mastra/core

Version:
204 lines (203 loc) • 8.22 kB
import { Ci as NotificationsStorage, Co as resolveDeliveryFailureUpdate, Si as InMemoryNotificationsStorage, So as defaultNotificationDeliveryDecision, _o as notificationSummaryContents, bo as readNotificationRoutingRequirement, go as notificationSignalMetadata, ho as notificationSignalAttributes, mo as createNotificationSummarySignal, po as createNotificationSignal, vo as notificationSummarySignalMetadata, wi as dispatchDueNotifications, wo as resolveNotificationDeliveryDecision, xo as MAX_NOTIFICATION_DELIVERY_ATTEMPTS, yo as summarizeNotifications } from "../run-registry-Ca8idv6o.js"; import { r as createTool } from "../tool-CXFwLwlu.js"; import { z } from "zod/v4"; // src/notifications/tool.ts const notificationActionSchema = z.object({ action: z.enum([ "list", "read", "markSeen", "dismiss", "archive", "search" ]), threadId: z.string().optional(), id: z.string().optional(), status: z.enum([ "pending", "delivered", "seen", "dismissed", "archived", "discarded", "failed" ]).optional(), priority: z.enum([ "low", "medium", "high", "urgent" ]).optional(), source: z.string().optional(), query: z.string().optional(), limit: z.number().int().positive().optional().describe("Maximum records to return. Defaults to 20; the response reports hasMore when more remain.") }).superRefine((input, ctx) => { if (input.action === "search" && !input.query?.trim()) ctx.addIssue({ code: "custom", path: ["query"], message: "notification-inbox search requires query" }); if ((input.action === "markSeen" || input.action === "dismiss" || input.action === "archive") && !input.id?.trim()) ctx.addIssue({ code: "custom", path: ["id"], message: `notification-inbox ${input.action} requires id` }); }); const isReadable = (notification) => notification.status === "pending" || notification.status === "delivered"; /** * Records a default list shows and then marks seen. `failed` records ran out of delivery * attempts, so the inbox listing is the only place the recipient learns delivery gave up; * marking them seen once shown keeps them from reappearing on every list. */ const isUnseen = (notification) => isReadable(notification) || notification.status === "failed"; const DEFAULT_LIST_LIMIT = 20; /** * Agent-facing projection for list/search results. `metadata` and `payload` are internal * bookkeeping (content hashes, raw source payloads) that can be several KB per record and * dominate the token cost of an inbox listing. */ const toInboxProjection = (notification) => { const { metadata: _metadata, payload: _payload, ...projection } = notification; return projection; }; /** * Viewing a notification marks it as seen: any pending/delivered/failed notification returned to * the agent transitions to 'seen' so the pending backlog drains as the agent triages it. * Without this, summarized notifications stayed 'pending' forever (the summary digest is * consumed without any per-record transition) and every list returned the full backlog. * Returns the ids of the records whose status write succeeded; a failed write leaves the * page readable with its stored statuses rather than failing the whole listing. */ async function markViewedNotificationsSeen({ threadId, notifications, storage }) { const ids = notifications.filter(isUnseen).map((notification) => notification.id); if (ids.length === 0) return /* @__PURE__ */ new Set(); try { const updated = await storage.updateNotificationsStatus({ threadId, ids, status: "seen" }); return new Set(updated.map((notification) => notification.id)); } catch { return /* @__PURE__ */ new Set(); } } async function deliverNotifications({ notifications, storage, context }) { let delivered = 0; let markedSeen = 0; let unavailable = 0; let alreadyRead = 0; for (const notification of notifications) { if (!isReadable(notification)) { alreadyRead += 1; continue; } const agentId = notification.agentId ?? context?.agent?.agentId; const resourceId = notification.resourceId ?? context?.agent?.resourceId; const mastra = context?.mastra; const agent = agentId && typeof mastra?.getAgentById === "function" ? await mastra.getAgentById(agentId) : void 0; if (agent && resourceId && !notification.deliveredSignalId) { const signal = createNotificationSignal({ ...notification, status: "delivered" }); const result = agent.sendSignal(signal, { resourceId, threadId: notification.threadId }); await result.persisted; await storage.updateNotification({ threadId: notification.threadId, id: notification.id, status: "seen", deliveredSignalId: result.signal.id }); delivered += 1; continue; } if (notification.deliveredSignalId) { await storage.updateNotification({ threadId: notification.threadId, id: notification.id, status: "seen" }); markedSeen += 1; } else unavailable += 1; } return { message: delivered > 0 ? `${delivered} notification${delivered === 1 ? "" : "s"} will now be delivered.` : "No unread notifications needed delivery.", delivered, markedSeen, unavailable, alreadyRead }; } function createNotificationInboxTool({ storage }) { return createTool({ id: "notification-inbox", description: "Inspect and manage the current thread notification inbox. Use this to list unread notifications, read full details after a summary, mark notifications seen, dismiss, archive, or search old notifications. Listing, reading, or searching automatically marks the returned unread notifications as seen; list defaults to unread and failed-delivery notifications unless a status is given.", inputSchema: notificationActionSchema, execute: async (input, context) => { const threadId = input.threadId ?? context?.agent?.threadId; if (!threadId) throw new Error("notification-inbox requires a threadId"); if (input.action === "list" || input.action === "search") { const limit = input.limit ?? DEFAULT_LIST_LIMIT; const notifications = await storage.listNotifications({ threadId, status: input.status ?? (input.action === "list" ? [ "pending", "delivered", "failed" ] : void 0), priority: input.priority, source: input.source, ...input.action === "search" ? { search: input.query } : {}, limit: limit + 1 }); const page = notifications.slice(0, limit); const seenIds = await markViewedNotificationsSeen({ threadId, notifications: page, storage }); return { notifications: page.map((notification) => seenIds.has(notification.id) && notification.status !== "failed" ? { ...toInboxProjection(notification), status: "seen" } : toInboxProjection(notification)), hasMore: notifications.length > limit, markedSeen: seenIds.size }; } if (input.action === "read") { const notifications = input.id ? [await storage.getNotification({ threadId, id: input.id })] : await storage.listNotifications({ threadId, status: input.status ?? ["pending", "delivered"], priority: input.priority, source: input.source, limit: input.limit ?? DEFAULT_LIST_LIMIT }); if (input.id && !notifications[0]) throw new Error(`Notification ${input.id} was not found for thread ${threadId}`); return deliverNotifications({ notifications: notifications.filter((notification) => Boolean(notification)), storage, context }); } return { notification: await storage.updateNotification({ threadId, id: input.id, status: { markSeen: "seen", dismiss: "dismissed", archive: "archived" }[input.action] }) }; } }); } export { InMemoryNotificationsStorage, MAX_NOTIFICATION_DELIVERY_ATTEMPTS, NotificationsStorage, createNotificationInboxTool, createNotificationSignal, createNotificationSummarySignal, defaultNotificationDeliveryDecision, dispatchDueNotifications, notificationSignalAttributes, notificationSignalMetadata, notificationSummaryContents, notificationSummarySignalMetadata, readNotificationRoutingRequirement, resolveDeliveryFailureUpdate, resolveNotificationDeliveryDecision, summarizeNotifications }; //# sourceMappingURL=index.js.map