@aglyn/plugins-ai 1.3.0 → 1.4.0
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.
- package/package.json +17 -17
- package/src/lib/components/ai-insight-dialog.component.js +7 -2
- package/src/lib/components/ai-insight-dialog.component.js.map +1 -1
- package/src/lib/components/ai-job-request.component.d.ts +28 -0
- package/src/lib/components/ai-job-request.component.js +103 -0
- package/src/lib/components/ai-job-request.component.js.map +1 -0
- package/src/lib/components/ai-jobs-list-page.component.d.ts +2 -0
- package/src/lib/components/ai-jobs-list-page.component.js +2 -2
- package/src/lib/components/ai-jobs-list-page.component.js.map +1 -1
- package/src/lib/components/ai-site-build-page.component.js +36 -6
- package/src/lib/components/ai-site-build-page.component.js.map +1 -1
- package/src/lib/insights/ai-insight-digest.d.ts +34 -5
- package/src/lib/insights/ai-insight-digest.js +171 -10
- package/src/lib/insights/ai-insight-digest.js.map +1 -1
- package/src/lib/jobs/ai-job-insight-step.d.ts +1 -1
- package/src/lib/jobs/ai-job-insight-step.js +5 -1
- package/src/lib/jobs/ai-job-insight-step.js.map +1 -1
- package/src/lib/model/ai-insight.d.ts +4 -0
- package/src/lib/model/ai-insight.js +1 -0
- package/src/lib/model/ai-insight.js.map +1 -1
- package/src/lib/model/ai-site-build-progress.d.ts +8 -0
- package/src/lib/model/ai-site-build-progress.js +62 -1
- package/src/lib/model/ai-site-build-progress.js.map +1 -1
- package/src/lib/plugin.js +1 -1
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/runtime/ai-insight-check.js +22 -6
- package/src/lib/runtime/ai-insight-check.js.map +1 -1
- package/src/lib/server/ai-insight-digest-route.js +3 -1
- package/src/lib/server/ai-insight-digest-route.js.map +1 -1
- package/src/lib/tools/ai-insight-tool.js +11 -3
- package/src/lib/tools/ai-insight-tool.js.map +1 -1
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
1
2
|
/**
|
|
2
3
|
* @license
|
|
3
4
|
* Copyright 2026 Aglyn LLC
|
|
@@ -15,11 +16,13 @@
|
|
|
15
16
|
* limitations under the License.
|
|
16
17
|
*/ import { FieldPath } from "firebase-admin/firestore";
|
|
17
18
|
import { INSIGHT_DIGESTS_FIELD, insightDigestSubscribed, notificationMuted } from "@aglyn/aglyn/app-utils/notifications";
|
|
19
|
+
import { liveCustomDomain, TENANT_APEX } from "@aglyn/aglyn/app-utils/host-naming";
|
|
18
20
|
import { hostRoleFor } from "@aglyn/aglyn/app-utils/organizations";
|
|
19
21
|
import { checkEntitlement, resolveBrandingProfile, resolveEffectivePlan } from "@aglyn/aglyn/app-utils/plan-entitlements";
|
|
20
22
|
import { isReleaseFlagOnForOrg, parseOrgReleaseFlagOverrides } from "@aglyn/aglyn/app-utils/release-flags";
|
|
21
|
-
import { weeklySummaryPeriod } from "@aglyn/aglyn/app-utils/weekly-summary";
|
|
22
|
-
import {
|
|
23
|
+
import { weeklySummaryFootnoteHtml, weeklySummaryPeriod, weeklySummaryPlainDates, weeklySummarySectionsHtml, weeklySummaryTilesHtml, weeklySummaryWeekday } from "@aglyn/aglyn/app-utils/weekly-summary";
|
|
24
|
+
import { normalizePluginFigureTable, pluginFigureCellText, pluginFigureReader } from "@aglyn/aglyn/plugin-manager/plugin-figures";
|
|
25
|
+
import { aiInsightDigestPeriod, aiInsightSourceHref, AI_INSIGHTS_COLLECTION, aiInsightIsoWeek } from "../model/ai-insight.js";
|
|
23
26
|
import { isAiOnForSite } from "../model/ai-site-switch.js";
|
|
24
27
|
import { cancelAiJob, createAiJob, getAiJob } from "../jobs/ai-jobs.js";
|
|
25
28
|
export const AI_INSIGHTS_DIGEST_CRON_ID = 'ai-insights-digest';
|
|
@@ -59,33 +62,174 @@ const str = (value)=>typeof value === 'string' ? value.trim() : '';
|
|
|
59
62
|
return [
|
|
60
63
|
input.periodLabel ? `Here is what ${input.siteName}'s figures showed last week, ${input.periodLabel}.${drew}` : `Here is what ${input.siteName}'s figures showed this week.${drew}`,
|
|
61
64
|
'',
|
|
62
|
-
...input.insights.map((insight, index)=>`${index + 1}. ${insight
|
|
65
|
+
...input.insights.map((insight, index)=>`${index + 1}. ${aiInsightDigestLine(insight)}`),
|
|
63
66
|
'',
|
|
64
67
|
input.analyticsUrl ? `Each of these is traced to the figures it cites. See them in ${input.productName}: ${input.analyticsUrl}` : `Each of these is traced to the figures it cites. See them on the site's Analytics page in ${input.productName}.`,
|
|
65
68
|
'',
|
|
66
69
|
input.settingsUrl ? `You asked for weekly insights for ${forWhom}. Turn them off in Notifications: ${input.settingsUrl}` : `You asked for weekly insights for ${forWhom}. Turn them off in your Notifications settings.`
|
|
67
70
|
].join('\n');
|
|
68
71
|
}
|
|
72
|
+
/** An insight in one line of plain text, its dates as a person says them. */ function aiInsightDigestLine(insight) {
|
|
73
|
+
const text = weeklySummaryPlainDates(insight.text);
|
|
74
|
+
return insight.headline ? `${insight.headline}: ${text}` : text;
|
|
75
|
+
}
|
|
76
|
+
/** The most tiles the digest leads with: one row. */ export const AI_INSIGHT_DIGEST_MAX_TILES = 3;
|
|
77
|
+
/** The most rows a section lists. */ export const AI_INSIGHT_DIGEST_MAX_ROWS = 5;
|
|
78
|
+
/** The columns that hold a figure a row can show, as against a label or a change. */ const FIGURE_KINDS = [
|
|
79
|
+
'count',
|
|
80
|
+
'money',
|
|
81
|
+
'percent',
|
|
82
|
+
'duration'
|
|
83
|
+
];
|
|
84
|
+
/**
|
|
85
|
+
* Each table the job read, as its reader's owner would headline it in the
|
|
86
|
+
* weekly summary. Only a figure compared with the week before earns a tile: a
|
|
87
|
+
* month's running count beside two weeks' does not read as the same kind of
|
|
88
|
+
* thing.
|
|
89
|
+
*/ function aiInsightDigestTiles(tables) {
|
|
90
|
+
return tables.flatMap((source)=>{
|
|
91
|
+
var _ref, _ref1;
|
|
92
|
+
var _pluginFigureReader, _summary_summarize;
|
|
93
|
+
const summary = (_pluginFigureReader = pluginFigureReader(source.reader)) == null ? void 0 : _pluginFigureReader.reader.weeklySummary;
|
|
94
|
+
const table = summary ? normalizePluginFigureTable(source) : null;
|
|
95
|
+
const stats = (table ? (_ref = summary == null ? void 0 : (_summary_summarize = summary.summarize(table)) == null ? void 0 : _summary_summarize.stats) != null ? _ref : [] : []).filter((stat)=>typeof stat.change === 'number');
|
|
96
|
+
return stats.length ? [
|
|
97
|
+
{
|
|
98
|
+
ref: source.ref,
|
|
99
|
+
stats,
|
|
100
|
+
order: (_ref1 = summary == null ? void 0 : summary.order) != null ? _ref1 : 0
|
|
101
|
+
}
|
|
102
|
+
] : [];
|
|
103
|
+
}).sort((a, b)=>a.order - b.order);
|
|
104
|
+
}
|
|
105
|
+
/** The row numbers a set of insights cite in a table, each once, in the order they cite them. */ function citedRows(insights, table) {
|
|
106
|
+
const rows = insights.flatMap((insight)=>insight.cites.filter((cite)=>cite.table === table.ref).flatMap((cite)=>cite.rows));
|
|
107
|
+
return [
|
|
108
|
+
...new Set(rows)
|
|
109
|
+
].filter((row)=>Number.isInteger(row) && table.rows[row]);
|
|
110
|
+
}
|
|
111
|
+
/** A row's label as a person reads it, and the page it names, when it names one. */ function rowLabel(value, siteUrl) {
|
|
112
|
+
const label = String(value != null ? value : '');
|
|
113
|
+
const path = label.startsWith('/');
|
|
114
|
+
return {
|
|
115
|
+
label: label === '/' ? 'Home' : label,
|
|
116
|
+
url: path && siteUrl ? `${siteUrl}${label === '/' ? '' : label}` : null
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* A section's figures, from the table's own columns, so a reader added
|
|
121
|
+
* tomorrow draws without a line here: a table of days is a chart of the week
|
|
122
|
+
* with the cited days marked, and any other is its cited rows, each with its
|
|
123
|
+
* change where the table has one, else with its second figure.
|
|
124
|
+
*/ function aiInsightDigestFigures(table, cited, siteUrl) {
|
|
125
|
+
const label = table.columns.find((column)=>column.kind === 'text' || column.kind === 'date');
|
|
126
|
+
const figures = table.columns.filter((column)=>FIGURE_KINDS.includes(column.kind));
|
|
127
|
+
const change = table.columns.find((column)=>column.kind === 'change');
|
|
128
|
+
if (!label || !figures.length || !cited.length) return {};
|
|
129
|
+
// A `figure` row names what it counts. Any other row's count takes its column's word.
|
|
130
|
+
const counted = label.key !== 'figure';
|
|
131
|
+
const text = (column, row)=>{
|
|
132
|
+
const cell = pluginFigureCellText(table, column.key, row[column.key]);
|
|
133
|
+
return counted && column.kind === 'count' ? `${cell} ${column.label.toLowerCase()}` : cell;
|
|
134
|
+
};
|
|
135
|
+
if (label.kind === 'date') {
|
|
136
|
+
const [figure] = figures;
|
|
137
|
+
const bars = table.rows.map((row, index)=>({
|
|
138
|
+
label: weeklySummaryWeekday(String(row[label.key])),
|
|
139
|
+
value: Number(row[figure.key]) || 0,
|
|
140
|
+
display: pluginFigureCellText(table, figure.key, row[figure.key]),
|
|
141
|
+
marked: cited.includes(index)
|
|
142
|
+
}));
|
|
143
|
+
return {
|
|
144
|
+
bars
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
const shown = figures.slice(0, change ? 1 : 2);
|
|
148
|
+
return {
|
|
149
|
+
rows: cited.slice(0, AI_INSIGHT_DIGEST_MAX_ROWS).map((index)=>{
|
|
150
|
+
const row = table.rows[index];
|
|
151
|
+
const moved = change ? row[change.key] : null;
|
|
152
|
+
return _extends({}, rowLabel(row[label.key], siteUrl), {
|
|
153
|
+
value: shown.map((column)=>text(column, row)).join(' · '),
|
|
154
|
+
change: typeof moved === 'number' ? moved : null
|
|
155
|
+
});
|
|
156
|
+
})
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
/** The digest's topics: one a table, however many insights cite it, in the order they first come up. */ function aiInsightDigestSections(insights, input) {
|
|
160
|
+
const groups = new Map();
|
|
161
|
+
for (const insight of insights){
|
|
162
|
+
var _ref, _groups_get, _input_tables_find;
|
|
163
|
+
var _insight_cites_;
|
|
164
|
+
const ref = (_ref = (_insight_cites_ = insight.cites[0]) == null ? void 0 : _insight_cites_.table) != null ? _ref : '';
|
|
165
|
+
const group = (_groups_get = groups.get(ref)) != null ? _groups_get : {
|
|
166
|
+
table: (_input_tables_find = input.tables.find((table)=>table.ref === ref)) != null ? _input_tables_find : null,
|
|
167
|
+
insights: []
|
|
168
|
+
};
|
|
169
|
+
group.insights.push(insight);
|
|
170
|
+
groups.set(ref, group);
|
|
171
|
+
}
|
|
172
|
+
return [
|
|
173
|
+
...groups.values()
|
|
174
|
+
].map(({ table, insights: said })=>{
|
|
175
|
+
var _ref;
|
|
176
|
+
const url = table ? input.sourceUrl(table) : null;
|
|
177
|
+
return _extends({
|
|
178
|
+
title: (_ref = table == null ? void 0 : table.title) != null ? _ref : 'What changed',
|
|
179
|
+
link: table && url ? {
|
|
180
|
+
label: table.source.label,
|
|
181
|
+
url
|
|
182
|
+
} : null,
|
|
183
|
+
points: said.map((insight)=>{
|
|
184
|
+
var _insight_headline;
|
|
185
|
+
return {
|
|
186
|
+
headline: ((_insight_headline = insight.headline) == null ? void 0 : _insight_headline.trim()) || null,
|
|
187
|
+
text: weeklySummaryPlainDates(insight.text)
|
|
188
|
+
};
|
|
189
|
+
})
|
|
190
|
+
}, table ? aiInsightDigestFigures(table, citedRows(said, table), input.siteUrl) : {});
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* The digest's drawn parts: the week's figures as tiles, one section a topic,
|
|
195
|
+
* and the small print. An insight that only says what the first tiles already
|
|
196
|
+
* show is left out, so the email never makes a person read the same figures
|
|
197
|
+
* twice.
|
|
198
|
+
*/ export function aiInsightDigestEmailHtml(input) {
|
|
199
|
+
const tiles = aiInsightDigestTiles(input.tables);
|
|
200
|
+
const restated = (insight)=>insight.cites.length > 0 && insight.cites.every((cite)=>{
|
|
201
|
+
var _tiles_;
|
|
202
|
+
return cite.table === ((_tiles_ = tiles[0]) == null ? void 0 : _tiles_.ref);
|
|
203
|
+
});
|
|
204
|
+
const fresh = input.insights.filter((insight)=>!restated(insight));
|
|
205
|
+
return {
|
|
206
|
+
'digest.html': weeklySummaryTilesHtml(tiles.flatMap((part)=>part.stats).slice(0, AI_INSIGHT_DIGEST_MAX_TILES), input.colors) + weeklySummarySectionsHtml(aiInsightDigestSections(fresh.length ? fresh : input.insights, input), input.colors),
|
|
207
|
+
'digest.footnote': weeklySummaryFootnoteHtml(input.why, input.settingsUrl ? {
|
|
208
|
+
label: 'Turn off weekly insights',
|
|
209
|
+
url: input.settingsUrl
|
|
210
|
+
} : null, input.colors)
|
|
211
|
+
};
|
|
212
|
+
}
|
|
69
213
|
/**
|
|
70
214
|
* The same digest as {@link aiInsightDigestEmailText}, cut into the parts the
|
|
71
215
|
* `ai-insights-digest` system email draws: the workspace and week above the
|
|
72
|
-
* heading, the
|
|
73
|
-
*
|
|
216
|
+
* heading, the figures and insights, a button to the site's Analytics page,
|
|
217
|
+
* what it cost, and where to turn it off.
|
|
74
218
|
*/ export function aiInsightDigestEmailParts(input) {
|
|
75
219
|
var _input_analyticsUrl;
|
|
76
220
|
var _input_workspaceName, _input_periodLabel;
|
|
77
221
|
const workspace = ((_input_workspaceName = input.workspaceName) == null ? void 0 : _input_workspaceName.trim()) || '';
|
|
78
222
|
const credits = Math.max(0, Math.round(Number(input.creditsSpent) || 0));
|
|
79
|
-
const
|
|
223
|
+
const spent = credits ? ` Writing these used ${credits.toLocaleString('en-US')} of ${workspace ? `${workspace}’s` : 'the workspace’s'} AI credits.` : '';
|
|
80
224
|
return {
|
|
81
225
|
'digest.eyebrow': [
|
|
82
226
|
workspace,
|
|
83
227
|
(_input_periodLabel = input.periodLabel) == null ? void 0 : _input_periodLabel.trim()
|
|
84
228
|
].filter(Boolean).join(' · '),
|
|
85
229
|
'digest.intro': `What ${input.siteName}'s figures showed ${input.periodLabel ? 'last week' : 'this week'}. ` + 'Each one is traced to the figures it cites, so you can check it on the Analytics page.',
|
|
86
|
-
'digest.insights': input.insights.map((insight, index)=>`${index + 1}. ${insight
|
|
230
|
+
'digest.insights': input.insights.map((insight, index)=>`${index + 1}. ${aiInsightDigestLine(insight)}`).join('\n\n'),
|
|
87
231
|
'digest.analyticsUrl': (_input_analyticsUrl = input.analyticsUrl) != null ? _input_analyticsUrl : '',
|
|
88
|
-
'digest.why': `
|
|
232
|
+
'digest.why': `Every number here is checked against ${input.siteName}'s own figures.${spent}`
|
|
89
233
|
};
|
|
90
234
|
}
|
|
91
235
|
async function readUsers(firestore, uids) {
|
|
@@ -254,6 +398,7 @@ async function readUsers(firestore, uids) {
|
|
|
254
398
|
}
|
|
255
399
|
const address = str((_member_email = member.email) != null ? _member_email : user == null ? void 0 : user.get('email')).toLowerCase();
|
|
256
400
|
if (address.includes('@')) {
|
|
401
|
+
var _liveCustomDomain, _record_tables;
|
|
257
402
|
const emailInput = {
|
|
258
403
|
siteName: site.name,
|
|
259
404
|
productName: branding.productName,
|
|
@@ -264,6 +409,8 @@ async function readUsers(firestore, uids) {
|
|
|
264
409
|
creditsSpent: job.creditsSpent,
|
|
265
410
|
periodLabel: aiInsightDigestPeriod(job.inputs, new Date(Number(marker.createdAtMs) || now.getTime())).label
|
|
266
411
|
};
|
|
412
|
+
const parts = aiInsightDigestEmailParts(emailInput);
|
|
413
|
+
const domain = (_liveCustomDomain = liveCustomDomain(host)) != null ? _liveCustomDomain : subdomain ? `${subdomain}.${TENANT_APEX}` : '';
|
|
267
414
|
const sent = await deps.send({
|
|
268
415
|
to: address,
|
|
269
416
|
subject: `Your weekly insights for ${site.name}`,
|
|
@@ -271,7 +418,21 @@ async function readUsers(firestore, uids) {
|
|
|
271
418
|
fromName: branding.fromName,
|
|
272
419
|
siteName: site.name,
|
|
273
420
|
org,
|
|
274
|
-
merge:
|
|
421
|
+
merge: _extends({}, parts, aiInsightDigestEmailHtml({
|
|
422
|
+
insights: record.insights,
|
|
423
|
+
tables: (_record_tables = record.tables) != null ? _record_tables : [],
|
|
424
|
+
colors: deps.colors(org),
|
|
425
|
+
siteUrl: domain ? `https://${domain}` : null,
|
|
426
|
+
sourceUrl: (table)=>{
|
|
427
|
+
const href = origin ? aiInsightSourceHref(table, {
|
|
428
|
+
orgSlug,
|
|
429
|
+
host: subdomain || null
|
|
430
|
+
}) : null;
|
|
431
|
+
return href ? `${origin}${href}` : null;
|
|
432
|
+
},
|
|
433
|
+
why: parts['digest.why'],
|
|
434
|
+
settingsUrl: emailInput.settingsUrl
|
|
435
|
+
}))
|
|
275
436
|
});
|
|
276
437
|
if (sent.rateLimited) {
|
|
277
438
|
// Nothing is marked, so the next run delivers this site whole.
|
|
@@ -283,7 +444,7 @@ async function readUsers(firestore, uids) {
|
|
|
283
444
|
if (!notificationMuted(user == null ? void 0 : user.get('notificationPrefs'), 'content.insightsDigest')) {
|
|
284
445
|
await deps.notify(member.$id, {
|
|
285
446
|
title: `Weekly insights · ${site.name}`,
|
|
286
|
-
body: record.insights[0]
|
|
447
|
+
body: aiInsightDigestLine(record.insights[0]),
|
|
287
448
|
link: `/${hostId}/analytics`,
|
|
288
449
|
orgId,
|
|
289
450
|
hostId
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/insights/ai-insight-digest.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from 'firebase-admin/firestore'\nimport { INSIGHT_DIGESTS_FIELD, insightDigestSubscribed, notificationMuted } from '@aglyn/aglyn/app-utils/notifications'\nimport { hostRoleFor } from '@aglyn/aglyn/app-utils/organizations'\nimport { checkEntitlement, resolveBrandingProfile, resolveEffectivePlan } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { isReleaseFlagOnForOrg, parseOrgReleaseFlagOverrides, type ReleaseFlagValue } from '@aglyn/aglyn/app-utils/release-flags'\nimport type { AglynOrgMember } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport { weeklySummaryPeriod } from '@aglyn/aglyn/app-utils/weekly-summary'\nimport {\n aiInsightDigestPeriod,\n AI_INSIGHTS_COLLECTION,\n aiInsightIsoWeek,\n type AiInsightRecord,\n} from '../model/ai-insight'\nimport { isAiOnForSite } from '../model/ai-site-switch'\nimport { cancelAiJob, createAiJob, getAiJob } from '../jobs/ai-jobs'\n\n/**\n * THE WEEKLY INSIGHTS (AGL-2915): `POST /api/admin/ai-insights-digest`, twice\n * a day on the console's scheduler.\n *\n * ## Who asked for it\n *\n * A person turns weekly insights on for a workspace beside the answers\n * themselves (`users/{uid}.insightDigests.{orgId}`), and off there or in\n * Notifications. It is opt-in, because each digest is a generation the\n * workspace pays for. At the sweep, every rung is asked again rather than\n * trusted from the switch: the workspace's plan includes `aiGenerative`,\n * `release_ai_generative` is on for it, its AI is not paused, the site has AI\n * on, and the person still holds `ai.generate` on the site.\n *\n * ## Monday: one job per site\n *\n * On a Monday run, for each workspace with someone who asked, the sites those\n * people reach — the busiest `AI_INSIGHT_DIGEST_MAX_SITES` by yesterday's page\n * views — each get one `insight` job with the `digest` surface, created by the\n * first of them who may generate there. The job runs on the AI jobs beat like\n * any other: it reserves, meters and records its credits, and a workspace at\n * its band — a Free one that has used its credits — has its job parked by the\n * reservation like any other. `orgs/{orgId}/aiInsightDigests/{week}` records\n * the jobs; `aiInsightDigestQueue/{week}` lists the workspaces still owed a\n * delivery, so a run that delivers reads one document rather than every\n * workspace.\n *\n * ## Every run: deliver what is written\n *\n * A digest whose job is done and kept at least one insight is delivered once:\n * a `content.insightsDigest` notification (unless the person muted the\n * category) and an email through the platform's own sending path, to each\n * person who asked for the workspace's insights and reaches the site. A job\n * that failed, kept nothing, or parked for credits is SKIPPED SILENTLY: a\n * parked job is canceled rather than left to spend later, and nobody is told,\n * because nobody asked about that week in particular. A job still running\n * past `AI_INSIGHT_DIGEST_DEADLINE_MS` is canceled and skipped the same way.\n *\n * The email says only what the answer says: the insights, each traced to the\n * figures it cites, and a link to the site's Analytics page. It is sent by the\n * platform to a person who asked for it, never to a contact.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport const AI_INSIGHTS_DIGEST_CRON_ID = 'ai-insights-digest'\nexport const AI_INSIGHTS_DIGEST_PATH = 'admin/ai-insights-digest'\n\n/** Orgs one call reads; a chunk that times out never advances the cursor, so the safe size is one that finishes. */\nexport const AI_INSIGHT_DIGEST_ORG_CHUNK = 25\n\n/** Sites one workspace's digest covers a week. */\nexport const AI_INSIGHT_DIGEST_MAX_SITES = 5\n\n/** Sites a workspace's sweep reads before it ranks them. */\nexport const AI_INSIGHT_DIGEST_HOST_READ_LIMIT = 50\n\n/** Workspaces one run delivers to, per week. */\nexport const AI_INSIGHT_DIGEST_DELIVER_LIMIT = 100\n\n/** How long a digest's job may take before its week is given up. */\nexport const AI_INSIGHT_DIGEST_DEADLINE_MS = 48 * 60 * 60_000\n\n/**\n * The time one call works before it stops and leaves the rest to the next:\n * inside the plugin dispatcher's 60 s function ceiling, with room for the\n * reads before the first check and the reply after the last. A call killed\n * mid-send could send one person a site's digest twice, because a send is\n * stamped after it goes.\n */\nexport const AI_INSIGHT_DIGEST_RUN_BUDGET_MS = 45_000\n\nexport const AI_INSIGHT_DIGEST_MARKERS = 'aiInsightDigests'\nexport const AI_INSIGHT_DIGEST_QUEUE = 'aiInsightDigestQueue'\n\nexport type AiInsightDigestSiteState = 'pending' | 'delivered' | 'skipped'\n\nexport interface AiInsightDigestSite {\n jobId: string\n name: string\n state: AiInsightDigestSiteState\n /**\n * The people already sent this site's digest, so a run the send rate\n * stopped never sends one twice. Dropped when the site settles, so a\n * settled marker names no person.\n */\n sent?: Record<string, boolean>\n}\n\nexport interface AiInsightDigestMarker {\n week: string\n createdAtMs: number\n sites: Record<string, AiInsightDigestSite>\n}\n\n/** What a send answered: whether it went, and whether the platform's send rate refused it for now. */\nexport interface AiInsightDigestSendResult {\n sent: boolean\n rateLimited: boolean\n}\n\n/** Everything the sweep reaches beyond Firestore, so a spec can hold each one. */\nexport interface AiInsightDigestDeps {\n firestore: Firestore\n now: Date\n flagValue: ReleaseFlagValue\n listMembers: (orgId: string) => Promise<AglynOrgMember[]>\n mayGenerate: (orgId: string, hostId: string, member: AglynOrgMember) => Promise<boolean>\n paused: (orgId: string) => Promise<boolean>\n notify: (uid: string, payload: { title: string; body: string; link: string; orgId: string; hostId: string }) => Promise<void>\n send: (email: {\n to: string\n subject: string\n text: string\n fromName: string\n /** The site the digest is about, and the org whose brand it wears (AGL-3367). */\n siteName: string\n org: Record<string, unknown>\n /** The designed email's merge values, from {@link aiInsightDigestEmailParts}. */\n merge?: Record<string, string>\n }) => Promise<AiInsightDigestSendResult>\n /** The console's absolute origin for an email link, or `''` when none is configured. */\n consoleOrigin: string\n /** The call's working time; `AI_INSIGHT_DIGEST_RUN_BUDGET_MS` unless a spec holds it. */\n budgetMs?: number\n}\n\nexport interface AiInsightDigestReport {\n week: string\n swept: number\n created: number\n delivered: number\n skipped: number\n /** The send rate refused or the call's time ran out; the run stops, and the next one delivers the rest. */\n deferred: boolean\n nextCursor: string | null\n done: boolean\n}\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/** The week a Monday digest covers: the week the run falls in. */\nexport function aiInsightDigestWeek(now: Date): string {\n return aiInsightIsoWeek(now)\n}\n\n/** The week before, whose late digests a run still delivers. */\nfunction previousWeek(now: Date): string {\n return aiInsightIsoWeek(new Date(now.getTime() - 7 * 86_400_000))\n}\n\n/**\n * A digest email's words: the insights, the site's Analytics page, and where\n * to turn it off. The digest is an AI job metered against the workspace, so\n * it says what it drew, and it names the workspace a member of several asked\n * for it in.\n */\nexport function aiInsightDigestEmailText(input: {\n siteName: string\n productName: string\n insights: ReadonlyArray<{ text: string }>\n /** Absolute links, or `null` where no console origin is configured to build one from. */\n analyticsUrl: string | null\n settingsUrl: string | null\n /** The workspace the digest was asked for in; `''` falls back to \"this workspace\". */\n workspaceName?: string\n /** The AI credits the digest's job drew; 0 or absent says nothing. */\n creditsSpent?: number\n /** The week the figures cover, \"Oct 5 – Oct 11\"; absent says \"this week\". */\n periodLabel?: string\n}): string {\n const workspace = input.workspaceName?.trim() || ''\n const credits = Math.max(0, Math.round(Number(input.creditsSpent) || 0))\n const drew = credits\n ? ` Writing it used ${credits.toLocaleString('en-US')} of ` +\n `${workspace ? `${workspace}’s` : 'the workspace’s'} AI credits.`\n : ''\n const forWhom = workspace || 'this workspace'\n return [\n input.periodLabel\n ? `Here is what ${input.siteName}'s figures showed last week, ${input.periodLabel}.${drew}`\n : `Here is what ${input.siteName}'s figures showed this week.${drew}`,\n '',\n ...input.insights.map((insight, index) => `${index + 1}. ${insight.text}`),\n '',\n input.analyticsUrl\n ? `Each of these is traced to the figures it cites. See them in ${input.productName}: ${input.analyticsUrl}`\n : `Each of these is traced to the figures it cites. See them on the site's Analytics page in ${input.productName}.`,\n '',\n input.settingsUrl\n ? `You asked for weekly insights for ${forWhom}. Turn them off in Notifications: ${input.settingsUrl}`\n : `You asked for weekly insights for ${forWhom}. Turn them off in your Notifications settings.`,\n ].join('\\n')\n}\n\n/**\n * The same digest as {@link aiInsightDigestEmailText}, cut into the parts the\n * `ai-insights-digest` system email draws: the workspace and week above the\n * heading, the insights as a numbered list, a button to the site's\n * Analytics page, and why it came.\n */\nexport function aiInsightDigestEmailParts(\n input: Parameters<typeof aiInsightDigestEmailText>[0],\n): Record<\n 'digest.eyebrow' | 'digest.intro' | 'digest.insights' | 'digest.analyticsUrl' | 'digest.why',\n string\n> {\n const workspace = input.workspaceName?.trim() || ''\n const credits = Math.max(0, Math.round(Number(input.creditsSpent) || 0))\n const forWhom = workspace || 'this workspace'\n return {\n 'digest.eyebrow': [workspace, input.periodLabel?.trim()].filter(Boolean).join(' · '),\n 'digest.intro':\n `What ${input.siteName}'s figures showed ${input.periodLabel ? 'last week' : 'this week'}. ` +\n 'Each one is traced to the figures it cites, so you can check it on the Analytics page.',\n 'digest.insights': input.insights.map((insight, index) => `${index + 1}. ${insight.text}`).join('\\n\\n'),\n 'digest.analyticsUrl': input.analyticsUrl ?? '',\n 'digest.why':\n `You asked for weekly insights for ${forWhom}.` +\n (credits\n ? ` Writing these used ${credits.toLocaleString('en-US')} of ${workspace ? `${workspace}’s` : 'the workspace’s'} AI credits.`\n : '') +\n (input.settingsUrl\n ? ` Turn them off in Notifications: ${input.settingsUrl}`\n : ' Turn them off in your Notifications settings.'),\n }\n}\n\nasync function readUsers(firestore: Firestore, uids: readonly string[]) {\n if (!uids.length) return new Map<string, FirebaseFirestore.DocumentSnapshot>()\n const docs = await firestore.getAll(...uids.map((uid) => firestore.collection('users').doc(uid)))\n return new Map(docs.map((doc) => [doc.id, doc]))\n}\n\n/** Creates one workspace's digests for the week; answers how many jobs it created. */\nasync function createOrgDigest(\n deps: AiInsightDigestDeps,\n orgDoc: FirebaseFirestore.QueryDocumentSnapshot,\n week: string,\n): Promise<number> {\n const { firestore, now } = deps\n const orgId = orgDoc.id\n const org = (orgDoc.data() ?? {}) as Record<string, unknown>\n if (!checkEntitlement(org as never, 'aiGenerative')) return 0\n const flagOn = isReleaseFlagOnForOrg(\n 'release_ai_generative',\n deps.flagValue,\n orgId,\n parseOrgReleaseFlagOverrides(org['releaseFlags']),\n resolveEffectivePlan(org as never),\n )\n if (!flagOn || (await deps.paused(orgId))) return 0\n const markerRef = orgDoc.ref.collection(AI_INSIGHT_DIGEST_MARKERS).doc(week)\n if ((await markerRef.get()).exists) return 0\n\n const members = (await deps.listMembers(orgId)).filter((member) => member.orgSuspended !== true)\n const users = await readUsers(firestore, members.map((member) => member.$id).sort())\n const subscribers = members\n .filter((member) => insightDigestSubscribed(users.get(member.$id)?.get(INSIGHT_DIGESTS_FIELD), orgId))\n .sort((a, b) => a.$id.localeCompare(b.$id))\n if (!subscribers.length) return 0\n\n const hosts = await firestore\n .collection('hosts')\n .where('orgId', '==', orgId)\n .limit(AI_INSIGHT_DIGEST_HOST_READ_LIMIT)\n .get()\n const yesterday = new Date(now.getTime() - 86_400_000).toISOString().slice(0, 10)\n const candidates: Array<{ hostId: string; name: string; creator: string; views: number }> = []\n for (const host of hosts.docs) {\n const data = host.data() ?? {}\n if (!isAiOnForSite(org, data)) continue\n let creator: string | null = null\n for (const member of subscribers) {\n if (hostRoleFor(member, host.id) !== null && (await deps.mayGenerate(orgId, host.id, member))) {\n creator = member.$id\n break\n }\n }\n if (!creator) continue\n const day = await host.ref.collection('analytics').doc(yesterday).get()\n candidates.push({\n hostId: host.id,\n name: str(data['displayName']) || str(data['name']) || str(data['subdomain']) || host.id,\n creator,\n views: Number(day.get('total') ?? 0) || 0,\n })\n }\n const chosen = candidates\n .sort((a, b) => b.views - a.views || a.hostId.localeCompare(b.hostId))\n .slice(0, AI_INSIGHT_DIGEST_MAX_SITES)\n if (!chosen.length) return 0\n\n const sites: Record<string, AiInsightDigestSite> = {}\n for (const site of chosen) {\n const job = await createAiJob(\n firestore,\n {\n orgId,\n hostId: site.hostId,\n kind: 'insight',\n brief: `Weekly insights for ${site.name}`,\n inputs: { surface: 'digest', week, through: weeklySummaryPeriod(now).to },\n createdBy: site.creator,\n },\n now,\n )\n sites[site.hostId] = { jobId: job.$id, name: site.name, state: 'pending' }\n }\n const marker: AiInsightDigestMarker = { week, createdAtMs: now.getTime(), sites }\n await markerRef.set(marker)\n await firestore\n .collection(AI_INSIGHT_DIGEST_QUEUE)\n .doc(week)\n .set({ week, pending: { [orgId]: true } }, { merge: true })\n return chosen.length\n}\n\n/** Delivers or settles one workspace's digests for a week; `deferred` when the send rate refused. */\nasync function deliverOrgDigest(\n deps: AiInsightDigestDeps,\n orgId: string,\n week: string,\n overBudget: () => boolean,\n): Promise<{ delivered: number; skipped: number; settled: boolean; deferred: boolean }> {\n const { firestore, now } = deps\n const orgRef = firestore.collection('orgs').doc(orgId)\n const markerRef = orgRef.collection(AI_INSIGHT_DIGEST_MARKERS).doc(week)\n const markerSnapshot = await markerRef.get()\n const result = { delivered: 0, skipped: 0, settled: true, deferred: false }\n if (!markerSnapshot.exists) return result\n const marker = markerSnapshot.data() as AiInsightDigestMarker\n const org = ((await orgRef.get()).data() ?? {}) as Record<string, unknown>\n let members: AglynOrgMember[] | null = null\n const branding = resolveBrandingProfile(org as never)\n\n for (const [hostId, site] of Object.entries(marker.sites ?? {})) {\n if (site.state !== 'pending') continue\n const settle = async (state: AiInsightDigestSiteState) => {\n // Replaced whole rather than merged, which drops `sent`.\n const settled: AiInsightDigestSite = { jobId: site.jobId, name: site.name, state }\n await markerRef.update({ [`sites.${hostId}`]: settled })\n if (state === 'delivered') result.delivered += 1\n else result.skipped += 1\n }\n const job = await getAiJob(firestore, orgId, site.jobId)\n if (!job || job.status === 'failed' || job.status === 'canceled') {\n await settle('skipped')\n continue\n }\n if (job.status !== 'done') {\n const late = now.getTime() - Number(marker.createdAtMs ?? 0) > AI_INSIGHT_DIGEST_DEADLINE_MS\n // A job parked for credits — a Free workspace at its band — is given up\n // rather than left to spend on a week that is already over.\n if (job.status === 'needs_input' || late) {\n await cancelAiJob(firestore, orgId, site.jobId, now)\n await settle('skipped')\n } else {\n result.settled = false\n }\n continue\n }\n const answer = await orgRef.collection(AI_INSIGHTS_COLLECTION).doc(site.jobId).get()\n const record = answer.exists ? (answer.data() as AiInsightRecord) : null\n if (!record?.insights?.length) {\n await settle('skipped')\n continue\n }\n\n members ??= (await deps.listMembers(orgId)).filter((member) => member.orgSuspended !== true)\n const reaching = members.filter((member) => hostRoleFor(member, hostId) !== null)\n const users = await readUsers(firestore, reaching.map((member) => member.$id).sort())\n const host = (await firestore.collection('hosts').doc(hostId).get()).data() ?? {}\n const orgSlug = str(org['slug'])\n const subdomain = str(host['subdomain'])\n const origin = deps.consoleOrigin\n const analyticsUrl = origin && orgSlug && subdomain ? `${origin}/${orgSlug}/hosts/${subdomain}/analytics` : null\n for (const member of reaching.sort((a, b) => a.$id.localeCompare(b.$id))) {\n const user = users.get(member.$id)\n if (!insightDigestSubscribed(user?.get(INSIGHT_DIGESTS_FIELD), orgId)) continue\n if (site.sent?.[member.$id]) continue\n if (overBudget()) {\n // Out of time: what was sent is stamped, and the next run sends the rest.\n result.deferred = true\n result.settled = false\n return result\n }\n const address = str(member.email ?? user?.get('email')).toLowerCase()\n if (address.includes('@')) {\n const emailInput = {\n siteName: site.name,\n productName: branding.productName,\n insights: record.insights,\n analyticsUrl,\n settingsUrl: origin ? `${origin}/manage/notifications` : null,\n workspaceName: str(org['name']),\n creditsSpent: job.creditsSpent,\n periodLabel: aiInsightDigestPeriod(job.inputs, new Date(Number(marker.createdAtMs) || now.getTime())).label,\n }\n const sent = await deps.send({\n to: address,\n subject: `Your weekly insights for ${site.name}`,\n text: aiInsightDigestEmailText(emailInput),\n fromName: branding.fromName,\n siteName: site.name,\n org,\n merge: aiInsightDigestEmailParts(emailInput),\n })\n if (sent.rateLimited) {\n // Nothing is marked, so the next run delivers this site whole.\n result.deferred = true\n result.settled = false\n return result\n }\n }\n if (!notificationMuted(user?.get('notificationPrefs'), 'content.insightsDigest')) {\n await deps.notify(member.$id, {\n title: `Weekly insights · ${site.name}`,\n body: record.insights[0].text,\n link: `/${hostId}/analytics`,\n orgId,\n hostId,\n })\n }\n await markerRef.set({ sites: { [hostId]: { sent: { [member.$id]: true } } } }, { merge: true })\n }\n await settle('delivered')\n }\n return result\n}\n\n/**\n * One call of the sweep: delivery for this week and the last on the first\n * call, then — on a Monday — one chunk of workspaces' creation, resumed by\n * `cursor`. The response shape is the console crons' (`nextCursor`, `done`),\n * so the scheduler's loop carries a platform of any size across calls.\n */\nexport async function runAiInsightDigestSweep(\n deps: AiInsightDigestDeps,\n options: { cursor: string | null },\n): Promise<AiInsightDigestReport> {\n const { firestore, now } = deps\n const startedAtMs = Date.now()\n const budgetMs = deps.budgetMs ?? AI_INSIGHT_DIGEST_RUN_BUDGET_MS\n const overBudget = () => Date.now() - startedAtMs > budgetMs\n const week = aiInsightDigestWeek(now)\n const report: AiInsightDigestReport = {\n week,\n swept: 0,\n created: 0,\n delivered: 0,\n skipped: 0,\n deferred: false,\n nextCursor: null,\n done: true,\n }\n\n if (!options.cursor) {\n for (const owed of [previousWeek(now), week]) {\n const queueRef = firestore.collection(AI_INSIGHT_DIGEST_QUEUE).doc(owed)\n const pending = Object.entries(((await queueRef.get()).get('pending') ?? {}) as Record<string, unknown>)\n .filter(([, owed]) => owed === true)\n .map(([orgId]) => orgId)\n .sort()\n .slice(0, AI_INSIGHT_DIGEST_DELIVER_LIMIT)\n for (const orgId of pending) {\n if (overBudget()) {\n report.deferred = true\n return report\n }\n try {\n const delivered = await deliverOrgDigest(deps, orgId, owed, overBudget)\n report.delivered += delivered.delivered\n report.skipped += delivered.skipped\n if (delivered.settled) {\n await queueRef.set({ pending: { [orgId]: false } }, { merge: true })\n }\n if (delivered.deferred) {\n report.deferred = true\n return report\n }\n } catch (error) {\n console.error('ai insight digest delivery failed', { orgId, week: owed, error })\n }\n }\n }\n }\n\n // Monday is the week's first day by ISO 8601, and the day a digest is made.\n if (now.getUTCDay() !== 1) return report\n\n let query = firestore.collection('orgs').orderBy(FieldPath.documentId()).limit(AI_INSIGHT_DIGEST_ORG_CHUNK + 1)\n if (options.cursor) query = query.startAfter(firestore.collection('orgs').doc(options.cursor))\n const page = await query.get()\n const orgs = page.docs.slice(0, AI_INSIGHT_DIGEST_ORG_CHUNK)\n for (const [index, orgDoc] of orgs.entries()) {\n if (overBudget()) {\n // Out of time: the next call resumes after the last workspace read. A\n // call that read none has no cursor to hand on, and the next scheduled\n // run starts the week's workspaces again, which the markers make safe.\n report.nextCursor = index ? orgs[index - 1].id : (options.cursor ?? null)\n report.done = report.nextCursor === null\n return report\n }\n report.swept += 1\n try {\n report.created += await createOrgDigest(deps, orgDoc, week)\n } catch (error) {\n console.error('ai insight digest creation failed', { orgId: orgDoc.id, week, error })\n }\n }\n const more = page.docs.length > AI_INSIGHT_DIGEST_ORG_CHUNK\n report.nextCursor = more ? (orgs[orgs.length - 1]?.id ?? null) : null\n report.done = !more\n return report\n}\n"],"names":["FieldPath","INSIGHT_DIGESTS_FIELD","insightDigestSubscribed","notificationMuted","hostRoleFor","checkEntitlement","resolveBrandingProfile","resolveEffectivePlan","isReleaseFlagOnForOrg","parseOrgReleaseFlagOverrides","weeklySummaryPeriod","aiInsightDigestPeriod","AI_INSIGHTS_COLLECTION","aiInsightIsoWeek","isAiOnForSite","cancelAiJob","createAiJob","getAiJob","AI_INSIGHTS_DIGEST_CRON_ID","AI_INSIGHTS_DIGEST_PATH","AI_INSIGHT_DIGEST_ORG_CHUNK","AI_INSIGHT_DIGEST_MAX_SITES","AI_INSIGHT_DIGEST_HOST_READ_LIMIT","AI_INSIGHT_DIGEST_DELIVER_LIMIT","AI_INSIGHT_DIGEST_DEADLINE_MS","AI_INSIGHT_DIGEST_RUN_BUDGET_MS","AI_INSIGHT_DIGEST_MARKERS","AI_INSIGHT_DIGEST_QUEUE","str","value","trim","aiInsightDigestWeek","now","previousWeek","Date","getTime","aiInsightDigestEmailText","input","workspace","workspaceName","credits","Math","max","round","Number","creditsSpent","drew","toLocaleString","forWhom","periodLabel","siteName","insights","map","insight","index","text","analyticsUrl","productName","settingsUrl","join","aiInsightDigestEmailParts","filter","Boolean","readUsers","firestore","uids","length","Map","docs","getAll","uid","collection","doc","id","createOrgDigest","deps","orgDoc","week","orgId","org","data","flagOn","flagValue","paused","markerRef","ref","get","exists","members","listMembers","member","orgSuspended","users","$id","sort","subscribers","a","b","localeCompare","hosts","where","limit","yesterday","toISOString","slice","candidates","host","day","creator","mayGenerate","push","hostId","name","views","chosen","sites","site","job","kind","brief","inputs","surface","through","to","createdBy","jobId","state","marker","createdAtMs","set","pending","merge","deliverOrgDigest","overBudget","orgRef","markerSnapshot","result","delivered","skipped","settled","deferred","branding","Object","entries","record","settle","update","status","late","answer","reaching","orgSlug","subdomain","origin","consoleOrigin","user","sent","address","email","toLowerCase","includes","emailInput","label","send","subject","fromName","rateLimited","notify","title","body","link","runAiInsightDigestSweep","options","orgs","startedAtMs","budgetMs","report","swept","created","nextCursor","done","cursor","owed","queueRef","error","console","getUTCDay","query","orderBy","documentId","startAfter","page","more"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,SAAS,QAAQ,2BAA0B;AACpD,SAASC,qBAAqB,EAAEC,uBAAuB,EAAEC,iBAAiB,QAAQ,uCAAsC;AACxH,SAASC,WAAW,QAAQ,uCAAsC;AAClE,SAASC,gBAAgB,EAAEC,sBAAsB,EAAEC,oBAAoB,QAAQ,2CAA0C;AACzH,SAASC,qBAAqB,EAAEC,4BAA4B,QAA+B,uCAAsC;AAEjI,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SACEC,qBAAqB,EACrBC,sBAAsB,EACtBC,gBAAgB,QAEX,yBAAqB;AAC5B,SAASC,aAAa,QAAQ,6BAAyB;AACvD,SAASC,WAAW,EAAEC,WAAW,EAAEC,QAAQ,QAAQ,qBAAiB;AA+CpE,OAAO,MAAMC,6BAA6B,qBAAoB;AAC9D,OAAO,MAAMC,0BAA0B,2BAA0B;AAEjE,kHAAkH,GAClH,OAAO,MAAMC,8BAA8B,GAAE;AAE7C,gDAAgD,GAChD,OAAO,MAAMC,8BAA8B,EAAC;AAE5C,0DAA0D,GAC1D,OAAO,MAAMC,oCAAoC,GAAE;AAEnD,8CAA8C,GAC9C,OAAO,MAAMC,kCAAkC,IAAG;AAElD,kEAAkE,GAClE,OAAO,MAAMC,gCAAgC,KAAK,KAAK,MAAM;AAE7D;;;;;;CAMC,GACD,OAAO,MAAMC,kCAAkC,MAAM;AAErD,OAAO,MAAMC,4BAA4B,mBAAkB;AAC3D,OAAO,MAAMC,0BAA0B,uBAAsB;AAkE7D,MAAMC,MAAM,CAACC,QAA4B,OAAOA,UAAU,WAAWA,MAAMC,IAAI,KAAK;AAEpF,gEAAgE,GAChE,OAAO,SAASC,oBAAoBC,GAAS;IAC3C,OAAOn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pF;IAChC,KAAK,MAAM,CAACkC,OAAOsB,OAAO,IAAIiG,KAAK9B,OAAO,GAAI;QAC5C,IAAIV,cAAc;gBAIkCuC;YAHlD,sEAAsE;YACtE,uEAAuE;YACvE,uEAAuE;YACvEI,OAAOG,UAAU,GAAG7H,QAAQuH,IAAI,CAACvH,QAAQ,EAAE,CAACmB,EAAE,IAAImG,kBAAAA,QAAQS,MAAM,YAAdT,kBAAkB;YACpEI,OAAOI,IAAI,GAAGJ,OAAOG,UAAU,KAAK;YACpC,OAAOH;QACT;QACAA,OAAOC,KAAK,IAAI;QAChB,IAAI;YACFD,OAAOE,OAAO,IAAI,MAAMxG,gBAAgBC,MAAMC,QAAQC;QACxD,EAAE,OAAO2G,OAAO;YACdC,QAAQD,KAAK,CAAC,qCAAqC;gBAAE1G,OAAOF,OAAOH,EAAE;gBAAEI;gBAAM2G;YAAM;QACrF;IACF;IACA,MAAMQ,OAAOD,KAAK3H,IAAI,CAACF,MAAM,GAAG9C;IAChC4J,OAAOG,UAAU,GAAGa,gBAAQnB,SAAAA,IAAI,CAACA,KAAK3G,MAAM,GAAG,EAAE,qBAArB2G,OAAuBpG,EAAE,mBAAI,OAAQ;IACjEuG,OAAOI,IAAI,GAAG,CAACY;IACf,OAAOhB;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/insights/ai-insight-digest.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldPath } from 'firebase-admin/firestore'\nimport { INSIGHT_DIGESTS_FIELD, insightDigestSubscribed, notificationMuted } from '@aglyn/aglyn/app-utils/notifications'\nimport { liveCustomDomain, TENANT_APEX } from '@aglyn/aglyn/app-utils/host-naming'\nimport { hostRoleFor } from '@aglyn/aglyn/app-utils/organizations'\nimport { checkEntitlement, resolveBrandingProfile, resolveEffectivePlan } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { isReleaseFlagOnForOrg, parseOrgReleaseFlagOverrides, type ReleaseFlagValue } from '@aglyn/aglyn/app-utils/release-flags'\nimport type { AglynOrgMember } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport {\n weeklySummaryFootnoteHtml,\n weeklySummaryPeriod,\n weeklySummaryPlainDates,\n weeklySummarySectionsHtml,\n weeklySummaryTilesHtml,\n weeklySummaryWeekday,\n type WeeklySummaryColors,\n type WeeklySummarySection,\n type WeeklySummarySectionBar,\n type WeeklySummarySectionRow,\n} from '@aglyn/aglyn/app-utils/weekly-summary'\nimport {\n normalizePluginFigureTable,\n pluginFigureCellText,\n pluginFigureReader,\n type PluginFigureColumn,\n type PluginFigureSummaryStat,\n} from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n aiInsightDigestPeriod,\n aiInsightSourceHref,\n AI_INSIGHTS_COLLECTION,\n aiInsightIsoWeek,\n type AiInsight,\n type AiInsightRecord,\n type AiInsightTable,\n} from '../model/ai-insight'\nimport { isAiOnForSite } from '../model/ai-site-switch'\nimport { cancelAiJob, createAiJob, getAiJob } from '../jobs/ai-jobs'\n\n/**\n * THE WEEKLY INSIGHTS (AGL-2915): `POST /api/admin/ai-insights-digest`, twice\n * a day on the console's scheduler.\n *\n * ## Who asked for it\n *\n * A person turns weekly insights on for a workspace beside the answers\n * themselves (`users/{uid}.insightDigests.{orgId}`), and off there or in\n * Notifications. It is opt-in, because each digest is a generation the\n * workspace pays for. At the sweep, every rung is asked again rather than\n * trusted from the switch: the workspace's plan includes `aiGenerative`,\n * `release_ai_generative` is on for it, its AI is not paused, the site has AI\n * on, and the person still holds `ai.generate` on the site.\n *\n * ## Monday: one job per site\n *\n * On a Monday run, for each workspace with someone who asked, the sites those\n * people reach — the busiest `AI_INSIGHT_DIGEST_MAX_SITES` by yesterday's page\n * views — each get one `insight` job with the `digest` surface, created by the\n * first of them who may generate there. The job runs on the AI jobs beat like\n * any other: it reserves, meters and records its credits, and a workspace at\n * its band — a Free one that has used its credits — has its job parked by the\n * reservation like any other. `orgs/{orgId}/aiInsightDigests/{week}` records\n * the jobs; `aiInsightDigestQueue/{week}` lists the workspaces still owed a\n * delivery, so a run that delivers reads one document rather than every\n * workspace.\n *\n * ## Every run: deliver what is written\n *\n * A digest whose job is done and kept at least one insight is delivered once:\n * a `content.insightsDigest` notification (unless the person muted the\n * category) and an email through the platform's own sending path, to each\n * person who asked for the workspace's insights and reaches the site. A job\n * that failed, kept nothing, or parked for credits is SKIPPED SILENTLY: a\n * parked job is canceled rather than left to spend later, and nobody is told,\n * because nobody asked about that week in particular. A job still running\n * past `AI_INSIGHT_DIGEST_DEADLINE_MS` is canceled and skipped the same way.\n *\n * The email says only what the answer says, drawn to be run down rather than\n * read: the week's headline figures as tiles, then one section a topic, however\n * many insights cite it, each with its headline, the figures those insights\n * cite and a link to where they live. Every reader draws the same way, from its\n * table's own columns. It is sent by the platform to a person who asked for it,\n * never to a contact.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport const AI_INSIGHTS_DIGEST_CRON_ID = 'ai-insights-digest'\nexport const AI_INSIGHTS_DIGEST_PATH = 'admin/ai-insights-digest'\n\n/** Orgs one call reads; a chunk that times out never advances the cursor, so the safe size is one that finishes. */\nexport const AI_INSIGHT_DIGEST_ORG_CHUNK = 25\n\n/** Sites one workspace's digest covers a week. */\nexport const AI_INSIGHT_DIGEST_MAX_SITES = 5\n\n/** Sites a workspace's sweep reads before it ranks them. */\nexport const AI_INSIGHT_DIGEST_HOST_READ_LIMIT = 50\n\n/** Workspaces one run delivers to, per week. */\nexport const AI_INSIGHT_DIGEST_DELIVER_LIMIT = 100\n\n/** How long a digest's job may take before its week is given up. */\nexport const AI_INSIGHT_DIGEST_DEADLINE_MS = 48 * 60 * 60_000\n\n/**\n * The time one call works before it stops and leaves the rest to the next:\n * inside the plugin dispatcher's 60 s function ceiling, with room for the\n * reads before the first check and the reply after the last. A call killed\n * mid-send could send one person a site's digest twice, because a send is\n * stamped after it goes.\n */\nexport const AI_INSIGHT_DIGEST_RUN_BUDGET_MS = 45_000\n\nexport const AI_INSIGHT_DIGEST_MARKERS = 'aiInsightDigests'\nexport const AI_INSIGHT_DIGEST_QUEUE = 'aiInsightDigestQueue'\n\nexport type AiInsightDigestSiteState = 'pending' | 'delivered' | 'skipped'\n\nexport interface AiInsightDigestSite {\n jobId: string\n name: string\n state: AiInsightDigestSiteState\n /**\n * The people already sent this site's digest, so a run the send rate\n * stopped never sends one twice. Dropped when the site settles, so a\n * settled marker names no person.\n */\n sent?: Record<string, boolean>\n}\n\nexport interface AiInsightDigestMarker {\n week: string\n createdAtMs: number\n sites: Record<string, AiInsightDigestSite>\n}\n\n/** What a send answered: whether it went, and whether the platform's send rate refused it for now. */\nexport interface AiInsightDigestSendResult {\n sent: boolean\n rateLimited: boolean\n}\n\n/** Everything the sweep reaches beyond Firestore, so a spec can hold each one. */\nexport interface AiInsightDigestDeps {\n firestore: Firestore\n now: Date\n flagValue: ReleaseFlagValue\n listMembers: (orgId: string) => Promise<AglynOrgMember[]>\n mayGenerate: (orgId: string, hostId: string, member: AglynOrgMember) => Promise<boolean>\n paused: (orgId: string) => Promise<boolean>\n notify: (uid: string, payload: { title: string; body: string; link: string; orgId: string; hostId: string }) => Promise<void>\n send: (email: {\n to: string\n subject: string\n text: string\n fromName: string\n /** The site the digest is about, and the org whose brand it wears (AGL-3367). */\n siteName: string\n org: Record<string, unknown>\n /** The designed email's merge values, from {@link aiInsightDigestEmailParts}. */\n merge?: Record<string, string>\n }) => Promise<AiInsightDigestSendResult>\n /** The console's absolute origin for an email link, or `''` when none is configured. */\n consoleOrigin: string\n /** The org's email theme, as the digest's drawing needs it. */\n colors: (org: Record<string, unknown>) => WeeklySummaryColors\n /** The call's working time; `AI_INSIGHT_DIGEST_RUN_BUDGET_MS` unless a spec holds it. */\n budgetMs?: number\n}\n\nexport interface AiInsightDigestReport {\n week: string\n swept: number\n created: number\n delivered: number\n skipped: number\n /** The send rate refused or the call's time ran out; the run stops, and the next one delivers the rest. */\n deferred: boolean\n nextCursor: string | null\n done: boolean\n}\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/** The week a Monday digest covers: the week the run falls in. */\nexport function aiInsightDigestWeek(now: Date): string {\n return aiInsightIsoWeek(now)\n}\n\n/** The week before, whose late digests a run still delivers. */\nfunction previousWeek(now: Date): string {\n return aiInsightIsoWeek(new Date(now.getTime() - 7 * 86_400_000))\n}\n\n/**\n * A digest email's words: the insights, the site's Analytics page, and where\n * to turn it off. The digest is an AI job metered against the workspace, so\n * it says what it drew, and it names the workspace a member of several asked\n * for it in.\n */\nexport function aiInsightDigestEmailText(input: {\n siteName: string\n productName: string\n insights: ReadonlyArray<{ text: string }>\n /** Absolute links, or `null` where no console origin is configured to build one from. */\n analyticsUrl: string | null\n settingsUrl: string | null\n /** The workspace the digest was asked for in; `''` falls back to \"this workspace\". */\n workspaceName?: string\n /** The AI credits the digest's job drew; 0 or absent says nothing. */\n creditsSpent?: number\n /** The week the figures cover, \"Oct 5 – Oct 11\"; absent says \"this week\". */\n periodLabel?: string\n}): string {\n const workspace = input.workspaceName?.trim() || ''\n const credits = Math.max(0, Math.round(Number(input.creditsSpent) || 0))\n const drew = credits\n ? ` Writing it used ${credits.toLocaleString('en-US')} of ` +\n `${workspace ? `${workspace}’s` : 'the workspace’s'} AI credits.`\n : ''\n const forWhom = workspace || 'this workspace'\n return [\n input.periodLabel\n ? `Here is what ${input.siteName}'s figures showed last week, ${input.periodLabel}.${drew}`\n : `Here is what ${input.siteName}'s figures showed this week.${drew}`,\n '',\n ...input.insights.map((insight, index) => `${index + 1}. ${aiInsightDigestLine(insight)}`),\n '',\n input.analyticsUrl\n ? `Each of these is traced to the figures it cites. See them in ${input.productName}: ${input.analyticsUrl}`\n : `Each of these is traced to the figures it cites. See them on the site's Analytics page in ${input.productName}.`,\n '',\n input.settingsUrl\n ? `You asked for weekly insights for ${forWhom}. Turn them off in Notifications: ${input.settingsUrl}`\n : `You asked for weekly insights for ${forWhom}. Turn them off in your Notifications settings.`,\n ].join('\\n')\n}\n\n/** An insight in one line of plain text, its dates as a person says them. */\nfunction aiInsightDigestLine(insight: { text: string; headline?: string | null }): string {\n const text = weeklySummaryPlainDates(insight.text)\n return insight.headline ? `${insight.headline}: ${text}` : text\n}\n\n/** The most tiles the digest leads with: one row. */\nexport const AI_INSIGHT_DIGEST_MAX_TILES = 3\n\n/** The most rows a section lists. */\nexport const AI_INSIGHT_DIGEST_MAX_ROWS = 5\n\n/** The columns that hold a figure a row can show, as against a label or a change. */\nconst FIGURE_KINDS: ReadonlyArray<PluginFigureColumn['kind']> = ['count', 'money', 'percent', 'duration']\n\n/**\n * Each table the job read, as its reader's owner would headline it in the\n * weekly summary. Only a figure compared with the week before earns a tile: a\n * month's running count beside two weeks' does not read as the same kind of\n * thing.\n */\nfunction aiInsightDigestTiles(tables: readonly AiInsightTable[]): Array<{ ref: string; stats: readonly PluginFigureSummaryStat[] }> {\n return tables\n .flatMap((source) => {\n const summary = pluginFigureReader(source.reader)?.reader.weeklySummary\n const table = summary ? normalizePluginFigureTable(source) : null\n const stats = (table ? (summary?.summarize(table)?.stats ?? []) : []).filter((stat) => typeof stat.change === 'number')\n return stats.length ? [{ ref: source.ref, stats, order: summary?.order ?? 0 }] : []\n })\n .sort((a, b) => a.order - b.order)\n}\n\n/** The row numbers a set of insights cite in a table, each once, in the order they cite them. */\nfunction citedRows(insights: readonly AiInsight[], table: AiInsightTable): number[] {\n const rows = insights.flatMap((insight) =>\n insight.cites.filter((cite) => cite.table === table.ref).flatMap((cite) => cite.rows),\n )\n return [...new Set(rows)].filter((row) => Number.isInteger(row) && table.rows[row])\n}\n\n/** A row's label as a person reads it, and the page it names, when it names one. */\nfunction rowLabel(value: unknown, siteUrl: string | null): Pick<WeeklySummarySectionRow, 'label' | 'url'> {\n const label = String(value ?? '')\n const path = label.startsWith('/')\n return { label: label === '/' ? 'Home' : label, url: path && siteUrl ? `${siteUrl}${label === '/' ? '' : label}` : null }\n}\n\n/**\n * A section's figures, from the table's own columns, so a reader added\n * tomorrow draws without a line here: a table of days is a chart of the week\n * with the cited days marked, and any other is its cited rows, each with its\n * change where the table has one, else with its second figure.\n */\nfunction aiInsightDigestFigures(\n table: AiInsightTable,\n cited: readonly number[],\n siteUrl: string | null,\n): Pick<WeeklySummarySection, 'rows' | 'bars'> {\n const label = table.columns.find((column) => column.kind === 'text' || column.kind === 'date')\n const figures = table.columns.filter((column) => FIGURE_KINDS.includes(column.kind))\n const change = table.columns.find((column) => column.kind === 'change')\n if (!label || !figures.length || !cited.length) return {}\n // A `figure` row names what it counts. Any other row's count takes its column's word.\n const counted = label.key !== 'figure'\n const text = (column: PluginFigureColumn, row: AiInsightTable['rows'][number]) => {\n const cell = pluginFigureCellText(table, column.key, row[column.key])\n return counted && column.kind === 'count' ? `${cell} ${column.label.toLowerCase()}` : cell\n }\n if (label.kind === 'date') {\n const [figure] = figures\n const bars: WeeklySummarySectionBar[] = table.rows.map((row, index) => ({\n label: weeklySummaryWeekday(String(row[label.key])),\n value: Number(row[figure.key]) || 0,\n display: pluginFigureCellText(table, figure.key, row[figure.key]),\n marked: cited.includes(index),\n }))\n return { bars }\n }\n const shown = figures.slice(0, change ? 1 : 2)\n return {\n rows: cited.slice(0, AI_INSIGHT_DIGEST_MAX_ROWS).map((index) => {\n const row = table.rows[index]\n const moved = change ? row[change.key] : null\n return {\n ...rowLabel(row[label.key], siteUrl),\n value: shown.map((column) => text(column, row)).join(' · '),\n change: typeof moved === 'number' ? moved : null,\n }\n }),\n }\n}\n\n/** The digest's topics: one a table, however many insights cite it, in the order they first come up. */\nfunction aiInsightDigestSections(\n insights: readonly AiInsight[],\n input: { tables: readonly AiInsightTable[]; siteUrl: string | null; sourceUrl: (table: AiInsightTable) => string | null },\n): WeeklySummarySection[] {\n const groups = new Map<string, { table: AiInsightTable | null; insights: AiInsight[] }>()\n for (const insight of insights) {\n const ref = insight.cites[0]?.table ?? ''\n const group = groups.get(ref) ?? { table: input.tables.find((table) => table.ref === ref) ?? null, insights: [] }\n group.insights.push(insight)\n groups.set(ref, group)\n }\n return [...groups.values()].map(({ table, insights: said }) => {\n const url = table ? input.sourceUrl(table) : null\n return {\n title: table?.title ?? 'What changed',\n link: table && url ? { label: table.source.label, url } : null,\n points: said.map((insight) => ({\n headline: insight.headline?.trim() || null,\n text: weeklySummaryPlainDates(insight.text),\n })),\n ...(table ? aiInsightDigestFigures(table, citedRows(said, table), input.siteUrl) : {}),\n }\n })\n}\n\n/**\n * The digest's drawn parts: the week's figures as tiles, one section a topic,\n * and the small print. An insight that only says what the first tiles already\n * show is left out, so the email never makes a person read the same figures\n * twice.\n */\nexport function aiInsightDigestEmailHtml(input: {\n insights: readonly AiInsight[]\n tables: readonly AiInsightTable[]\n colors: WeeklySummaryColors\n /** The site's own address, which a row naming a page links to. */\n siteUrl: string | null\n /** Where a table's figures live in the console, absolute. */\n sourceUrl: (table: AiInsightTable) => string | null\n /** The sentence that says what the digest cost. */\n why: string\n settingsUrl: string | null\n}): Record<'digest.html' | 'digest.footnote', string> {\n const tiles = aiInsightDigestTiles(input.tables)\n const restated = (insight: AiInsight) =>\n insight.cites.length > 0 && insight.cites.every((cite) => cite.table === tiles[0]?.ref)\n const fresh = input.insights.filter((insight) => !restated(insight))\n return {\n 'digest.html':\n weeklySummaryTilesHtml(tiles.flatMap((part) => part.stats).slice(0, AI_INSIGHT_DIGEST_MAX_TILES), input.colors) +\n weeklySummarySectionsHtml(aiInsightDigestSections(fresh.length ? fresh : input.insights, input), input.colors),\n 'digest.footnote': weeklySummaryFootnoteHtml(\n input.why,\n input.settingsUrl ? { label: 'Turn off weekly insights', url: input.settingsUrl } : null,\n input.colors,\n ),\n }\n}\n\n/**\n * The same digest as {@link aiInsightDigestEmailText}, cut into the parts the\n * `ai-insights-digest` system email draws: the workspace and week above the\n * heading, the figures and insights, a button to the site's Analytics page,\n * what it cost, and where to turn it off.\n */\nexport function aiInsightDigestEmailParts(\n input: Parameters<typeof aiInsightDigestEmailText>[0],\n): Record<\n 'digest.eyebrow' | 'digest.intro' | 'digest.insights' | 'digest.analyticsUrl' | 'digest.why',\n string\n> {\n const workspace = input.workspaceName?.trim() || ''\n const credits = Math.max(0, Math.round(Number(input.creditsSpent) || 0))\n const spent = credits\n ? ` Writing these used ${credits.toLocaleString('en-US')} of ${workspace ? `${workspace}’s` : 'the workspace’s'} AI credits.`\n : ''\n return {\n 'digest.eyebrow': [workspace, input.periodLabel?.trim()].filter(Boolean).join(' · '),\n 'digest.intro':\n `What ${input.siteName}'s figures showed ${input.periodLabel ? 'last week' : 'this week'}. ` +\n 'Each one is traced to the figures it cites, so you can check it on the Analytics page.',\n 'digest.insights': input.insights\n .map((insight, index) => `${index + 1}. ${aiInsightDigestLine(insight)}`)\n .join('\\n\\n'),\n 'digest.analyticsUrl': input.analyticsUrl ?? '',\n 'digest.why': `Every number here is checked against ${input.siteName}'s own figures.${spent}`,\n }\n}\n\nasync function readUsers(firestore: Firestore, uids: readonly string[]) {\n if (!uids.length) return new Map<string, FirebaseFirestore.DocumentSnapshot>()\n const docs = await firestore.getAll(...uids.map((uid) => firestore.collection('users').doc(uid)))\n return new Map(docs.map((doc) => [doc.id, doc]))\n}\n\n/** Creates one workspace's digests for the week; answers how many jobs it created. */\nasync function createOrgDigest(\n deps: AiInsightDigestDeps,\n orgDoc: FirebaseFirestore.QueryDocumentSnapshot,\n week: string,\n): Promise<number> {\n const { firestore, now } = deps\n const orgId = orgDoc.id\n const org = (orgDoc.data() ?? {}) as Record<string, unknown>\n if (!checkEntitlement(org as never, 'aiGenerative')) return 0\n const flagOn = isReleaseFlagOnForOrg(\n 'release_ai_generative',\n deps.flagValue,\n orgId,\n parseOrgReleaseFlagOverrides(org['releaseFlags']),\n resolveEffectivePlan(org as never),\n )\n if (!flagOn || (await deps.paused(orgId))) return 0\n const markerRef = orgDoc.ref.collection(AI_INSIGHT_DIGEST_MARKERS).doc(week)\n if ((await markerRef.get()).exists) return 0\n\n const members = (await deps.listMembers(orgId)).filter((member) => member.orgSuspended !== true)\n const users = await readUsers(firestore, members.map((member) => member.$id).sort())\n const subscribers = members\n .filter((member) => insightDigestSubscribed(users.get(member.$id)?.get(INSIGHT_DIGESTS_FIELD), orgId))\n .sort((a, b) => a.$id.localeCompare(b.$id))\n if (!subscribers.length) return 0\n\n const hosts = await firestore\n .collection('hosts')\n .where('orgId', '==', orgId)\n .limit(AI_INSIGHT_DIGEST_HOST_READ_LIMIT)\n .get()\n const yesterday = new Date(now.getTime() - 86_400_000).toISOString().slice(0, 10)\n const candidates: Array<{ hostId: string; name: string; creator: string; views: number }> = []\n for (const host of hosts.docs) {\n const data = host.data() ?? {}\n if (!isAiOnForSite(org, data)) continue\n let creator: string | null = null\n for (const member of subscribers) {\n if (hostRoleFor(member, host.id) !== null && (await deps.mayGenerate(orgId, host.id, member))) {\n creator = member.$id\n break\n }\n }\n if (!creator) continue\n const day = await host.ref.collection('analytics').doc(yesterday).get()\n candidates.push({\n hostId: host.id,\n name: str(data['displayName']) || str(data['name']) || str(data['subdomain']) || host.id,\n creator,\n views: Number(day.get('total') ?? 0) || 0,\n })\n }\n const chosen = candidates\n .sort((a, b) => b.views - a.views || a.hostId.localeCompare(b.hostId))\n .slice(0, AI_INSIGHT_DIGEST_MAX_SITES)\n if (!chosen.length) return 0\n\n const sites: Record<string, AiInsightDigestSite> = {}\n for (const site of chosen) {\n const job = await createAiJob(\n firestore,\n {\n orgId,\n hostId: site.hostId,\n kind: 'insight',\n brief: `Weekly insights for ${site.name}`,\n inputs: { surface: 'digest', week, through: weeklySummaryPeriod(now).to },\n createdBy: site.creator,\n },\n now,\n )\n sites[site.hostId] = { jobId: job.$id, name: site.name, state: 'pending' }\n }\n const marker: AiInsightDigestMarker = { week, createdAtMs: now.getTime(), sites }\n await markerRef.set(marker)\n await firestore\n .collection(AI_INSIGHT_DIGEST_QUEUE)\n .doc(week)\n .set({ week, pending: { [orgId]: true } }, { merge: true })\n return chosen.length\n}\n\n/** Delivers or settles one workspace's digests for a week; `deferred` when the send rate refused. */\nasync function deliverOrgDigest(\n deps: AiInsightDigestDeps,\n orgId: string,\n week: string,\n overBudget: () => boolean,\n): Promise<{ delivered: number; skipped: number; settled: boolean; deferred: boolean }> {\n const { firestore, now } = deps\n const orgRef = firestore.collection('orgs').doc(orgId)\n const markerRef = orgRef.collection(AI_INSIGHT_DIGEST_MARKERS).doc(week)\n const markerSnapshot = await markerRef.get()\n const result = { delivered: 0, skipped: 0, settled: true, deferred: false }\n if (!markerSnapshot.exists) return result\n const marker = markerSnapshot.data() as AiInsightDigestMarker\n const org = ((await orgRef.get()).data() ?? {}) as Record<string, unknown>\n let members: AglynOrgMember[] | null = null\n const branding = resolveBrandingProfile(org as never)\n\n for (const [hostId, site] of Object.entries(marker.sites ?? {})) {\n if (site.state !== 'pending') continue\n const settle = async (state: AiInsightDigestSiteState) => {\n // Replaced whole rather than merged, which drops `sent`.\n const settled: AiInsightDigestSite = { jobId: site.jobId, name: site.name, state }\n await markerRef.update({ [`sites.${hostId}`]: settled })\n if (state === 'delivered') result.delivered += 1\n else result.skipped += 1\n }\n const job = await getAiJob(firestore, orgId, site.jobId)\n if (!job || job.status === 'failed' || job.status === 'canceled') {\n await settle('skipped')\n continue\n }\n if (job.status !== 'done') {\n const late = now.getTime() - Number(marker.createdAtMs ?? 0) > AI_INSIGHT_DIGEST_DEADLINE_MS\n // A job parked for credits — a Free workspace at its band — is given up\n // rather than left to spend on a week that is already over.\n if (job.status === 'needs_input' || late) {\n await cancelAiJob(firestore, orgId, site.jobId, now)\n await settle('skipped')\n } else {\n result.settled = false\n }\n continue\n }\n const answer = await orgRef.collection(AI_INSIGHTS_COLLECTION).doc(site.jobId).get()\n const record = answer.exists ? (answer.data() as AiInsightRecord) : null\n if (!record?.insights?.length) {\n await settle('skipped')\n continue\n }\n\n members ??= (await deps.listMembers(orgId)).filter((member) => member.orgSuspended !== true)\n const reaching = members.filter((member) => hostRoleFor(member, hostId) !== null)\n const users = await readUsers(firestore, reaching.map((member) => member.$id).sort())\n const host = (await firestore.collection('hosts').doc(hostId).get()).data() ?? {}\n const orgSlug = str(org['slug'])\n const subdomain = str(host['subdomain'])\n const origin = deps.consoleOrigin\n const analyticsUrl = origin && orgSlug && subdomain ? `${origin}/${orgSlug}/hosts/${subdomain}/analytics` : null\n for (const member of reaching.sort((a, b) => a.$id.localeCompare(b.$id))) {\n const user = users.get(member.$id)\n if (!insightDigestSubscribed(user?.get(INSIGHT_DIGESTS_FIELD), orgId)) continue\n if (site.sent?.[member.$id]) continue\n if (overBudget()) {\n // Out of time: what was sent is stamped, and the next run sends the rest.\n result.deferred = true\n result.settled = false\n return result\n }\n const address = str(member.email ?? user?.get('email')).toLowerCase()\n if (address.includes('@')) {\n const emailInput = {\n siteName: site.name,\n productName: branding.productName,\n insights: record.insights,\n analyticsUrl,\n settingsUrl: origin ? `${origin}/manage/notifications` : null,\n workspaceName: str(org['name']),\n creditsSpent: job.creditsSpent,\n periodLabel: aiInsightDigestPeriod(job.inputs, new Date(Number(marker.createdAtMs) || now.getTime())).label,\n }\n const parts = aiInsightDigestEmailParts(emailInput)\n const domain = liveCustomDomain(host as never) ?? (subdomain ? `${subdomain}.${TENANT_APEX}` : '')\n const sent = await deps.send({\n to: address,\n subject: `Your weekly insights for ${site.name}`,\n text: aiInsightDigestEmailText(emailInput),\n fromName: branding.fromName,\n siteName: site.name,\n org,\n merge: {\n ...parts,\n ...aiInsightDigestEmailHtml({\n insights: record.insights,\n tables: record.tables ?? [],\n colors: deps.colors(org),\n siteUrl: domain ? `https://${domain}` : null,\n sourceUrl: (table) => {\n const href = origin ? aiInsightSourceHref(table, { orgSlug, host: subdomain || null }) : null\n return href ? `${origin}${href}` : null\n },\n why: parts['digest.why'],\n settingsUrl: emailInput.settingsUrl,\n }),\n },\n })\n if (sent.rateLimited) {\n // Nothing is marked, so the next run delivers this site whole.\n result.deferred = true\n result.settled = false\n return result\n }\n }\n if (!notificationMuted(user?.get('notificationPrefs'), 'content.insightsDigest')) {\n await deps.notify(member.$id, {\n title: `Weekly insights · ${site.name}`,\n body: aiInsightDigestLine(record.insights[0]),\n link: `/${hostId}/analytics`,\n orgId,\n hostId,\n })\n }\n await markerRef.set({ sites: { [hostId]: { sent: { [member.$id]: true } } } }, { merge: true })\n }\n await settle('delivered')\n }\n return result\n}\n\n/**\n * One call of the sweep: delivery for this week and the last on the first\n * call, then — on a Monday — one chunk of workspaces' creation, resumed by\n * `cursor`. The response shape is the console crons' (`nextCursor`, `done`),\n * so the scheduler's loop carries a platform of any size across calls.\n */\nexport async function runAiInsightDigestSweep(\n deps: AiInsightDigestDeps,\n options: { cursor: string | null },\n): Promise<AiInsightDigestReport> {\n const { firestore, now } = deps\n const startedAtMs = Date.now()\n const budgetMs = deps.budgetMs ?? AI_INSIGHT_DIGEST_RUN_BUDGET_MS\n const overBudget = () => Date.now() - startedAtMs > budgetMs\n const week = aiInsightDigestWeek(now)\n const report: AiInsightDigestReport = {\n week,\n swept: 0,\n created: 0,\n delivered: 0,\n skipped: 0,\n deferred: false,\n nextCursor: null,\n done: true,\n }\n\n if (!options.cursor) {\n for (const owed of [previousWeek(now), week]) {\n const queueRef = firestore.collection(AI_INSIGHT_DIGEST_QUEUE).doc(owed)\n const pending = Object.entries(((await queueRef.get()).get('pending') ?? {}) as Record<string, unknown>)\n .filter(([, owed]) => owed === true)\n .map(([orgId]) => orgId)\n .sort()\n .slice(0, AI_INSIGHT_DIGEST_DELIVER_LIMIT)\n for (const orgId of pending) {\n if (overBudget()) {\n report.deferred = true\n return report\n }\n try {\n const delivered = await deliverOrgDigest(deps, orgId, owed, overBudget)\n report.delivered += delivered.delivered\n report.skipped += delivered.skipped\n if (delivered.settled) {\n await queueRef.set({ pending: { [orgId]: false } }, { merge: true })\n }\n if (delivered.deferred) {\n report.deferred = true\n return report\n }\n } catch (error) {\n console.error('ai insight digest delivery failed', { orgId, week: owed, error })\n }\n }\n }\n }\n\n // Monday is the week's first day by ISO 8601, and the day a digest is made.\n if (now.getUTCDay() !== 1) return report\n\n let query = firestore.collection('orgs').orderBy(FieldPath.documentId()).limit(AI_INSIGHT_DIGEST_ORG_CHUNK + 1)\n if (options.cursor) query = query.startAfter(firestore.collection('orgs').doc(options.cursor))\n const page = await query.get()\n const orgs = page.docs.slice(0, AI_INSIGHT_DIGEST_ORG_CHUNK)\n for (const [index, orgDoc] of orgs.entries()) {\n if (overBudget()) {\n // Out of time: the next call resumes after the last workspace read. A\n // call that read none has no cursor to hand on, and the next scheduled\n // run starts the week's workspaces again, which the markers make safe.\n report.nextCursor = index ? orgs[index - 1].id : (options.cursor ?? null)\n report.done = report.nextCursor === null\n return report\n }\n report.swept += 1\n try {\n report.created += await createOrgDigest(deps, orgDoc, week)\n } catch (error) {\n console.error('ai insight digest creation failed', { orgId: orgDoc.id, week, error })\n }\n }\n const more = page.docs.length > AI_INSIGHT_DIGEST_ORG_CHUNK\n report.nextCursor = more ? (orgs[orgs.length - 1]?.id ?? null) : null\n report.done = !more\n return report\n}\n"],"names":["FieldPath","INSIGHT_DIGESTS_FIELD","insightDigestSubscribed","notificationMuted","liveCustomDomain","TENANT_APEX","hostRoleFor","checkEntitlement","resolveBrandingProfile","resolveEffectivePlan","isReleaseFlagOnForOrg","parseOrgReleaseFlagOverrides","weeklySummaryFootnoteHtml","weeklySummaryPeriod","weeklySummaryPlainDates","weeklySummarySectionsHtml","weeklySummaryTilesHtml","weeklySummaryWeekday","normalizePluginFigureTable","pluginFigureCellText","pluginFigureReader","aiInsightDigestPeriod","aiInsightSourceHref","AI_INSIGHTS_COLLECTION","aiInsightIsoWeek","isAiOnForSite","cancelAiJob","createAiJob","getAiJob","AI_INSIGHTS_DIGEST_CRON_ID","AI_INSIGHTS_DIGEST_PATH","AI_INSIGHT_DIGEST_ORG_CHUNK","AI_INSIGHT_DIGEST_MAX_SITES","AI_INSIGHT_DIGEST_HOST_READ_LIMIT","AI_INSIGHT_DIGEST_DELIVER_LIMIT","AI_INSIGHT_DIGEST_DEADLINE_MS","AI_INSIGHT_DIGEST_RUN_BUDGET_MS","AI_INSIGHT_DIGEST_MARKERS","AI_INSIGHT_DIGEST_QUEUE","str","value","trim","aiInsightDigestWeek","now","previousWeek","Date","getTime","aiInsightDigestEmailText","input","workspace","workspaceName","credits","Math","max","round","Number","creditsSpent","drew","toLocaleString","forWhom","periodLabel","siteName","insights","map","insight","index","aiInsightDigestLine","analyticsUrl","productName","settingsUrl","join","text","headline","AI_INSIGHT_DIGEST_MAX_TILES","AI_INSIGHT_DIGEST_MAX_ROWS","FIGURE_KINDS","aiInsightDigestTiles","tables","flatMap","source","summary","reader","weeklySummary","table","stats","summarize","filter","stat","change","length","ref","order","sort","a","b","citedRows","rows","cites","cite","Set","row","isInteger","rowLabel","siteUrl","label","String","path","startsWith","url","aiInsightDigestFigures","cited","columns","find","column","kind","figures","includes","counted","key","cell","toLowerCase","figure","bars","display","marked","shown","slice","moved","aiInsightDigestSections","groups","Map","group","get","push","set","values","said","sourceUrl","title","link","points","aiInsightDigestEmailHtml","tiles","restated","every","fresh","part","colors","why","aiInsightDigestEmailParts","spent","Boolean","readUsers","firestore","uids","docs","getAll","uid","collection","doc","id","createOrgDigest","deps","orgDoc","week","orgId","org","data","flagOn","flagValue","paused","markerRef","exists","members","listMembers","member","orgSuspended","users","$id","subscribers","localeCompare","hosts","where","limit","yesterday","toISOString","candidates","host","day","creator","mayGenerate","hostId","name","views","chosen","sites","site","job","brief","inputs","surface","through","to","createdBy","jobId","state","marker","createdAtMs","pending","merge","deliverOrgDigest","overBudget","orgRef","markerSnapshot","result","delivered","skipped","settled","deferred","branding","Object","entries","record","settle","update","status","late","answer","reaching","orgSlug","subdomain","origin","consoleOrigin","user","sent","address","email","emailInput","parts","domain","send","subject","fromName","href","rateLimited","notify","body","runAiInsightDigestSweep","options","orgs","startedAtMs","budgetMs","report","swept","created","nextCursor","done","cursor","owed","queueRef","error","console","getUTCDay","query","orderBy","documentId","startAfter","page","more"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,SAAS,QAAQ,2BAA0B;AACpD,SAASC,qBAAqB,EAAEC,uBAAuB,EAAEC,iBAAiB,QAAQ,uCAAsC;AACxH,SAASC,gBAAgB,EAAEC,WAAW,QAAQ,qCAAoC;AAClF,SAASC,WAAW,QAAQ,uCAAsC;AAClE,SAASC,gBAAgB,EAAEC,sBAAsB,EAAEC,oBAAoB,QAAQ,2CAA0C;AACzH,SAASC,qBAAqB,EAAEC,4BAA4B,QAA+B,uCAAsC;AAEjI,SACEC,yBAAyB,EACzBC,mBAAmB,EACnBC,uBAAuB,EACvBC,yBAAyB,EACzBC,sBAAsB,EACtBC,oBAAoB,QAKf,wCAAuC;AAC9C,SACEC,0BAA0B,EAC1BC,oBAAoB,EACpBC,kBAAkB,QAGb,6CAA4C;AACnD,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,sBAAsB,EACtBC,gBAAgB,QAIX,yBAAqB;AAC5B,SAASC,aAAa,QAAQ,6BAAyB;AACvD,SAASC,WAAW,EAAEC,WAAW,EAAEC,QAAQ,QAAQ,qBAAiB;AAkDpE,OAAO,MAAMC,6BAA6B,qBAAoB;AAC9D,OAAO,MAAMC,0BAA0B,2BAA0B;AAEjE,kHAAkH,GAClH,OAAO,MAAMC,8BAA8B,GAAE;AAE7C,gDAAgD,GAChD,OAAO,MAAMC,8BAA8B,EAAC;AAE5C,0DAA0D,GAC1D,OAAO,MAAMC,oCAAoC,GAAE;AAEnD,8CAA8C,GAC9C,OAAO,MAAMC,kCAAkC,IAAG;AAElD,kEAAkE,GAClE,OAAO,MAAMC,gCAAgC,KAAK,KAAK,MAAM;AAE7D;;;;;;CAMC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C7B,KAAK,CAAC,GAAG/F;IAChC,KAAK,MAAM,CAACkC,OAAOkG,OAAO,IAAIsF,KAAK5B,OAAO,GAAI;QAC5C,IAAIV,cAAc;gBAIkCqC;YAHlD,sEAAsE;YACtE,uEAAuE;YACvE,uEAAuE;YACvEI,OAAOG,UAAU,GAAG9L,QAAQwL,IAAI,CAACxL,QAAQ,EAAE,CAAC+F,EAAE,IAAIwF,kBAAAA,QAAQS,MAAM,YAAdT,kBAAkB;YACpEI,OAAOI,IAAI,GAAGJ,OAAOG,UAAU,KAAK;YACpC,OAAOH;QACT;QACAA,OAAOC,KAAK,IAAI;QAChB,IAAI;YACFD,OAAOE,OAAO,IAAI,MAAM7F,gBAAgBC,MAAMC,QAAQC;QACxD,EAAE,OAAOgG,OAAO;YACdC,QAAQD,KAAK,CAAC,qCAAqC;gBAAE/F,OAAOF,OAAOH,EAAE;gBAAEI;gBAAMgG;YAAM;QACrF;IACF;IACA,MAAMQ,OAAOD,KAAKhH,IAAI,CAAClE,MAAM,GAAG1D;IAChC6N,OAAOG,UAAU,GAAGa,gBAAQnB,SAAAA,IAAI,CAACA,KAAKhK,MAAM,GAAG,EAAE,qBAArBgK,OAAuBzF,EAAE,mBAAI,OAAQ;IACjE4F,OAAOI,IAAI,GAAG,CAACY;IACf,OAAOhB;AACT"}
|
|
@@ -27,7 +27,7 @@ export declare const AI_INSIGHT_NO_READERS_COPY = "There are no figures to answe
|
|
|
27
27
|
export declare const AI_INSIGHT_NO_TABLES_COPY = "The figures could not be read. Try again in a moment.";
|
|
28
28
|
export declare const AI_INSIGHT_UNREADABLE_COPY = "The AI did not answer with insights. Try asking in different words.";
|
|
29
29
|
/** The digest's question: what a week's insights cover, in the order a person reads them. */
|
|
30
|
-
export declare const AI_INSIGHT_DIGEST_QUESTION = "What changed on this site last week, Monday to Sunday? Write the week\u2019s insights: the change in traffic, the most viewed page, the form that turned the most views into submissions, a campaign that did better than the rest, and any day that stood out \u2014 only those the tables support.";
|
|
30
|
+
export declare const AI_INSIGHT_DIGEST_QUESTION = "What changed on this site last week, Monday to Sunday? Write the week\u2019s insights: the change in traffic, the most viewed page, the form that turned the most views into submissions, a campaign that did better than the rest, and any day that stood out \u2014 only those the tables support. The email shows the week\u2019s visitors and page views above your insights, so do not restate those totals: say what moved them and what stood out.";
|
|
31
31
|
/** The rules both calls are sent: static, byte-identical for every workspace. */
|
|
32
32
|
export declare const AI_INSIGHT_RULES: string;
|
|
33
33
|
/** The system blocks both calls send: the rules and the platform's acceptable-use rules. */
|
|
@@ -35,7 +35,7 @@ export const AI_INSIGHT_NO_SITE_COPY = 'Open the site whose numbers you are aski
|
|
|
35
35
|
export const AI_INSIGHT_NO_READERS_COPY = 'There are no figures to answer from here yet: the features this page reports on are not on for this workspace.';
|
|
36
36
|
export const AI_INSIGHT_NO_TABLES_COPY = 'The figures could not be read. Try again in a moment.';
|
|
37
37
|
export const AI_INSIGHT_UNREADABLE_COPY = 'The AI did not answer with insights. Try asking in different words.';
|
|
38
|
-
/** The digest's question: what a week's insights cover, in the order a person reads them. */ export const AI_INSIGHT_DIGEST_QUESTION = 'What changed on this site last week, Monday to Sunday? Write the week’s insights: the change in traffic, the most viewed page, the form that turned the most views into submissions, a campaign that did better than the rest, and any day that stood out — only those the tables support.';
|
|
38
|
+
/** The digest's question: what a week's insights cover, in the order a person reads them. */ export const AI_INSIGHT_DIGEST_QUESTION = 'What changed on this site last week, Monday to Sunday? Write the week’s insights: the change in traffic, the most viewed page, the form that turned the most views into submissions, a campaign that did better than the rest, and any day that stood out — only those the tables support. The email shows the week’s visitors and page views above your insights, so do not restate those totals: say what moved them and what stood out.';
|
|
39
39
|
/** The rules both calls are sent: static, byte-identical for every workspace. */ export const AI_INSIGHT_RULES = [
|
|
40
40
|
'You answer a workspace owner’s questions about their own figures: page views, orders, bookings, forms, campaigns, A/B tests and datasets. You never see a record, and you never write a query: code reads figures through fixed readers and gives you their tables.',
|
|
41
41
|
'',
|
|
@@ -48,6 +48,10 @@ export const AI_INSIGHT_UNREADABLE_COPY = 'The AI did not answer with insights.
|
|
|
48
48
|
'- Say a figure rose or fell only when a change you quote shows it.',
|
|
49
49
|
'- Name nobody, and write no email address or phone number.',
|
|
50
50
|
'- Plain sentences: no markdown, no headings, no lists.',
|
|
51
|
+
'- Each insight has a headline saying what happened in a few words, the way a person would say it: “Visitors up 22.5%”, “Contact form converts best”. Its text is one short sentence on why that matters or what sits behind it. The figures you cite are shown beside it, so do not list them again.',
|
|
52
|
+
'- Write for someone reading on a phone: say one thing, and only what they would want to know.',
|
|
53
|
+
'- Write a date the way a person says it: Monday, Oct 26, never 2026-10-26.',
|
|
54
|
+
'- Leave out a percent change that rests on a handful of views.',
|
|
51
55
|
'- When the tables cannot answer part of the question, say so in gap in one sentence with no numbers; otherwise gap is null.',
|
|
52
56
|
'- Whether the site is published, its address and which pages are published come only from the Site status table. Page views and visitors never show whether a site or a page is live: never say or suggest a site is not live, not launched or not published because of its traffic, and never call the pages a views table lists the published ones.',
|
|
53
57
|
'- Write in the language of the question.'
|