UNPKG

@mastra/core

Version:
1 lines • 13.3 kB
{"version":3,"file":"index.cjs","names":["z","createNotificationSignal","createTool"],"sources":["../../src/notifications/tool.ts"],"sourcesContent":["import { z } from 'zod/v4';\nimport { createTool } from '../tools';\nimport type { ToolExecutionContext } from '../tools';\nimport { createNotificationSignal } from './signals';\nimport type { NotificationsStorage } from './storage';\nimport type { NotificationRecord, NotificationStatus } from './types';\n\nconst notificationActionSchema = z\n .object({\n action: z.enum(['list', 'read', 'markSeen', 'dismiss', 'archive', 'search']),\n threadId: z.string().optional(),\n id: z.string().optional(),\n status: z.enum(['pending', 'delivered', 'seen', 'dismissed', 'archived', 'discarded', 'failed']).optional(),\n priority: z.enum(['low', 'medium', 'high', 'urgent']).optional(),\n source: z.string().optional(),\n query: z.string().optional(),\n limit: z\n .number()\n .int()\n .positive()\n .optional()\n .describe('Maximum records to return. Defaults to 20; the response reports hasMore when more remain.'),\n })\n .superRefine((input, ctx) => {\n if (input.action === 'search' && !input.query?.trim()) {\n ctx.addIssue({ code: 'custom', path: ['query'], message: 'notification-inbox search requires query' });\n }\n if (\n (input.action === 'markSeen' || input.action === 'dismiss' || input.action === 'archive') &&\n !input.id?.trim()\n ) {\n ctx.addIssue({ code: 'custom', path: ['id'], message: `notification-inbox ${input.action} requires id` });\n }\n });\n\ntype NotificationInboxAction = z.infer<typeof notificationActionSchema>;\n\ntype NotificationToolAgent = {\n sendSignal: (\n signal: ReturnType<typeof createNotificationSignal>,\n target: { resourceId: string; threadId: string },\n ) => { signal: ReturnType<typeof createNotificationSignal>; persisted?: Promise<void> };\n};\n\nconst isReadable = (notification: NotificationRecord) =>\n notification.status === 'pending' || notification.status === 'delivered';\n\n/**\n * Records a default list shows and then marks seen. `failed` records ran out of delivery\n * attempts, so the inbox listing is the only place the recipient learns delivery gave up;\n * marking them seen once shown keeps them from reappearing on every list.\n */\nconst isUnseen = (notification: NotificationRecord) => isReadable(notification) || notification.status === 'failed';\n\nconst DEFAULT_LIST_LIMIT = 20;\n\n/**\n * Agent-facing projection for list/search results. `metadata` and `payload` are internal\n * bookkeeping (content hashes, raw source payloads) that can be several KB per record and\n * dominate the token cost of an inbox listing.\n */\nconst toInboxProjection = (notification: NotificationRecord) => {\n const { metadata: _metadata, payload: _payload, ...projection } = notification;\n return projection;\n};\n\n/**\n * Viewing a notification marks it as seen: any pending/delivered/failed notification returned to\n * the agent transitions to 'seen' so the pending backlog drains as the agent triages it.\n * Without this, summarized notifications stayed 'pending' forever (the summary digest is\n * consumed without any per-record transition) and every list returned the full backlog.\n * Returns the ids of the records whose status write succeeded; a failed write leaves the\n * page readable with its stored statuses rather than failing the whole listing.\n */\nasync function markViewedNotificationsSeen({\n threadId,\n notifications,\n storage,\n}: {\n threadId: string;\n notifications: NotificationRecord[];\n storage: NotificationsStorage;\n}): Promise<Set<string>> {\n const ids = notifications.filter(isUnseen).map(notification => notification.id);\n if (ids.length === 0) return new Set();\n try {\n const updated = await storage.updateNotificationsStatus({ threadId, ids, status: 'seen' });\n return new Set(updated.map(notification => notification.id));\n } catch {\n return new Set();\n }\n}\n\nasync function deliverNotifications({\n notifications,\n storage,\n context,\n}: {\n notifications: NotificationRecord[];\n storage: NotificationsStorage;\n context: ToolExecutionContext;\n}) {\n let delivered = 0;\n let markedSeen = 0;\n let unavailable = 0;\n let alreadyRead = 0;\n\n for (const notification of notifications) {\n if (!isReadable(notification)) {\n alreadyRead += 1;\n continue;\n }\n\n const agentId = notification.agentId ?? context?.agent?.agentId;\n const resourceId = notification.resourceId ?? context?.agent?.resourceId;\n const mastra = context?.mastra;\n const agent =\n agentId && typeof mastra?.getAgentById === 'function' ? await mastra.getAgentById(agentId) : undefined;\n\n if (agent && resourceId && !notification.deliveredSignalId) {\n const signal = createNotificationSignal({ ...notification, status: 'delivered' });\n const result = (agent as NotificationToolAgent).sendSignal(signal, {\n resourceId,\n threadId: notification.threadId,\n });\n await result.persisted;\n await storage.updateNotification({\n threadId: notification.threadId,\n id: notification.id,\n status: 'seen',\n deliveredSignalId: result.signal.id,\n });\n delivered += 1;\n continue;\n }\n\n if (notification.deliveredSignalId) {\n await storage.updateNotification({ threadId: notification.threadId, id: notification.id, status: 'seen' });\n markedSeen += 1;\n } else {\n // No agent/resourceId to deliver through and no prior signal: the content never reached\n // the agent, so leave it pending rather than silently consuming it.\n unavailable += 1;\n }\n }\n\n const message =\n delivered > 0\n ? `${delivered} notification${delivered === 1 ? '' : 's'} will now be delivered.`\n : 'No unread notifications needed delivery.';\n\n return { message, delivered, markedSeen, unavailable, alreadyRead };\n}\n\nexport function createNotificationInboxTool({ storage }: { storage: NotificationsStorage }) {\n return createTool({\n id: 'notification-inbox',\n description:\n '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.',\n inputSchema: notificationActionSchema,\n execute: async (input: NotificationInboxAction, context) => {\n const threadId = input.threadId ?? context?.agent?.threadId;\n if (!threadId) {\n throw new Error('notification-inbox requires a threadId');\n }\n\n if (input.action === 'list' || input.action === 'search') {\n // Fetch one past the page so the response can report whether the inbox has more.\n const limit = input.limit ?? DEFAULT_LIST_LIMIT;\n const notifications = await storage.listNotifications({\n threadId,\n // Default list to unread and failed: auto-seen bumps updatedAt (the sort key), so listing every\n // status would keep returning the page just viewed. Search spans all statuses.\n status: input.status ?? (input.action === 'list' ? ['pending', 'delivered', 'failed'] : undefined),\n priority: input.priority,\n source: input.source,\n ...(input.action === 'search' ? { search: input.query! } : {}),\n limit: limit + 1,\n });\n const page = notifications.slice(0, limit);\n const seenIds = await markViewedNotificationsSeen({ threadId, notifications: page, storage });\n return {\n // A failed record keeps reporting `failed` on the listing that surfaces it, so the\n // recipient sees delivery gave up; storage now holds it as seen.\n notifications: page.map(notification =>\n seenIds.has(notification.id) && notification.status !== 'failed'\n ? { ...toInboxProjection(notification), status: 'seen' as const }\n : toInboxProjection(notification),\n ),\n hasMore: notifications.length > limit,\n markedSeen: seenIds.size,\n };\n }\n\n if (input.action === 'read') {\n const notifications = input.id\n ? [await storage.getNotification({ threadId, id: input.id })]\n : await storage.listNotifications({\n threadId,\n status: input.status ?? ['pending', 'delivered'],\n priority: input.priority,\n source: input.source,\n limit: input.limit ?? DEFAULT_LIST_LIMIT,\n });\n if (input.id && !notifications[0])\n throw new Error(`Notification ${input.id} was not found for thread ${threadId}`);\n return deliverNotifications({\n notifications: notifications.filter((notification): notification is NotificationRecord =>\n Boolean(notification),\n ),\n storage,\n context,\n });\n }\n\n const statusByAction = {\n markSeen: 'seen',\n dismiss: 'dismissed',\n archive: 'archived',\n } satisfies Record<'markSeen' | 'dismiss' | 'archive', NotificationStatus>;\n\n return {\n notification: await storage.updateNotification({\n threadId,\n // The schema refine guarantees id for these actions; superRefine does not narrow the type.\n id: input.id!,\n status: statusByAction[input.action],\n }),\n };\n },\n });\n}\n"],"mappings":";;;;;AAOA,MAAM,2BAA2BA,OAAAA,EAC9B,OAAO;CACN,QAAQA,OAAAA,EAAE,KAAK;EAAC;EAAQ;EAAQ;EAAY;EAAW;EAAW;CAAQ,CAAC;CAC3E,UAAUA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,IAAIA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CACxB,QAAQA,OAAAA,EAAE,KAAK;EAAC;EAAW;EAAa;EAAQ;EAAa;EAAY;EAAa;CAAQ,CAAC,CAAC,CAAC,SAAS;CAC1G,UAAUA,OAAAA,EAAE,KAAK;EAAC;EAAO;EAAU;EAAQ;CAAQ,CAAC,CAAC,CAAC,SAAS;CAC/D,QAAQA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAC5B,OAAOA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,OAAOA,OAAAA,EACJ,OAAO,CAAC,CACR,IAAI,CAAC,CACL,SAAS,CAAC,CACV,SAAS,CAAC,CACV,SAAS,2FAA2F;AACzG,CAAC,CA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