@agent-native/core 0.141.3 → 0.141.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/corpus/README.md +1 -1
  2. package/corpus/templates/analytics/.agents/skills/analysis-workspace/SKILL.md +1 -1
  3. package/corpus/templates/analytics/actions/gong-calls.ts +56 -18
  4. package/corpus/templates/analytics/changelog/2026-08-05-analytics-queries-keep-every-table-tenant-scoped.md +6 -0
  5. package/corpus/templates/analytics/changelog/2026-08-05-fixed-sign-in-and-dashboard-requests-failing-when-background.md +6 -0
  6. package/corpus/templates/analytics/changelog/2026-08-05-historical-rollups-stay-complete-while-live-events-arrive.md +6 -0
  7. package/corpus/templates/analytics/server/db/schema.ts +1 -0
  8. package/corpus/templates/analytics/server/lib/dashboard-report.ts +2 -0
  9. package/corpus/templates/analytics/server/lib/emails.ts +51 -0
  10. package/corpus/templates/analytics/server/lib/first-party-analytics-health.ts +8 -12
  11. package/corpus/templates/analytics/server/lib/first-party-analytics-rollups.ts +9 -0
  12. package/corpus/templates/analytics/server/lib/first-party-analytics.ts +262 -13
  13. package/corpus/templates/analytics/server/lib/gong.ts +132 -33
  14. package/corpus/templates/analytics/server/plugins/agent-chat.ts +1 -1
  15. package/corpus/templates/analytics/server/plugins/auth.ts +21 -2
  16. package/corpus/templates/analytics/server/plugins/db.ts +11 -3
  17. package/corpus/templates/analytics/server/plugins/transactional-emails.ts +5 -0
  18. package/corpus/templates/calendar/app/components/calendar/InlineEventPickers.tsx +17 -7
  19. package/corpus/templates/calendar/server/lib/booking-emails.ts +154 -70
  20. package/corpus/templates/calendar/server/lib/emails.ts +167 -0
  21. package/corpus/templates/calendar/server/lib/event-guest-notifications.ts +64 -28
  22. package/corpus/templates/calendar/server/plugins/transactional-emails.ts +5 -0
  23. package/corpus/templates/clips/actions/invite-member.ts +39 -16
  24. package/corpus/templates/clips/app/components/player/share-dialog.tsx +73 -1
  25. package/corpus/templates/clips/app/i18n/en-US.ts +3 -0
  26. package/corpus/templates/clips/app/routes/r.$recordingId.tsx +10 -25
  27. package/corpus/templates/clips/app/routes/share.$shareId.tsx +2 -0
  28. package/corpus/templates/clips/changelog/2026-08-05-activity-is-now-the-default-clips-recording-tab-and-ai-setup.md +6 -0
  29. package/corpus/templates/clips/changelog/2026-08-05-clips-can-copy-a-linked-email-preview-for-public-recordings.md +6 -0
  30. package/corpus/templates/clips/changelog/2026-08-05-preparing-recording-now-uses-a-clean-shadow-free-status-card.md +6 -0
  31. package/corpus/templates/clips/desktop/src/styles.css +0 -3
  32. package/corpus/templates/clips/server/lib/emails.ts +256 -0
  33. package/corpus/templates/clips/server/lib/transactional-email-templates.ts +24 -0
  34. package/corpus/templates/clips/server/plugins/transactional-email-catalog.ts +5 -0
  35. package/corpus/templates/clips/server/routes/api/thumbnail/[recordingId].get.ts +4 -1
  36. package/corpus/templates/clips/shared/email-preview.ts +61 -0
  37. package/corpus/templates/content/server/lib/comment-notifications.ts +57 -26
  38. package/corpus/templates/content/server/lib/emails.ts +70 -0
  39. package/corpus/templates/content/server/plugins/transactional-emails.ts +5 -0
  40. package/corpus/templates/design/actions/import-design-tokens.ts +11 -8
  41. package/corpus/templates/design/actions/index-design-tokens.ts +13 -6
  42. package/corpus/templates/design/changelog/2026-08-05-design-token-imports-classify-typography-dimensions-correctly.md +6 -0
  43. package/corpus/templates/dispatch/app/routes/transactional-email.$appId.$id.tsx +4 -0
  44. package/corpus/templates/dispatch/app/routes/transactional-email.tsx +4 -0
  45. package/corpus/templates/dispatch/changelog/2026-08-05-transactional-email-catalogs-and-delivery-activity-are-available-again.md +6 -0
  46. package/corpus/templates/factory/AGENTS.md +18 -17
  47. package/corpus/templates/factory/actions/get-factory-automation-health.ts +50 -0
  48. package/corpus/templates/factory/actions/get-triage-config.ts +8 -0
  49. package/corpus/templates/factory/actions/save-triage-config.ts +26 -0
  50. package/corpus/templates/factory/app/i18n/en-US.ts +27 -0
  51. package/corpus/templates/factory/app/routes/factory.tsx +376 -206
  52. package/corpus/templates/factory/changelog/2026-08-05-factory-now-keeps-production-automations-running-shows-sched.md +6 -0
  53. package/corpus/templates/factory/server/db/schema.ts +6 -0
  54. package/corpus/templates/factory/server/plugins/factory-migrations.ts +10 -0
  55. package/corpus/templates/factory/server/plugins/factory-scheduler-job.ts +141 -2
  56. package/corpus/templates/forms/app/pages/FormsListPage.tsx +41 -21
  57. package/corpus/templates/forms/changelog/2026-08-05-form-links-can-now-be-cmd-clicked-to-open-in-a-new-tab.md +6 -0
  58. package/corpus/templates/forms/server/lib/emails.ts +52 -0
  59. package/corpus/templates/forms/server/lib/response-email.ts +2 -0
  60. package/corpus/templates/forms/server/plugins/transactional-emails.ts +5 -0
  61. package/corpus/templates/plan/actions/request-plan-access.ts +33 -12
  62. package/corpus/templates/plan/server/lib/comment-notifications.ts +53 -27
  63. package/corpus/templates/plan/server/lib/emails.ts +67 -0
  64. package/corpus/templates/plan/server/plugins/transactional-emails.ts +5 -0
  65. package/corpus/templates/slides/actions/import-from-url.ts +1 -0
  66. package/corpus/templates/slides/app/components/editor/NewDeckReferenceStep.tsx +492 -381
  67. package/corpus/templates/slides/app/components/editor/PromptDialog.tsx +8 -7
  68. package/corpus/templates/slides/app/components/layout/Layout.tsx +27 -23
  69. package/corpus/templates/slides/app/components/onboarding/FirstDeckOnboardingFlow.tsx +313 -0
  70. package/corpus/templates/slides/app/components/ui/command.tsx +1 -0
  71. package/corpus/templates/slides/app/i18n/en-US.ts +8 -2
  72. package/corpus/templates/slides/app/lib/create-deck-generation.ts +305 -0
  73. package/corpus/templates/slides/app/pages/DeckEditor.tsx +12 -12
  74. package/corpus/templates/slides/app/pages/Index.tsx +127 -137
  75. package/corpus/templates/slides/app/root.tsx +8 -0
  76. package/corpus/templates/slides/changelog/2026-08-05-deck-browsing-keeps-all-and-mine-in-the-header-with-a-tighte.md +6 -0
  77. package/corpus/templates/slides/changelog/2026-08-05-new-deck-creation-now-flows-through-a-clean-full-screen-refe.md +6 -0
  78. package/corpus/templates/slides/changelog/2026-08-05-website-imports-now-include-linked-stylesheets-for-more-accu.md +6 -0
  79. package/corpus/templates/slides/server/lib/comment-notifications.ts +44 -21
  80. package/corpus/templates/slides/server/lib/emails.ts +40 -0
  81. package/corpus/templates/slides/server/plugins/transactional-emails.ts +5 -0
  82. package/dist/brand-kit/index.d.ts +1 -0
  83. package/dist/brand-kit/index.js +1 -0
  84. package/dist/brand-kit/tokens.d.ts +91 -0
  85. package/dist/brand-kit/tokens.js +279 -0
  86. package/dist/brand-kit/types.d.ts +25 -0
  87. package/dist/client/AssistantChat.js +7 -7
  88. package/dist/client/onboarding/FirstRunOnboarding.js +26 -2
  89. package/dist/client/onboarding/first-run-registry.d.ts +25 -0
  90. package/dist/client/onboarding/first-run-registry.js +18 -0
  91. package/dist/client/onboarding/index.d.ts +2 -0
  92. package/dist/client/onboarding/index.js +1 -0
  93. package/dist/collab/routes.d.ts +1 -1
  94. package/dist/deploy/build.d.ts +8 -0
  95. package/dist/deploy/build.js +92 -3
  96. package/dist/deploy/workspace-deploy.js +86 -3
  97. package/dist/email-catalog/actions/list-email-activity.d.ts +5 -0
  98. package/dist/email-catalog/actions/list-email-activity.js +19 -0
  99. package/dist/email-catalog/actions/list-email-engagement.d.ts +5 -0
  100. package/dist/email-catalog/actions/list-email-engagement.js +15 -0
  101. package/dist/email-catalog/actions/list-email-log.d.ts +7 -0
  102. package/dist/email-catalog/actions/list-email-log.js +23 -0
  103. package/dist/email-catalog/actions/list-transactional-emails.d.ts +22 -0
  104. package/dist/email-catalog/actions/list-transactional-emails.js +67 -0
  105. package/dist/email-catalog/actions/render-transactional-email-preview.d.ts +9 -0
  106. package/dist/email-catalog/actions/render-transactional-email-preview.js +25 -0
  107. package/dist/email-catalog/authorize.d.ts +1 -0
  108. package/dist/email-catalog/authorize.js +9 -0
  109. package/dist/email-catalog/log.d.ts +60 -0
  110. package/dist/email-catalog/log.js +142 -0
  111. package/dist/email-catalog/provider-metrics.d.ts +34 -0
  112. package/dist/email-catalog/provider-metrics.js +182 -0
  113. package/dist/email-catalog/registry.d.ts +78 -0
  114. package/dist/email-catalog/registry.js +70 -0
  115. package/dist/email-catalog/schema.d.ts +231 -0
  116. package/dist/email-catalog/schema.js +53 -0
  117. package/dist/email-catalog/system-emails.d.ts +13 -0
  118. package/dist/email-catalog/system-emails.js +67 -0
  119. package/dist/jobs/index.d.ts +2 -0
  120. package/dist/jobs/index.js +2 -0
  121. package/dist/jobs/run-history.js +48 -1
  122. package/dist/jobs/scheduler-dispatch.d.ts +7 -0
  123. package/dist/jobs/scheduler-dispatch.js +7 -0
  124. package/dist/jobs/scheduler-health.d.ts +22 -0
  125. package/dist/jobs/scheduler-health.js +172 -0
  126. package/dist/jobs/scheduler.js +67 -2
  127. package/dist/localization/default-messages.d.ts +45 -0
  128. package/dist/localization/default-messages.js +45 -0
  129. package/dist/mcp/screen-memory-stdio.d.ts +7 -7
  130. package/dist/notifications/routes.d.ts +3 -3
  131. package/dist/observability/routes.d.ts +5 -5
  132. package/dist/org/handlers.js +9 -1
  133. package/dist/progress/routes.d.ts +1 -1
  134. package/dist/provider-api/actions/custom-provider-registration.d.ts +10 -10
  135. package/dist/provider-api/actions/provider-api.d.ts +8 -8
  136. package/dist/secrets/routes.d.ts +9 -9
  137. package/dist/server/action-discovery.js +22 -0
  138. package/dist/server/agent-chat/recurring-jobs-runtime.d.ts +7 -1
  139. package/dist/server/agent-chat/recurring-jobs-runtime.js +12 -0
  140. package/dist/server/agent-chat-plugin.d.ts +2 -1
  141. package/dist/server/agent-chat-plugin.js +39 -1
  142. package/dist/server/better-auth-instance.js +17 -2
  143. package/dist/server/design-token-utils.d.ts +6 -1
  144. package/dist/server/design-token-utils.js +252 -59
  145. package/dist/server/email.d.ts +11 -0
  146. package/dist/server/email.js +54 -3
  147. package/dist/server/index.d.ts +1 -0
  148. package/dist/server/index.js +1 -0
  149. package/dist/server/realtime-token.d.ts +1 -1
  150. package/dist/server/transcribe-voice.d.ts +1 -1
  151. package/dist/vite/client.js +20 -14
  152. package/package.json +2 -1
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Durable send log for transactional emails.
3
+ *
4
+ * Written by `sendEmail` on every attempt, successful or not. Read by Dispatch
5
+ * to report per-email send counts and last-sent without depending on the
6
+ * provider's activity retention window.
7
+ */
8
+ import { randomUUID } from "node:crypto";
9
+ import { getDbExec, isPostgres } from "../db/client.js";
10
+ import { ensureColumnExists, ensureIndexExists, ensureTableExists, } from "../db/ddl-guard.js";
11
+ import { getRequestOrgId } from "../server/request-context.js";
12
+ let _initPromise;
13
+ async function ensureTable() {
14
+ if (!_initPromise) {
15
+ _initPromise = (async () => {
16
+ const { EMAIL_LOG_CREATE_SQL, EMAIL_LOG_ORG_APP_INDEX_SQL, EMAIL_LOG_TEMPLATE_INDEX_SQL, } = await import("./schema.js");
17
+ const client = getDbExec();
18
+ // Generic INTEGER maps to BIGINT on Postgres, which millisecond
19
+ // timestamps need.
20
+ const createSql = isPostgres()
21
+ ? EMAIL_LOG_CREATE_SQL.replace(/\bINTEGER\b/g, "BIGINT")
22
+ : EMAIL_LOG_CREATE_SQL;
23
+ if (isPostgres()) {
24
+ await ensureTableExists("email_log", createSql);
25
+ await ensureColumnExists("email_log", "org_id", "ALTER TABLE email_log ADD COLUMN IF NOT EXISTS org_id TEXT");
26
+ await ensureIndexExists("email_log_template_created_idx", EMAIL_LOG_TEMPLATE_INDEX_SQL);
27
+ await ensureIndexExists("email_log_org_app_created_idx", EMAIL_LOG_ORG_APP_INDEX_SQL);
28
+ return;
29
+ }
30
+ await client.execute(createSql);
31
+ try {
32
+ await client.execute("ALTER TABLE email_log ADD COLUMN org_id TEXT");
33
+ }
34
+ catch (error) {
35
+ const message = error instanceof Error ? error.message : String(error);
36
+ if (!/already exists|duplicate column name/i.test(message)) {
37
+ throw error;
38
+ }
39
+ console.info("[agent-native:email] email_log.org_id already exists during local bootstrap");
40
+ }
41
+ await client.execute(EMAIL_LOG_TEMPLATE_INDEX_SQL);
42
+ await client.execute(EMAIL_LOG_ORG_APP_INDEX_SQL);
43
+ })().catch((error) => {
44
+ // Don't memoize a failed bootstrap — the next send should retry rather
45
+ // than log nothing forever.
46
+ _initPromise = undefined;
47
+ throw error;
48
+ });
49
+ }
50
+ return _initPromise;
51
+ }
52
+ /**
53
+ * Append one send record.
54
+ *
55
+ * Callers treat logging as best-effort: a logging failure must not turn a
56
+ * delivered email into a thrown send. The failure is surfaced on the console
57
+ * rather than swallowed, so a persistently broken log is visible instead of
58
+ * quietly producing an empty activity view.
59
+ */
60
+ export async function recordEmailSend(args) {
61
+ try {
62
+ await ensureTable();
63
+ const orgId = args.orgId ?? getRequestOrgId() ?? null;
64
+ await getDbExec().execute({
65
+ sql: `INSERT INTO email_log
66
+ (id, org_id, template_id, app, recipient, sender, subject, status, error, provider, created_at)
67
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
68
+ args: [
69
+ randomUUID(),
70
+ orgId,
71
+ args.templateId ?? null,
72
+ args.app ?? null,
73
+ args.recipient,
74
+ args.sender,
75
+ args.subject,
76
+ args.status,
77
+ args.error ?? null,
78
+ args.provider,
79
+ Date.now(),
80
+ ],
81
+ });
82
+ }
83
+ catch (error) {
84
+ console.error("[agent-native:email] failed to record send", error);
85
+ }
86
+ }
87
+ /**
88
+ * Per-template send counts and last-sent, for sends at or after `since`.
89
+ * Templates with no rows are absent from the result — callers distinguish
90
+ * "never sent" from "sent zero times in window" by that absence.
91
+ */
92
+ export async function getEmailSendStats(since, app, orgId) {
93
+ await ensureTable();
94
+ const { rows } = await getDbExec().execute({
95
+ sql: `SELECT template_id,
96
+ SUM(CASE WHEN status = 'sent' THEN 1 ELSE 0 END) AS sent,
97
+ SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failed,
98
+ MAX(CASE WHEN status = 'sent' THEN created_at END) AS last_sent_at
99
+ FROM email_log
100
+ WHERE org_id = ? AND app = ? AND template_id IS NOT NULL AND created_at >= ?
101
+ GROUP BY template_id`,
102
+ args: [orgId, app, since],
103
+ });
104
+ return rows.map((row) => ({
105
+ templateId: String(row.template_id),
106
+ sent: Number(row.sent ?? 0),
107
+ failed: Number(row.failed ?? 0),
108
+ lastSentAt: row.last_sent_at == null ? null : Number(row.last_sent_at),
109
+ }));
110
+ }
111
+ /** Most recent sends for one app, newest first, optionally filtered to one template. */
112
+ export async function listEmailLog(options) {
113
+ await ensureTable();
114
+ const limit = Math.min(Math.max(options.limit ?? 100, 1), 500);
115
+ const where = options.templateId
116
+ ? `WHERE org_id = ? AND app = ? AND template_id = ?`
117
+ : `WHERE org_id = ? AND app = ?`;
118
+ const args = options.templateId
119
+ ? [options.orgId, options.app, options.templateId, limit]
120
+ : [options.orgId, options.app, limit];
121
+ const { rows } = await getDbExec().execute({
122
+ sql: `SELECT id, template_id, app, recipient, sender, subject, status, error, provider, created_at
123
+ FROM email_log ${where} ORDER BY created_at DESC LIMIT ?`,
124
+ args,
125
+ });
126
+ return rows.map((row) => ({
127
+ id: String(row.id),
128
+ templateId: row.template_id == null ? null : String(row.template_id),
129
+ app: row.app == null ? null : String(row.app),
130
+ recipient: String(row.recipient),
131
+ sender: String(row.sender),
132
+ subject: String(row.subject),
133
+ status: String(row.status),
134
+ error: row.error == null ? null : String(row.error),
135
+ provider: String(row.provider),
136
+ createdAt: Number(row.created_at),
137
+ }));
138
+ }
139
+ /** Provider category that is safe to query for one organization only. */
140
+ export function getScopedEmailProviderCategory(templateId, orgId) {
141
+ return `${templateId}::org::${encodeURIComponent(orgId)}`;
142
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Engagement metrics and activity for registered transactional emails, read
3
+ * from the active provider in the current app's request context.
4
+ */
5
+ export type ProviderMetricsResult<T> = {
6
+ available: true;
7
+ data: T;
8
+ } | {
9
+ available: false;
10
+ reason: string;
11
+ };
12
+ export interface EmailEngagement {
13
+ templateId: string;
14
+ delivered: number;
15
+ uniqueOpens: number;
16
+ uniqueClicks: number;
17
+ openRate: number | null;
18
+ }
19
+ export declare function fetchEmailEngagement(templateIds: string[], windowDays: number, orgId?: string): Promise<ProviderMetricsResult<EmailEngagement[]>>;
20
+ export interface EmailActivityEntry {
21
+ msgId: string;
22
+ toEmail: string;
23
+ fromEmail: string;
24
+ subject: string;
25
+ status: string;
26
+ opensCount: number;
27
+ clicksCount: number;
28
+ lastEventTime: string;
29
+ }
30
+ export declare function fetchEmailActivity(options: {
31
+ templateId: string;
32
+ orgId?: string;
33
+ limit?: number;
34
+ }): Promise<ProviderMetricsResult<EmailActivityEntry[]>>;
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Engagement metrics and activity for registered transactional emails, read
3
+ * from the active provider in the current app's request context.
4
+ */
5
+ import { z } from "zod";
6
+ import { resolveSecret } from "../server/credential-provider.js";
7
+ import { getEmailProvider } from "../server/email.js";
8
+ import { getScopedEmailProviderCategory } from "./log.js";
9
+ const SENDGRID_API = "https://api.sendgrid.com/v3";
10
+ const SENDGRID_PAGE_SIZE = 1000;
11
+ const SENDGRID_MAX_PAGES = 10;
12
+ const categoryMetricsSchema = z
13
+ .object({
14
+ delivered: z.number().default(0),
15
+ unique_opens: z.number().default(0),
16
+ unique_clicks: z.number().default(0),
17
+ })
18
+ .passthrough();
19
+ const categoryStatSchema = z
20
+ .object({
21
+ name: z.string(),
22
+ metrics: categoryMetricsSchema.default(() => ({
23
+ delivered: 0,
24
+ unique_opens: 0,
25
+ unique_clicks: 0,
26
+ })),
27
+ })
28
+ .passthrough();
29
+ const categorySumsSchema = z.object({
30
+ stats: z.array(categoryStatSchema).default([]),
31
+ });
32
+ const activitySchema = z.object({
33
+ messages: z
34
+ .array(z
35
+ .object({
36
+ msg_id: z.string().default(""),
37
+ to_email: z.string().default(""),
38
+ from_email: z.string().default(""),
39
+ subject: z.string().default(""),
40
+ status: z.string().default(""),
41
+ opens_count: z.coerce.number().default(0),
42
+ clicks_count: z.coerce.number().default(0),
43
+ last_event_time: z.string().default(""),
44
+ })
45
+ .passthrough())
46
+ .default([]),
47
+ });
48
+ async function activeSendGrid() {
49
+ const provider = await getEmailProvider();
50
+ if (provider === "resend") {
51
+ return {
52
+ available: false,
53
+ reason: "Email delivery uses Resend, so SendGrid metrics do not describe the active transport.",
54
+ };
55
+ }
56
+ if (provider !== "sendgrid") {
57
+ return {
58
+ available: false,
59
+ reason: "No email provider is configured, so provider metrics cannot be read.",
60
+ };
61
+ }
62
+ const key = await resolveSecret("SENDGRID_API_KEY");
63
+ if (!key) {
64
+ return {
65
+ available: false,
66
+ reason: "SendGrid is the active email transport, but SENDGRID_API_KEY could not be resolved.",
67
+ };
68
+ }
69
+ return { available: true, key };
70
+ }
71
+ function isoDate(ms) {
72
+ return new Date(ms).toISOString().slice(0, 10);
73
+ }
74
+ async function sendgridGet(key, path, params) {
75
+ const url = new URL(`${SENDGRID_API}${path}`);
76
+ for (const [name, value] of params)
77
+ url.searchParams.append(name, value);
78
+ const res = await fetch(url, {
79
+ headers: { Authorization: `Bearer ${key}` },
80
+ });
81
+ if (!res.ok) {
82
+ const body = await res
83
+ .text()
84
+ .catch((cause) => `<error body unreadable: ${cause}>`);
85
+ throw new Error(`SendGrid ${res.status} on ${path}: ${body.slice(0, 300)}`);
86
+ }
87
+ return res.json();
88
+ }
89
+ export async function fetchEmailEngagement(templateIds, windowDays, orgId) {
90
+ if (!templateIds.length)
91
+ return { available: true, data: [] };
92
+ if (!orgId) {
93
+ return {
94
+ available: false,
95
+ reason: "Organization context is required for provider email metrics.",
96
+ };
97
+ }
98
+ const sendgrid = await activeSendGrid();
99
+ if (!sendgrid.available)
100
+ return sendgrid;
101
+ const end = Date.now();
102
+ const start = end - windowDays * 24 * 60 * 60 * 1000;
103
+ const categoryToTemplate = new Map(templateIds.map((templateId) => [
104
+ getScopedEmailProviderCategory(templateId, orgId),
105
+ templateId,
106
+ ]));
107
+ const requested = new Set(categoryToTemplate.keys());
108
+ const data = [];
109
+ try {
110
+ for (let page = 0; page < SENDGRID_MAX_PAGES; page += 1) {
111
+ const payload = categorySumsSchema.parse(await sendgridGet(sendgrid.key, "/categories/stats/sums", [
112
+ ["start_date", isoDate(start)],
113
+ ["end_date", isoDate(end)],
114
+ ["limit", String(SENDGRID_PAGE_SIZE)],
115
+ ["offset", String(page * SENDGRID_PAGE_SIZE)],
116
+ ]));
117
+ for (const entry of payload.stats) {
118
+ if (!requested.has(entry.name))
119
+ continue;
120
+ requested.delete(entry.name);
121
+ const delivered = entry.metrics.delivered;
122
+ const uniqueOpens = entry.metrics.unique_opens;
123
+ data.push({
124
+ templateId: categoryToTemplate.get(entry.name),
125
+ delivered,
126
+ uniqueOpens,
127
+ uniqueClicks: entry.metrics.unique_clicks,
128
+ openRate: delivered > 0 ? Math.min(uniqueOpens / delivered, 1) : null,
129
+ });
130
+ }
131
+ if (requested.size === 0 || payload.stats.length < SENDGRID_PAGE_SIZE) {
132
+ break;
133
+ }
134
+ }
135
+ return { available: true, data };
136
+ }
137
+ catch (error) {
138
+ return {
139
+ available: false,
140
+ reason: error instanceof Error ? error.message : String(error),
141
+ };
142
+ }
143
+ }
144
+ export async function fetchEmailActivity(options) {
145
+ if (!options.orgId) {
146
+ return {
147
+ available: false,
148
+ reason: "Organization context is required for provider email activity.",
149
+ };
150
+ }
151
+ const sendgrid = await activeSendGrid();
152
+ if (!sendgrid.available)
153
+ return sendgrid;
154
+ const limit = Math.min(Math.max(options.limit ?? 50, 1), 1000);
155
+ const category = getScopedEmailProviderCategory(options.templateId, options.orgId);
156
+ const safe = category.replace(/["\\]/g, "");
157
+ try {
158
+ const payload = activitySchema.parse(await sendgridGet(sendgrid.key, "/messages", [
159
+ ["limit", String(limit)],
160
+ ["query", `category="${safe}"`],
161
+ ]));
162
+ return {
163
+ available: true,
164
+ data: payload.messages.map((message) => ({
165
+ msgId: message.msg_id,
166
+ toEmail: message.to_email,
167
+ fromEmail: message.from_email,
168
+ subject: message.subject,
169
+ status: message.status,
170
+ opensCount: message.opens_count,
171
+ clicksCount: message.clicks_count,
172
+ lastEventTime: message.last_event_time,
173
+ })),
174
+ };
175
+ }
176
+ catch (error) {
177
+ return {
178
+ available: false,
179
+ reason: error instanceof Error ? error.message : String(error),
180
+ };
181
+ }
182
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Registry of the transactional emails an app can send.
3
+ *
4
+ * An app declares each email it sends here so the workspace can answer, without
5
+ * reading the app's source: what emails exist, what makes one send, who it goes
6
+ * to, who it comes from, and what it looks like. Dispatch aggregates these
7
+ * across every mounted app via the `list-transactional-emails` action.
8
+ *
9
+ * Declare emails next to the code that sends them, then import that module from
10
+ * a server plugin so registration happens at startup:
11
+ *
12
+ * defineTransactionalEmail({
13
+ * id: "calendar.booking-confirmed",
14
+ * name: "Booking confirmed",
15
+ * trigger: "A guest completes a booking on a public scheduling page.",
16
+ * recipient: "The guest email captured on the booking form.",
17
+ * sender: "EMAIL_FROM, with reply-to set to the event host.",
18
+ * preview: () => renderBookingConfirmedEmail(SAMPLE_BOOKING),
19
+ * });
20
+ *
21
+ * The `id` doubles as the SendGrid category `sendEmail` tags the message with,
22
+ * which is how per-email delivery and open metrics are attributed later.
23
+ */
24
+ import type { RenderedEmailMessage } from "../server/email-templates.js";
25
+ export interface TransactionalEmailDefinition {
26
+ /**
27
+ * Stable, globally unique id in `<app>.<email>` form, e.g.
28
+ * `calendar.booking-confirmed`. Used as the SendGrid category, so changing it
29
+ * orphans historical metrics for this email.
30
+ */
31
+ id: string;
32
+ /** Human-readable name, e.g. "Booking confirmed". */
33
+ name: string;
34
+ /**
35
+ * App slug this email belongs to. Defaults to the running app, which is
36
+ * correct for every app-declared email; core system emails set it explicitly.
37
+ */
38
+ app?: string;
39
+ /** Plain-language description of the condition that causes a send. */
40
+ trigger: string;
41
+ /** Plain-language description of how the recipient address is chosen. */
42
+ recipient: string;
43
+ /**
44
+ * Two-to-four word summary of the recipient for table cells, e.g.
45
+ * "Booking guest". The full `recipient` sentence is shown on the detail view.
46
+ */
47
+ recipientLabel: string;
48
+ /** Plain-language description of how From and Reply-To are chosen. */
49
+ sender: string;
50
+ /** Two-to-four word summary of the sender, e.g. "Default, reply-to host". */
51
+ senderLabel: string;
52
+ /**
53
+ * Render the email with representative dummy data. Must not read from the
54
+ * database or touch the network — previews are rendered on demand from
55
+ * Dispatch, for apps whose data the caller may not be able to see.
56
+ */
57
+ preview: () => RenderedEmailMessage;
58
+ }
59
+ /** A definition with its app resolved, as returned to callers. */
60
+ export type RegisteredTransactionalEmail = TransactionalEmailDefinition & {
61
+ app: string;
62
+ };
63
+ /**
64
+ * Register a transactional email. Returns the definition so the call site can
65
+ * export it and reuse `id` when sending.
66
+ */
67
+ export declare function defineTransactionalEmail(definition: TransactionalEmailDefinition): RegisteredTransactionalEmail;
68
+ /** Every registered email, sorted by app then name. */
69
+ export declare function listTransactionalEmails(): RegisteredTransactionalEmail[];
70
+ export declare function getTransactionalEmail(id: string): RegisteredTransactionalEmail | undefined;
71
+ /**
72
+ * Render one email's preview. Throws when the id is unknown or the renderer
73
+ * fails — a preview that silently returns an empty body would look like an
74
+ * email that legitimately renders blank.
75
+ */
76
+ export declare function renderTransactionalEmailPreview(id: string): RenderedEmailMessage;
77
+ /** Test seam — drops all registrations. */
78
+ export declare function resetTransactionalEmailRegistry(): void;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Registry of the transactional emails an app can send.
3
+ *
4
+ * An app declares each email it sends here so the workspace can answer, without
5
+ * reading the app's source: what emails exist, what makes one send, who it goes
6
+ * to, who it comes from, and what it looks like. Dispatch aggregates these
7
+ * across every mounted app via the `list-transactional-emails` action.
8
+ *
9
+ * Declare emails next to the code that sends them, then import that module from
10
+ * a server plugin so registration happens at startup:
11
+ *
12
+ * defineTransactionalEmail({
13
+ * id: "calendar.booking-confirmed",
14
+ * name: "Booking confirmed",
15
+ * trigger: "A guest completes a booking on a public scheduling page.",
16
+ * recipient: "The guest email captured on the booking form.",
17
+ * sender: "EMAIL_FROM, with reply-to set to the event host.",
18
+ * preview: () => renderBookingConfirmedEmail(SAMPLE_BOOKING),
19
+ * });
20
+ *
21
+ * The `id` doubles as the SendGrid category `sendEmail` tags the message with,
22
+ * which is how per-email delivery and open metrics are attributed later.
23
+ */
24
+ import { getAppSlug } from "../server/app-name.js";
25
+ const registry = new Map();
26
+ /** Source definitions, so re-registering the same one is a no-op rather than a clash. */
27
+ const sources = new Map();
28
+ /**
29
+ * Register a transactional email. Returns the definition so the call site can
30
+ * export it and reuse `id` when sending.
31
+ */
32
+ export function defineTransactionalEmail(definition) {
33
+ const existing = sources.get(definition.id);
34
+ if (existing && existing !== definition) {
35
+ // Two emails sharing an id would silently merge their metrics and make the
36
+ // catalog claim one exists when the other actually sent.
37
+ throw new Error(`Duplicate transactional email id "${definition.id}". Ids must be unique across the app.`);
38
+ }
39
+ const resolved = {
40
+ ...definition,
41
+ app: definition.app ?? getAppSlug() ?? "unknown",
42
+ };
43
+ registry.set(definition.id, resolved);
44
+ sources.set(definition.id, definition);
45
+ return resolved;
46
+ }
47
+ /** Every registered email, sorted by app then name. */
48
+ export function listTransactionalEmails() {
49
+ return [...registry.values()].sort((a, b) => a.app.localeCompare(b.app) || a.name.localeCompare(b.name));
50
+ }
51
+ export function getTransactionalEmail(id) {
52
+ return registry.get(id);
53
+ }
54
+ /**
55
+ * Render one email's preview. Throws when the id is unknown or the renderer
56
+ * fails — a preview that silently returns an empty body would look like an
57
+ * email that legitimately renders blank.
58
+ */
59
+ export function renderTransactionalEmailPreview(id) {
60
+ const definition = registry.get(id);
61
+ if (!definition) {
62
+ throw new Error(`Unknown transactional email "${id}".`);
63
+ }
64
+ return definition.preview();
65
+ }
66
+ /** Test seam — drops all registrations. */
67
+ export function resetTransactionalEmailRegistry() {
68
+ registry.clear();
69
+ sources.clear();
70
+ }