@mastra/core
Version:
220 lines (219 loc) • 8.8 kB
JavaScript
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_run_registry = require("../run-registry-BrKoxzT0.cjs");
const require_tool = require("../tool-BMl4Lb5_.cjs");
let zod_v4 = require("zod/v4");
// src/notifications/tool.ts
const notificationActionSchema = zod_v4.z.object({
action: zod_v4.z.enum([
"list",
"read",
"markSeen",
"dismiss",
"archive",
"search"
]),
threadId: zod_v4.z.string().optional(),
id: zod_v4.z.string().optional(),
status: zod_v4.z.enum([
"pending",
"delivered",
"seen",
"dismissed",
"archived",
"discarded",
"failed"
]).optional(),
priority: zod_v4.z.enum([
"low",
"medium",
"high",
"urgent"
]).optional(),
source: zod_v4.z.string().optional(),
query: zod_v4.z.string().optional(),
limit: zod_v4.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 = require_run_registry.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 require_tool.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]
}) };
}
});
}
exports.InMemoryNotificationsStorage = require_run_registry.InMemoryNotificationsStorage;
exports.MAX_NOTIFICATION_DELIVERY_ATTEMPTS = require_run_registry.MAX_NOTIFICATION_DELIVERY_ATTEMPTS;
exports.NotificationsStorage = require_run_registry.NotificationsStorage;
exports.createNotificationInboxTool = createNotificationInboxTool;
exports.createNotificationSignal = require_run_registry.createNotificationSignal;
exports.createNotificationSummarySignal = require_run_registry.createNotificationSummarySignal;
exports.defaultNotificationDeliveryDecision = require_run_registry.defaultNotificationDeliveryDecision;
exports.dispatchDueNotifications = require_run_registry.dispatchDueNotifications;
exports.notificationSignalAttributes = require_run_registry.notificationSignalAttributes;
exports.notificationSignalMetadata = require_run_registry.notificationSignalMetadata;
exports.notificationSummaryContents = require_run_registry.notificationSummaryContents;
exports.notificationSummarySignalMetadata = require_run_registry.notificationSummarySignalMetadata;
exports.readNotificationRoutingRequirement = require_run_registry.readNotificationRoutingRequirement;
exports.resolveDeliveryFailureUpdate = require_run_registry.resolveDeliveryFailureUpdate;
exports.resolveNotificationDeliveryDecision = require_run_registry.resolveNotificationDeliveryDecision;
exports.summarizeNotifications = require_run_registry.summarizeNotifications;
//# sourceMappingURL=index.cjs.map