@aglyn/plugins-ai 1.5.0 → 1.7.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/README.md +2 -2
- package/package.json +17 -17
- package/src/lib/components/ai-insight-dialog.component.js +14 -0
- package/src/lib/components/ai-insight-dialog.component.js.map +1 -1
- package/src/lib/components/ai-seo-audit-card.component.d.ts +7 -0
- package/src/lib/components/ai-seo-audit-card.component.js +32 -4
- package/src/lib/components/ai-seo-audit-card.component.js.map +1 -1
- package/src/lib/insights/ai-figure-readers.d.ts +13 -0
- package/src/lib/insights/ai-figure-readers.js +158 -11
- package/src/lib/insights/ai-figure-readers.js.map +1 -1
- package/src/lib/insights/ai-figure-summaries.js +4 -2
- package/src/lib/insights/ai-figure-summaries.js.map +1 -1
- package/src/lib/insights/ai-insight-digest.d.ts +27 -17
- package/src/lib/insights/ai-insight-digest.js +96 -107
- package/src/lib/insights/ai-insight-digest.js.map +1 -1
- package/src/lib/jobs/ai-job-insight-budget.d.ts +19 -3
- package/src/lib/jobs/ai-job-insight-budget.js +18 -4
- package/src/lib/jobs/ai-job-insight-budget.js.map +1 -1
- package/src/lib/jobs/ai-job-insight-step.d.ts +2 -2
- package/src/lib/jobs/ai-job-insight-step.js +17 -7
- package/src/lib/jobs/ai-job-insight-step.js.map +1 -1
- package/src/lib/jobs/ai-job-seo-step.d.ts +4 -0
- package/src/lib/jobs/ai-job-seo-step.js +9 -4
- package/src/lib/jobs/ai-job-seo-step.js.map +1 -1
- package/src/lib/jobs/ai-job-settings-step.d.ts +6 -2
- package/src/lib/jobs/ai-job-settings-step.js +45 -6
- package/src/lib/jobs/ai-job-settings-step.js.map +1 -1
- package/src/lib/jobs/ai-site-publish.js +1 -1
- package/src/lib/jobs/ai-site-publish.js.map +1 -1
- package/src/lib/model/ai-insight.d.ts +23 -3
- package/src/lib/model/ai-insight.js +17 -3
- package/src/lib/model/ai-insight.js.map +1 -1
- package/src/lib/model/ai-site-entity.d.ts +4 -4
- package/src/lib/model/ai-site-entity.js +3 -3
- package/src/lib/model/ai-site-entity.js.map +1 -1
- package/src/lib/providers/routing.js +3 -1
- package/src/lib/providers/routing.js.map +1 -1
- package/src/lib/runtime/ai-insight-check.d.ts +7 -0
- package/src/lib/runtime/ai-insight-check.js +111 -27
- package/src/lib/runtime/ai-insight-check.js.map +1 -1
- package/src/lib/tools/ai-insight-tool.js +45 -2
- package/src/lib/tools/ai-insight-tool.js.map +1 -1
|
@@ -30,11 +30,27 @@ export declare const AI_INSIGHT_READ_MAX_TOKENS = 400;
|
|
|
30
30
|
* dataset's first 2,000 records.
|
|
31
31
|
*/
|
|
32
32
|
export declare const AI_INSIGHT_READS_MS = 8000;
|
|
33
|
+
/**
|
|
34
|
+
* How a weekly digest thinks (AGL-4131). A question is phrased over figures
|
|
35
|
+
* and the routing row keeps it from thinking; a digest connects a week's
|
|
36
|
+
* tables and says what drove them, which is the reasoning the owner pays for.
|
|
37
|
+
*/
|
|
38
|
+
export declare const AI_INSIGHT_DIGEST_THINKING: {
|
|
39
|
+
readonly thinking: "adaptive";
|
|
40
|
+
readonly effort: "low";
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* A digest's ceiling: five insights at their bounds, each with its reason and
|
|
44
|
+
* next step and citing three tables of ten rows, the overview and the gap
|
|
45
|
+
* sentence, written as JSON: about 5,400 characters, 1,800 tokens at three
|
|
46
|
+
* characters a token, with as much again to think in.
|
|
47
|
+
*/
|
|
48
|
+
export declare const AI_INSIGHT_DIGEST_MAX_TOKENS = 4000;
|
|
33
49
|
/**
|
|
34
50
|
* The step's time: the read call and the answer with its one re-ask, sharing
|
|
35
|
-
* one allowance of twice the
|
|
36
|
-
*
|
|
37
|
-
*
|
|
51
|
+
* one allowance of twice the ceiling, on the tier `job.insight` is served
|
|
52
|
+
* from, after the readers read. A digest makes no read call, and its larger
|
|
53
|
+
* ceiling is what sizes the time.
|
|
38
54
|
*/
|
|
39
55
|
export declare const AI_JOB_INSIGHT_STEP_BUDGET: import("./ai-job-budget").AiJobStepBudget;
|
|
40
56
|
/** The least time one insight step needs before it starts. */
|
|
@@ -29,14 +29,28 @@ import { aiJobStepBudget } from "./ai-job-budget.js";
|
|
|
29
29
|
* tables, the heaviest a store's two windows of up to 1,000 orders each, or a
|
|
30
30
|
* dataset's first 2,000 records.
|
|
31
31
|
*/ export const AI_INSIGHT_READS_MS = 8000;
|
|
32
|
+
/**
|
|
33
|
+
* How a weekly digest thinks (AGL-4131). A question is phrased over figures
|
|
34
|
+
* and the routing row keeps it from thinking; a digest connects a week's
|
|
35
|
+
* tables and says what drove them, which is the reasoning the owner pays for.
|
|
36
|
+
*/ export const AI_INSIGHT_DIGEST_THINKING = {
|
|
37
|
+
thinking: 'adaptive',
|
|
38
|
+
effort: 'low'
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* A digest's ceiling: five insights at their bounds, each with its reason and
|
|
42
|
+
* next step and citing three tables of ten rows, the overview and the gap
|
|
43
|
+
* sentence, written as JSON: about 5,400 characters, 1,800 tokens at three
|
|
44
|
+
* characters a token, with as much again to think in.
|
|
45
|
+
*/ export const AI_INSIGHT_DIGEST_MAX_TOKENS = 4000;
|
|
32
46
|
/**
|
|
33
47
|
* The step's time: the read call and the answer with its one re-ask, sharing
|
|
34
|
-
* one allowance of twice the
|
|
35
|
-
*
|
|
36
|
-
*
|
|
48
|
+
* one allowance of twice the ceiling, on the tier `job.insight` is served
|
|
49
|
+
* from, after the readers read. A digest makes no read call, and its larger
|
|
50
|
+
* ceiling is what sizes the time.
|
|
37
51
|
*/ export const AI_JOB_INSIGHT_STEP_BUDGET = aiJobStepBudget({
|
|
38
52
|
tier: AI_STEP_TIERS['job.insight'],
|
|
39
|
-
maxTokens: AI_ROUTING_TABLE['job.insight'].maxTokens,
|
|
53
|
+
maxTokens: Math.max(AI_ROUTING_TABLE['job.insight'].maxTokens, AI_INSIGHT_DIGEST_MAX_TOKENS),
|
|
40
54
|
attempts: 2,
|
|
41
55
|
lookups: 1,
|
|
42
56
|
ownReadsMs: AI_INSIGHT_READS_MS
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-insight-budget.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 { AI_STEP_TIERS } from '../providers/catalog'\nimport { AI_ROUTING_TABLE } from '../providers/routing'\nimport { aiJobStepBudget } from './ai-job-budget'\n\n/**\n * The time an insight step needs (AGL-2915, AGL-3035), declared apart from the\n * step so the machine and the specs read it without loading the readers.\n */\n\n/**\n * The read call's ceiling: a few reads, each a reader id, a window and its\n * parameters. It is spent from the same allowance as the answer, so it adds a\n * wait for a first token and no output of its own to the worst case.\n */\nexport const AI_INSIGHT_READ_MAX_TOKENS = 400\n\n/**\n * ASSUMED: how long the readers take between the two calls — up to four\n * tables, the heaviest a store's two windows of up to 1,000 orders each, or a\n * dataset's first 2,000 records.\n */\nexport const AI_INSIGHT_READS_MS = 8_000\n\n/**\n * The step's time: the read call and the answer with its one re-ask, sharing\n * one allowance of twice the
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-insight-budget.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 { AI_STEP_TIERS } from '../providers/catalog'\nimport { AI_ROUTING_TABLE } from '../providers/routing'\nimport { aiJobStepBudget } from './ai-job-budget'\n\n/**\n * The time an insight step needs (AGL-2915, AGL-3035), declared apart from the\n * step so the machine and the specs read it without loading the readers.\n */\n\n/**\n * The read call's ceiling: a few reads, each a reader id, a window and its\n * parameters. It is spent from the same allowance as the answer, so it adds a\n * wait for a first token and no output of its own to the worst case.\n */\nexport const AI_INSIGHT_READ_MAX_TOKENS = 400\n\n/**\n * ASSUMED: how long the readers take between the two calls — up to four\n * tables, the heaviest a store's two windows of up to 1,000 orders each, or a\n * dataset's first 2,000 records.\n */\nexport const AI_INSIGHT_READS_MS = 8_000\n\n/**\n * How a weekly digest thinks (AGL-4131). A question is phrased over figures\n * and the routing row keeps it from thinking; a digest connects a week's\n * tables and says what drove them, which is the reasoning the owner pays for.\n */\nexport const AI_INSIGHT_DIGEST_THINKING = { thinking: 'adaptive', effort: 'low' } as const\n\n/**\n * A digest's ceiling: five insights at their bounds, each with its reason and\n * next step and citing three tables of ten rows, the overview and the gap\n * sentence, written as JSON: about 5,400 characters, 1,800 tokens at three\n * characters a token, with as much again to think in.\n */\nexport const AI_INSIGHT_DIGEST_MAX_TOKENS = 4_000\n\n/**\n * The step's time: the read call and the answer with its one re-ask, sharing\n * one allowance of twice the ceiling, on the tier `job.insight` is served\n * from, after the readers read. A digest makes no read call, and its larger\n * ceiling is what sizes the time.\n */\nexport const AI_JOB_INSIGHT_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.insight'],\n maxTokens: Math.max(AI_ROUTING_TABLE['job.insight'].maxTokens, AI_INSIGHT_DIGEST_MAX_TOKENS),\n attempts: 2,\n lookups: 1,\n ownReadsMs: AI_INSIGHT_READS_MS,\n})\n\n/** The least time one insight step needs before it starts. */\nexport const AI_JOB_INSIGHT_STEP_MINIMUM_MS = AI_JOB_INSIGHT_STEP_BUDGET.minimumMs\n"],"names":["AI_STEP_TIERS","AI_ROUTING_TABLE","aiJobStepBudget","AI_INSIGHT_READ_MAX_TOKENS","AI_INSIGHT_READS_MS","AI_INSIGHT_DIGEST_THINKING","thinking","effort","AI_INSIGHT_DIGEST_MAX_TOKENS","AI_JOB_INSIGHT_STEP_BUDGET","tier","maxTokens","Math","max","attempts","lookups","ownReadsMs","AI_JOB_INSIGHT_STEP_MINIMUM_MS","minimumMs"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,0BAAsB;AACpD,SAASC,gBAAgB,QAAQ,0BAAsB;AACvD,SAASC,eAAe,QAAQ,qBAAiB;AAEjD;;;CAGC,GAED;;;;CAIC,GACD,OAAO,MAAMC,6BAA6B,IAAG;AAE7C;;;;CAIC,GACD,OAAO,MAAMC,sBAAsB,KAAK;AAExC;;;;CAIC,GACD,OAAO,MAAMC,6BAA6B;IAAEC,UAAU;IAAYC,QAAQ;AAAM,EAAU;AAE1F;;;;;CAKC,GACD,OAAO,MAAMC,+BAA+B,KAAK;AAEjD;;;;;CAKC,GACD,OAAO,MAAMC,6BAA6BP,gBAAgB;IACxDQ,MAAMV,aAAa,CAAC,cAAc;IAClCW,WAAWC,KAAKC,GAAG,CAACZ,gBAAgB,CAAC,cAAc,CAACU,SAAS,EAAEH;IAC/DM,UAAU;IACVC,SAAS;IACTC,YAAYZ;AACd,GAAE;AAEF,4DAA4D,GAC5D,OAAO,MAAMa,iCAAiCR,2BAA2BS,SAAS,CAAA"}
|
|
@@ -26,8 +26,8 @@ export declare const AI_INSIGHT_NO_SITE_COPY = "Open the site whose numbers you
|
|
|
26
26
|
export declare 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.";
|
|
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
|
-
/** The digest's question: what
|
|
30
|
-
export declare const AI_INSIGHT_DIGEST_QUESTION = "What
|
|
29
|
+
/** The digest's question: what the week meant, why and what to do, in the owner's words. */
|
|
30
|
+
export declare const AI_INSIGHT_DIGEST_QUESTION = "What happened on this site last week, Monday to Sunday, why, and what should the owner do next? The owner already gets an email listing the week\u2019s figures, so never recite them. Write the overview, then the moves worth talking about, each with what most likely drove it: compare the days and pages that moved with what changed on the site, where visits came from and any campaign. Only what the tables support.";
|
|
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. */
|
|
@@ -28,14 +28,14 @@ import { aiDatasetCatalog } from "../insights/ai-dataset-catalog.js";
|
|
|
28
28
|
import { aiInsightDatasetCatalog, aiInsightReaderCatalog, aiInsightReaderDays, aiInsightReaders, aiInsightTableText, readAiInsightTables } from "../insights/ai-insight-readers.js";
|
|
29
29
|
import { assistExchangeExpiry } from "../usage/assist-usage.js";
|
|
30
30
|
import { registerAiJobAdmission } from "./ai-job-admission.js";
|
|
31
|
-
import { AI_INSIGHT_READ_MAX_TOKENS, AI_JOB_INSIGHT_STEP_BUDGET, AI_JOB_INSIGHT_STEP_MINIMUM_MS } from "./ai-job-insight-budget.js";
|
|
31
|
+
import { AI_INSIGHT_DIGEST_THINKING, AI_INSIGHT_READ_MAX_TOKENS, AI_JOB_INSIGHT_STEP_BUDGET, AI_JOB_INSIGHT_STEP_MINIMUM_MS } from "./ai-job-insight-budget.js";
|
|
32
32
|
import { registerAiJobStep } from "./ai-jobs.js";
|
|
33
33
|
export const AI_INSIGHT_NO_SURFACE_COPY = 'This question does not say which page it was asked from.';
|
|
34
34
|
export const AI_INSIGHT_NO_SITE_COPY = 'Open the site whose numbers you are asking about.';
|
|
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
|
|
38
|
+
/** The digest's question: what the week meant, why and what to do, in the owner's words. */ export const AI_INSIGHT_DIGEST_QUESTION = 'What happened on this site last week, Monday to Sunday, why, and what should the owner do next? The owner already gets an email listing the week’s figures, so never recite them. Write the overview, then the moves worth talking about, each with what most likely drove it: compare the days and pages that moved with what changed on the site, where visits came from and any campaign. Only what the tables support.';
|
|
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
|
'',
|
|
@@ -43,6 +43,7 @@ export const AI_INSIGHT_UNREADABLE_COPY = 'The AI did not answer with insights.
|
|
|
43
43
|
'',
|
|
44
44
|
`When you are given tables, call ${AI_INSIGHT_ANSWER_TOOL_NAME} once. Each table has a handle (t1, t2, …) and numbered rows. Rules for the insights:`,
|
|
45
45
|
'- Say what matters most to the question first. Leave out what the tables do not support.',
|
|
46
|
+
'- Read the figures like the owner’s analyst: say what a move means and connect the tables, never just repeat a row.',
|
|
46
47
|
'- Every insight cites the table and the rows its figures come from.',
|
|
47
48
|
'- Every number you write appears in a row you cite, as the table shows it or rounded. Never add, subtract, average or otherwise compute a figure yourself. The only other numbers you may write are the length of a table’s window, a date in it, and how many rows you cite.',
|
|
48
49
|
'- Say a figure rose or fell only when a change you quote shows it.',
|
|
@@ -52,6 +53,10 @@ export const AI_INSIGHT_UNREADABLE_COPY = 'The AI did not answer with insights.
|
|
|
52
53
|
'- Write for someone reading on a phone: say one thing, and only what they would want to know.',
|
|
53
54
|
'- Write a date the way a person says it: Monday, Oct 26, never 2026-10-26.',
|
|
54
55
|
'- Leave out a percent change that rests on a handful of views.',
|
|
56
|
+
'- why says what most likely drove a move, in one short sentence, and must cite the row it rests on: a dated change, a source or a campaign. Write the reason alone: a label already calls it likely. Two things happening together does not prove one caused the other. When nothing in those tables explains a move, set why to null and say so in text.',
|
|
57
|
+
'- A source or campaign whose change shows it held steady cannot explain a move: steady traffic does not make a page rise or fall.',
|
|
58
|
+
'- next is one concrete step the owner can take in the console or on their site, for this insight. Name only something that exists, and never promise a result. null when none fits.',
|
|
59
|
+
'- overview is for a weekly digest: what the week meant in two or three sentences of your own, not a list of figures. On a question, overview is null, and why and next are null unless the question asks why or what to do.',
|
|
55
60
|
'- When the tables cannot answer part of the question, say so in gap in one sentence with no numbers; otherwise gap is null.',
|
|
56
61
|
'- 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.',
|
|
57
62
|
'- Write in the language of the question.'
|
|
@@ -198,7 +203,10 @@ export const runAiJobInsightStep = async (context)=>{
|
|
|
198
203
|
const digest = surface === 'digest';
|
|
199
204
|
const days = digest ? AI_INSIGHT_DIGEST_DAYS : aiInsightDays((_job_inputs = job.inputs) == null ? void 0 : _job_inputs['days']);
|
|
200
205
|
const question = digest ? AI_INSIGHT_DIGEST_QUESTION : job.brief.slice(0, AI_INSIGHT_QUESTION_MAX_CHARS);
|
|
201
|
-
const
|
|
206
|
+
const route = AI_ROUTING_TABLE['job.insight'];
|
|
207
|
+
// The budget is sized for a digest's ceiling; a question keeps the row's.
|
|
208
|
+
const fits = AI_JOB_INSIGHT_STEP_BUDGET.maxTokens(model);
|
|
209
|
+
const maxTokens = digest ? fits : Math.min(fits, route.maxTokens);
|
|
202
210
|
const allowance = AI_GENERATION_MAX_ATTEMPTS * maxTokens;
|
|
203
211
|
const left = ()=>allowance - spend.usage.outputTokens;
|
|
204
212
|
// What the business is and what the owner's edits showed (AGL-3661), so an
|
|
@@ -216,8 +224,9 @@ export const runAiJobInsightStep = async (context)=>{
|
|
|
216
224
|
contact: false
|
|
217
225
|
}) : null)
|
|
218
226
|
];
|
|
219
|
-
// A development run's effort A/B arm (AGL-3781), else the row's.
|
|
220
|
-
const effort = (_aiDevEffortFor = aiDevEffortFor('job.insight')) != null ? _aiDevEffortFor :
|
|
227
|
+
// A development run's effort A/B arm (AGL-3781), else the digest's or the row's.
|
|
228
|
+
const effort = (_aiDevEffortFor = aiDevEffortFor('job.insight')) != null ? _aiDevEffortFor : digest ? AI_INSIGHT_DIGEST_THINKING.effort : route.effort;
|
|
229
|
+
const thinking = digest ? AI_INSIGHT_DIGEST_THINKING.thinking : route.thinking;
|
|
221
230
|
// Both tools on both calls, so the answer call reads the prefix the read call wrote (AGL-4076).
|
|
222
231
|
const tools = aiInsightTools();
|
|
223
232
|
const ask = (messages, tool, ceiling)=>runAiRequest(_extends({
|
|
@@ -227,8 +236,8 @@ export const runAiJobInsightStep = async (context)=>{
|
|
|
227
236
|
tools,
|
|
228
237
|
toolChoice: tool === 'read' ? AI_INSIGHT_READ_TOOL_NAME : AI_INSIGHT_ANSWER_TOOL_NAME,
|
|
229
238
|
maxTokens: Math.max(1, Math.min(ceiling, left()))
|
|
230
|
-
},
|
|
231
|
-
thinking
|
|
239
|
+
}, thinking ? {
|
|
240
|
+
thinking
|
|
232
241
|
} : {}, effort ? {
|
|
233
242
|
effort
|
|
234
243
|
} : {}, {
|
|
@@ -330,6 +339,7 @@ export const runAiJobInsightStep = async (context)=>{
|
|
|
330
339
|
createdBy: job.createdBy,
|
|
331
340
|
question: digest ? str(job.brief) || 'Weekly insights' : question,
|
|
332
341
|
days,
|
|
342
|
+
overview: digest ? checked.overview : null,
|
|
333
343
|
insights: checked.kept,
|
|
334
344
|
gap: checked.gap,
|
|
335
345
|
tables,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-insight-step.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 type { ResolvedPluginFigureReader } from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n AI_INSIGHT_ASK_SURFACES,\n AI_INSIGHT_DIGEST_DAYS,\n AI_INSIGHT_DIGEST_READERS,\n AI_INSIGHT_QUESTION_MAX_CHARS,\n AI_INSIGHTS_COLLECTION,\n aiInsightDays,\n aiInsightDigestPeriod,\n aiInsightOutput,\n aiInsightSurface,\n aiInsightSurfaceNeedsSite,\n type AiInsightRecord,\n type AiInsightSurface,\n type AiInsightTable,\n} from '../model/ai-insight'\nimport { aiHostPublishContext, aiSiteStatusTable } from '../model/ai-host-publish-context'\nimport { aiInstructionsWithSiteContext } from '../model/ai-site-context'\nimport { readAiSiteContext } from '../runtime/site-context'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport { aiDevEffortFor } from '../runtime/ai-dev-env'\nimport {\n AI_ACCEPTABLE_USE_BLOCK,\n runAiRequest,\n type AiMessage,\n type AiResult,\n type AiSystemBlock,\n type AiUsage,\n} from '../runtime/ai-runtime'\nimport type { AiTool } from '../providers/contract'\nimport { AI_GENERATION_MAX_ATTEMPTS } from '../runtime/ai-generation-bounds'\nimport { checkAiInsightAnswer, type AiInsightCheck } from '../runtime/ai-insight-check'\nimport {\n AI_INSIGHT_ANSWER_TOOL_NAME,\n AI_INSIGHT_READ_TOOL_NAME,\n aiInsightAnswerTool,\n aiInsightReadTool,\n parseAiInsightAnswer,\n parseAiInsightReads,\n type AiInsightReadRequest,\n} from '../tools/ai-insight-tool'\nimport { aiDatasetCatalog } from '../insights/ai-dataset-catalog'\nimport {\n aiInsightDatasetCatalog,\n aiInsightReaderCatalog,\n aiInsightReaderDays,\n aiInsightReaders,\n aiInsightTableText,\n readAiInsightTables,\n} from '../insights/ai-insight-readers'\nimport { assistExchangeExpiry } from '../usage/assist-usage'\nimport { registerAiJobAdmission, type AiJobAdmissionContext, type AiJobAdmissionRefusal } from './ai-job-admission'\nimport { AI_INSIGHT_READ_MAX_TOKENS, AI_JOB_INSIGHT_STEP_BUDGET, AI_JOB_INSIGHT_STEP_MINIMUM_MS } from './ai-job-insight-budget'\nimport type { AiJobStepContext, AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The `insight` step (AGL-2915): a question about a site's figures, answered\n * from tables code read, with every insight traced to the rows it cites.\n *\n * ## Two exchanges, and the model never writes a query\n *\n * 1. **The reads.** The model is shown the question and the readers this job\n * may read — each an id, what it answers, its windows and parameters — and\n * answers `read_figures` with a choice among them. It names nothing else: no\n * collection, no field path, no filter. A choice that names no reader this\n * job may read is dropped, and a job left with none reads the surface's\n * defaults. A weekly digest makes no read call: code reads the digest's\n * readers.\n * 2. **The answer.** Code reads the tables through the owners' readers, and the\n * model is shown them and answers `submit_insights`. The trace\n * (`runtime/ai-insight-check.ts`) keeps each insight whose every number is\n * in a row it cites and leaves out the rest. An answer that is not a call,\n * or whose every insight was left out, is asked for once more with the\n * reasons; what the second answer keeps is the answer.\n *\n * Both calls share one allowance of output, twice the routing ceiling, which\n * is what the step's least time is planned against.\n *\n * ## What reaches the model\n *\n * The question, the names and descriptions of the readers, the tables, the\n * site's publish state (published or not, its address, its pages' paths), and\n * for a datasets question the names of the datasets the member may see with\n * their fields' names and types. A table holds counts, sums and rates labeled\n * by a page path, a referring site, a form's, a service's, a product's or a\n * campaign's name, or the values of a dataset field with at most sixty\n * different values that at least three records share. No\n * record, visitor, contact, order, booking, submission or recipient is read\n * into a prompt, and every text cell is masked of email addresses and phone\n * numbers on its way into a table.\n *\n * ## What it writes\n *\n * The answer, at `orgs/{orgId}/aiInsights/{jobId}` under the job's own\n * expiry, and an output that names it and says how many insights it holds.\n * Nothing else: no draft, no setting, no message.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport const AI_INSIGHT_NO_SURFACE_COPY = 'This question does not say which page it was asked from.'\nexport const AI_INSIGHT_NO_SITE_COPY = 'Open the site whose numbers you are asking about.'\nexport const AI_INSIGHT_NO_READERS_COPY =\n 'There are no figures to answer from here yet: the features this page reports on are not on for this workspace.'\nexport const AI_INSIGHT_NO_TABLES_COPY = 'The figures could not be read. Try again in a moment.'\nexport const AI_INSIGHT_UNREADABLE_COPY = 'The AI did not answer with insights. Try asking in different words.'\n\n/** The digest's question: what a week's insights cover, in the order a person reads them. */\nexport const AI_INSIGHT_DIGEST_QUESTION =\n '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.'\n\n/** The rules both calls are sent: static, byte-identical for every workspace. */\nexport const AI_INSIGHT_RULES = [\n '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.',\n '',\n `When you are given a question and a list of readers, call ${AI_INSIGHT_READ_TOOL_NAME} once with the readers whose tables answer it, most useful first, and the window each should cover. Choose only readers from the list, with their parameters' values taken from what the list and the question give you.`,\n '',\n `When you are given tables, call ${AI_INSIGHT_ANSWER_TOOL_NAME} once. Each table has a handle (t1, t2, …) and numbered rows. Rules for the insights:`,\n '- Say what matters most to the question first. Leave out what the tables do not support.',\n '- Every insight cites the table and the rows its figures come from.',\n '- Every number you write appears in a row you cite, as the table shows it or rounded. Never add, subtract, average or otherwise compute a figure yourself. The only other numbers you may write are the length of a table’s window, a date in it, and how many rows you cite.',\n '- Say a figure rose or fell only when a change you quote shows it.',\n '- Name nobody, and write no email address or phone number.',\n '- Plain sentences: no markdown, no headings, no lists.',\n '- 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.',\n '- Write for someone reading on a phone: say one thing, and only what they would want to know.',\n '- Write a date the way a person says it: Monday, Oct 26, never 2026-10-26.',\n '- Leave out a percent change that rests on a handful of views.',\n '- When the tables cannot answer part of the question, say so in gap in one sentence with no numbers; otherwise gap is null.',\n '- 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.',\n '- Write in the language of the question.',\n].join('\\n')\n\n/** The system blocks both calls send: the rules and the platform's acceptable-use rules. */\nexport const AI_JOB_INSIGHT_SYSTEM: AiSystemBlock[] = [\n { text: `${AI_INSIGHT_RULES}\\n\\n${AI_ACCEPTABLE_USE_BLOCK}`, cacheBreakpoint: true },\n]\n\n/**\n * The tools BOTH calls send, in this order (AGL-4076). The provider's cached\n * prefix opens with the tools, then the system blocks, so a call that sends\n * other tools than the call before it reads none of the system block that\n * call wrote: the answer call, sent the answer tool alone after a read call\n * sent the read tool alone, read nothing on every insight. Each call names\n * the one it is for (`toolChoice`), and its user turn says so.\n */\nexport function aiInsightTools(): AiTool[] {\n return [aiInsightReadTool(), aiInsightAnswerTool()]\n}\n\nconst ZERO_USAGE: AiUsage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/** What the step's calls have spent so far, in the outcome's shape. */\nclass InsightSpend {\n usage: AiUsage = { ...ZERO_USAGE }\n estCostUsd = 0\n stopReason: string | null = null\n\n constructor(readonly model: string) {}\n\n add(result: AiResult): void {\n this.usage = {\n inputTokens: this.usage.inputTokens + result.usage.inputTokens,\n outputTokens: this.usage.outputTokens + result.usage.outputTokens,\n cacheReadTokens: this.usage.cacheReadTokens + result.usage.cacheReadTokens,\n cacheWriteTokens: this.usage.cacheWriteTokens + result.usage.cacheWriteTokens,\n }\n this.estCostUsd = Math.round((this.estCostUsd + result.estCostUsd) * 1_000_000) / 1_000_000\n this.stopReason = result.stopReason\n }\n\n outcome(): Pick<AiJobStepOutcome, 'usage' | 'estCostUsd' | 'model' | 'stopReason' | 'effort'> {\n return { usage: this.usage, estCostUsd: this.estCostUsd, model: this.model, stopReason: this.stopReason, effort: null }\n }\n}\n\n/** The read call's user turn: the question, the window asked for, the readers and, for datasets, the datasets. */\nexport function aiInsightReadPrompt(input: {\n question: string\n days: number\n readers: readonly ResolvedPluginFigureReader[]\n datasets: string | null\n}): string {\n return [\n `Question: ${input.question}`,\n `The window picked on the page: ${input.days} days. Use it unless the question names another window a reader lists.`,\n 'Readers you may read here:',\n aiInsightReaderCatalog(input.readers),\n ...(input.datasets === null ? [] : ['', 'Datasets you may read, with their fields:', input.datasets]),\n '',\n `Call ${AI_INSIGHT_READ_TOOL_NAME} now.`,\n ].join('\\n')\n}\n\n/** The answer call's user turn: the question and every table. */\nexport function aiInsightAnswerPrompt(question: string, tables: readonly AiInsightTable[]): string {\n return [\n `Question: ${question}`,\n '',\n 'Tables:',\n '',\n tables.map(aiInsightTableText).join('\\n\\n'),\n '',\n `These are all the tables there are. Call ${AI_INSIGHT_ANSWER_TOOL_NAME} now.`,\n ].join('\\n')\n}\n\n/** What a re-ask tells the model: why nothing it wrote could be kept. */\nexport function aiInsightReaskMessage(check: AiInsightCheck | null): string {\n const reasons = check?.findings.length\n ? `None of those insights could be kept: ${[...new Set(check.findings)].slice(0, 8).join('; ')}.`\n : `That answer did not come through ${AI_INSIGHT_ANSWER_TOOL_NAME}.`\n return `${reasons} Answer again with ${AI_INSIGHT_ANSWER_TOOL_NAME}: cite the rows each insight's figures are in, and write every number as a row you cite shows it.`\n}\n\n/** The reads a surface falls back to when the model named none it may read: the digest's own readers. */\nfunction defaultReads(readers: readonly ResolvedPluginFigureReader[], days: number): AiInsightReadRequest[] {\n const ids = readers.map(({ reader }) => reader.id)\n const preferred = AI_INSIGHT_DIGEST_READERS.filter((id) => ids.includes(id))\n const chosen = preferred.length ? preferred : ids\n return chosen.map((id) => ({\n reader: id,\n days: aiInsightReaderDays(readers.find(({ reader }) => reader.id === id)?.reader.windows ?? [], days),\n params: {},\n }))\n}\n\nasync function readHost(\n firestore: Firestore,\n orgId: string,\n hostId: string | null,\n): Promise<{ host: Record<string, unknown> | null; ok: boolean }> {\n if (!hostId) return { host: null, ok: true }\n const snapshot = await firestore.collection('hosts').doc(hostId).get()\n const host = snapshot.exists ? ((snapshot.data() ?? {}) as Record<string, unknown>) : null\n return { host, ok: Boolean(host) && host?.['orgId'] === orgId }\n}\n\nexport const runAiJobInsightStep: AiJobStepRunner = async (context: AiJobStepContext) => {\n const { job, firestore, signal, now } = context\n const model = context.modelFor?.('job.insight') ?? aiModelForStep('job.insight')\n const spend = new InsightSpend(model)\n const stop = (failure: string): AiJobStepOutcome => ({ outputs: [], ...spend.outcome(), failure })\n\n const surface = aiInsightSurface(job.inputs)\n if (!surface) return stop(AI_INSIGHT_NO_SURFACE_COPY)\n const hostId = job.hostId ?? null\n if (aiInsightSurfaceNeedsSite(surface) && !hostId) return stop(AI_INSIGHT_NO_SITE_COPY)\n // The door checks the caller belongs to the org; that the site does is\n // checked here, before anything about it is read.\n const site = await readHost(firestore, job.orgId, hostId)\n if (!site.ok) return stop(AI_INSIGHT_NO_SITE_COPY)\n const readers = await aiInsightReaders({\n orgId: job.orgId,\n hostId,\n org: context.org ?? null,\n host: site.host,\n surface,\n })\n if (!readers.length) return stop(AI_INSIGHT_NO_READERS_COPY)\n\n const digest = surface === 'digest'\n const days = digest ? AI_INSIGHT_DIGEST_DAYS : aiInsightDays(job.inputs?.['days'])\n const question = digest ? AI_INSIGHT_DIGEST_QUESTION : job.brief.slice(0, AI_INSIGHT_QUESTION_MAX_CHARS)\n const maxTokens = AI_JOB_INSIGHT_STEP_BUDGET.maxTokens(model)\n const allowance = AI_GENERATION_MAX_ATTEMPTS * maxTokens\n const left = () => allowance - spend.usage.outputTokens\n // What the business is and what the owner's edits showed (AGL-3661), so an\n // answer reads the numbers for THIS business. No contact details: an\n // insight names nobody. No publish state either: that is the Site status\n // table's to say, and the rules send the model there.\n const siteContext = await readAiSiteContext(firestore, { orgId: job.orgId, hostId, host: site.host ?? null })\n const system = [\n ...aiInstructionsWithSiteContext(\n AI_JOB_INSIGHT_SYSTEM,\n siteContext ? { ...siteContext, publish: null, contact: false } : null,\n ),\n ]\n // A development run's effort A/B arm (AGL-3781), else the row's.\n const effort = aiDevEffortFor('job.insight') ?? AI_ROUTING_TABLE['job.insight'].effort\n // Both tools on both calls, so the answer call reads the prefix the read call wrote (AGL-4076).\n const tools = aiInsightTools()\n const ask = (messages: AiMessage[], tool: 'read' | 'answer', ceiling: number) =>\n runAiRequest({\n model,\n system,\n messages,\n tools,\n toolChoice: tool === 'read' ? AI_INSIGHT_READ_TOOL_NAME : AI_INSIGHT_ANSWER_TOOL_NAME,\n maxTokens: Math.max(1, Math.min(ceiling, left())),\n ...(AI_ROUTING_TABLE['job.insight'].thinking ? { thinking: AI_ROUTING_TABLE['job.insight'].thinking } : {}),\n ...(effort ? { effort } : {}),\n stream: false,\n ...(signal ? { signal } : {}),\n })\n\n // 1. The reads.\n // A digest reads last Monday to Sunday, whatever minute the beat runs it.\n const readNow = digest ? aiInsightDigestPeriod(job.inputs, now).now : now\n const base = { orgId: job.orgId, hostId, uid: digest ? null : job.createdBy, now: readNow }\n let requests: AiInsightReadRequest[]\n if (digest) {\n requests = defaultReads(readers, days)\n } else {\n const datasets =\n surface === 'datasets'\n ? aiInsightDatasetCatalog(await aiDatasetCatalog(firestore, { orgId: job.orgId, hostId, uid: job.createdBy }))\n : null\n const result = await ask(\n [{ role: 'user', content: aiInsightReadPrompt({ question, days, readers, datasets }) }],\n 'read',\n AI_INSIGHT_READ_MAX_TOKENS,\n )\n spend.add(result)\n if (result.kind === 'refusal') return { outputs: [], ...spend.outcome(), refused: true }\n requests = parseAiInsightReads(result.toolUse.find((use) => use.name === AI_INSIGHT_READ_TOOL_NAME)?.input)\n }\n const maxTables = digest ? AI_INSIGHT_DIGEST_READERS.length : undefined\n let read = await readAiInsightTables(readers, requests, base, maxTables)\n if (!read.tables.length && !digest) read = await readAiInsightTables(readers, defaultReads(readers, days), base)\n if (read.refusals.length) console.warn('ai insight reads refused', { jobId: job.$id, refusals: read.refusals })\n if (!read.tables.length) return stop(AI_INSIGHT_NO_TABLES_COPY)\n // A site's question is told whether the site is live, so traffic is never\n // read as launch status. Appended, so the readers' refs stay as they were.\n const tables =\n !digest && site.host\n ? [...read.tables, aiSiteStatusTable(aiHostPublishContext(site.host), `t${read.tables.length + 1}`)]\n : read.tables\n\n // 2. The answer, and at most one re-ask.\n let messages: AiMessage[] = [{ role: 'user', content: aiInsightAnswerPrompt(question, tables) }]\n let checked: AiInsightCheck | null = null\n for (let attempt = 0; attempt < AI_GENERATION_MAX_ATTEMPTS && left() > 0; attempt += 1) {\n const result = await ask(messages, 'answer', maxTokens)\n spend.add(result)\n if (result.kind === 'refusal') return { outputs: [], ...spend.outcome(), refused: true }\n const answer = parseAiInsightAnswer(result.toolUse.find((use) => use.name === AI_INSIGHT_ANSWER_TOOL_NAME)?.input)\n const check = answer ? checkAiInsightAnswer(answer, tables) : null\n if (check) checked = check\n if (check && (check.kept.length || !answer?.insights.length)) break\n messages = [\n ...messages,\n { role: 'assistant', content: `Answered with ${AI_INSIGHT_ANSWER_TOOL_NAME}.` },\n { role: 'user', content: aiInsightReaskMessage(check) },\n ]\n }\n if (!checked) return stop(AI_INSIGHT_UNREADABLE_COPY)\n\n const record: AiInsightRecord = {\n jobId: job.$id,\n orgId: job.orgId,\n hostId,\n surface,\n createdBy: job.createdBy,\n question: digest ? str(job.brief) || 'Weekly insights' : question,\n days,\n insights: checked.kept,\n gap: checked.gap,\n tables,\n left: checked.left.length,\n week: digest ? str(job.inputs?.['week']) || null : null,\n createdAtMs: now.getTime(),\n }\n if (checked.left.length) {\n console.info('ai insight left out untraced insights', { jobId: job.$id, findings: checked.findings })\n }\n // Keyed by the job, so a step run again replaces its own answer.\n await firestore\n .collection('orgs')\n .doc(job.orgId)\n .collection(AI_INSIGHTS_COLLECTION)\n .doc(job.$id)\n .set({ ...(JSON.parse(JSON.stringify(record)) as AiInsightRecord), expiresAt: job.expiresAt ?? assistExchangeExpiry(now) })\n return {\n outputs: [aiInsightOutput(job, record, str(site.host?.['subdomain']) || null)],\n ...spend.outcome(),\n }\n}\n\n/**\n * Whether a question may be asked here: a surface a person asks from, a site\n * of the job's own org where the surface needs one, and at least one reader\n * the workspace may read. A digest is made by the weekly sweep and never at a\n * door.\n */\nexport async function aiInsightAdmissionRefusal(\n context: AiJobAdmissionContext,\n): Promise<AiJobAdmissionRefusal | null> {\n const surface: AiInsightSurface | null = aiInsightSurface(context.inputs)\n if (!surface || !AI_INSIGHT_ASK_SURFACES.includes(surface)) {\n return { status: 400, error: 'Ask about your numbers from a site’s Analytics, Data or CRM Reports page.' }\n }\n if (aiInsightSurfaceNeedsSite(surface) && !context.hostId) {\n return { status: 400, error: AI_INSIGHT_NO_SITE_COPY }\n }\n const site = await readHost(context.firestore, context.orgId, context.hostId)\n if (!site.ok) return { status: 404, error: 'Unknown site' }\n const readers = await aiInsightReaders({\n orgId: context.orgId,\n hostId: context.hostId,\n org: context.org,\n host: site.host,\n surface,\n })\n return readers.length ? null : { status: 403, error: AI_INSIGHT_NO_READERS_COPY }\n}\n\n/**\n * The insight kind's registrations, called by the console surface\n * (`registerAiJobKinds` in `server.ts`), never made by importing this module\n * (AGL-3025).\n */\nexport function registerAiInsightJob(): void {\n registerAiJobStep('insight', runAiJobInsightStep, { minimumMs: AI_JOB_INSIGHT_STEP_MINIMUM_MS })\n registerAiJobAdmission('insight', aiInsightAdmissionRefusal)\n}\n"],"names":["AI_INSIGHT_ASK_SURFACES","AI_INSIGHT_DIGEST_DAYS","AI_INSIGHT_DIGEST_READERS","AI_INSIGHT_QUESTION_MAX_CHARS","AI_INSIGHTS_COLLECTION","aiInsightDays","aiInsightDigestPeriod","aiInsightOutput","aiInsightSurface","aiInsightSurfaceNeedsSite","aiHostPublishContext","aiSiteStatusTable","aiInstructionsWithSiteContext","readAiSiteContext","AI_ROUTING_TABLE","aiModelForStep","aiDevEffortFor","AI_ACCEPTABLE_USE_BLOCK","runAiRequest","AI_GENERATION_MAX_ATTEMPTS","checkAiInsightAnswer","AI_INSIGHT_ANSWER_TOOL_NAME","AI_INSIGHT_READ_TOOL_NAME","aiInsightAnswerTool","aiInsightReadTool","parseAiInsightAnswer","parseAiInsightReads","aiDatasetCatalog","aiInsightDatasetCatalog","aiInsightReaderCatalog","aiInsightReaderDays","aiInsightReaders","aiInsightTableText","readAiInsightTables","assistExchangeExpiry","registerAiJobAdmission","AI_INSIGHT_READ_MAX_TOKENS","AI_JOB_INSIGHT_STEP_BUDGET","AI_JOB_INSIGHT_STEP_MINIMUM_MS","registerAiJobStep","AI_INSIGHT_NO_SURFACE_COPY","AI_INSIGHT_NO_SITE_COPY","AI_INSIGHT_NO_READERS_COPY","AI_INSIGHT_NO_TABLES_COPY","AI_INSIGHT_UNREADABLE_COPY","AI_INSIGHT_DIGEST_QUESTION","AI_INSIGHT_RULES","join","AI_JOB_INSIGHT_SYSTEM","text","cacheBreakpoint","aiInsightTools","ZERO_USAGE","inputTokens","outputTokens","cacheReadTokens","cacheWriteTokens","str","value","trim","InsightSpend","add","result","usage","estCostUsd","Math","round","stopReason","outcome","model","effort","aiInsightReadPrompt","input","question","days","readers","datasets","aiInsightAnswerPrompt","tables","map","aiInsightReaskMessage","check","reasons","findings","length","Set","slice","defaultReads","ids","reader","id","preferred","filter","includes","chosen","find","windows","params","readHost","firestore","orgId","hostId","snapshot","host","ok","collection","doc","get","exists","data","Boolean","runAiJobInsightStep","context","job","site","signal","now","modelFor","spend","stop","failure","outputs","surface","inputs","org","digest","brief","maxTokens","allowance","left","siteContext","system","publish","contact","tools","ask","messages","tool","ceiling","toolChoice","max","min","thinking","stream","readNow","base","uid","createdBy","requests","role","content","kind","refused","toolUse","use","name","maxTables","undefined","read","refusals","console","warn","jobId","$id","checked","attempt","answer","kept","insights","record","gap","week","createdAtMs","getTime","info","set","JSON","parse","stringify","expiresAt","aiInsightAdmissionRefusal","status","error","registerAiInsightJob","minimumMs"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SACEA,uBAAuB,EACvBC,sBAAsB,EACtBC,yBAAyB,EACzBC,6BAA6B,EAC7BC,sBAAsB,EACtBC,aAAa,EACbC,qBAAqB,EACrBC,eAAe,EACfC,gBAAgB,EAChBC,yBAAyB,QAIpB,yBAAqB;AAC5B,SAASC,oBAAoB,EAAEC,iBAAiB,QAAQ,sCAAkC;AAC1F,SAASC,6BAA6B,QAAQ,8BAA0B;AACxE,SAASC,iBAAiB,QAAQ,6BAAyB;AAC3D,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,0BAAsB;AACvE,SAASC,cAAc,QAAQ,2BAAuB;AACtD,SACEC,uBAAuB,EACvBC,YAAY,QAKP,2BAAuB;AAE9B,SAASC,0BAA0B,QAAQ,qCAAiC;AAC5E,SAASC,oBAAoB,QAA6B,iCAA6B;AACvF,SACEC,2BAA2B,EAC3BC,yBAAyB,EACzBC,mBAAmB,EACnBC,iBAAiB,EACjBC,oBAAoB,EACpBC,mBAAmB,QAEd,8BAA0B;AACjC,SAASC,gBAAgB,QAAQ,oCAAgC;AACjE,SACEC,uBAAuB,EACvBC,sBAAsB,EACtBC,mBAAmB,EACnBC,gBAAgB,EAChBC,kBAAkB,EAClBC,mBAAmB,QACd,oCAAgC;AACvC,SAASC,oBAAoB,QAAQ,2BAAuB;AAC5D,SAASC,sBAAsB,QAAgE,wBAAoB;AACnH,SAASC,0B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MAAMhB,SAASc,QAAQb,SAAS,EAAEa,QAAQZ,KAAK,EAAEY,QAAQX,MAAM;IAC5E,IAAI,CAACa,KAAKV,EAAE,EAAE,OAAO;QAAE6E,QAAQ;QAAKC,OAAO;IAAe;IAC1D,MAAM3G,UAAU,MAAM5C,iBAAiB;QACrCqE,OAAOY,QAAQZ,KAAK;QACpBC,QAAQW,QAAQX,MAAM;QACtBuB,KAAKZ,QAAQY,GAAG;QAChBrB,MAAMW,KAAKX,IAAI;QACfmB;IACF;IACA,OAAO/C,QAAQS,MAAM,GAAG,OAAO;QAAEiG,QAAQ;QAAKC,OAAO5I;IAA2B;AAClF;AAEA;;;;CAIC,GACD,OAAO,SAAS6I;IACdhJ,kBAAkB,WAAWwE,qBAAqB;QAAEyE,WAAWlJ;IAA+B;IAC9FH,uBAAuB,WAAWiJ;AACpC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-insight-step.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 type { ResolvedPluginFigureReader } from '@aglyn/aglyn/plugin-manager/plugin-figures'\nimport {\n AI_INSIGHT_ASK_SURFACES,\n AI_INSIGHT_DIGEST_DAYS,\n AI_INSIGHT_DIGEST_READERS,\n AI_INSIGHT_QUESTION_MAX_CHARS,\n AI_INSIGHTS_COLLECTION,\n aiInsightDays,\n aiInsightDigestPeriod,\n aiInsightOutput,\n aiInsightSurface,\n aiInsightSurfaceNeedsSite,\n type AiInsightRecord,\n type AiInsightSurface,\n type AiInsightTable,\n} from '../model/ai-insight'\nimport { aiHostPublishContext, aiSiteStatusTable } from '../model/ai-host-publish-context'\nimport { aiInstructionsWithSiteContext } from '../model/ai-site-context'\nimport { readAiSiteContext } from '../runtime/site-context'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport { aiDevEffortFor } from '../runtime/ai-dev-env'\nimport {\n AI_ACCEPTABLE_USE_BLOCK,\n runAiRequest,\n type AiMessage,\n type AiResult,\n type AiSystemBlock,\n type AiUsage,\n} from '../runtime/ai-runtime'\nimport type { AiTool } from '../providers/contract'\nimport { AI_GENERATION_MAX_ATTEMPTS } from '../runtime/ai-generation-bounds'\nimport { checkAiInsightAnswer, type AiInsightCheck } from '../runtime/ai-insight-check'\nimport {\n AI_INSIGHT_ANSWER_TOOL_NAME,\n AI_INSIGHT_READ_TOOL_NAME,\n aiInsightAnswerTool,\n aiInsightReadTool,\n parseAiInsightAnswer,\n parseAiInsightReads,\n type AiInsightReadRequest,\n} from '../tools/ai-insight-tool'\nimport { aiDatasetCatalog } from '../insights/ai-dataset-catalog'\nimport {\n aiInsightDatasetCatalog,\n aiInsightReaderCatalog,\n aiInsightReaderDays,\n aiInsightReaders,\n aiInsightTableText,\n readAiInsightTables,\n} from '../insights/ai-insight-readers'\nimport { assistExchangeExpiry } from '../usage/assist-usage'\nimport { registerAiJobAdmission, type AiJobAdmissionContext, type AiJobAdmissionRefusal } from './ai-job-admission'\nimport {\n AI_INSIGHT_DIGEST_THINKING,\n AI_INSIGHT_READ_MAX_TOKENS,\n AI_JOB_INSIGHT_STEP_BUDGET,\n AI_JOB_INSIGHT_STEP_MINIMUM_MS,\n} from './ai-job-insight-budget'\nimport type { AiJobStepContext, AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The `insight` step (AGL-2915): a question about a site's figures, answered\n * from tables code read, with every insight traced to the rows it cites.\n *\n * ## Two exchanges, and the model never writes a query\n *\n * 1. **The reads.** The model is shown the question and the readers this job\n * may read — each an id, what it answers, its windows and parameters — and\n * answers `read_figures` with a choice among them. It names nothing else: no\n * collection, no field path, no filter. A choice that names no reader this\n * job may read is dropped, and a job left with none reads the surface's\n * defaults. A weekly digest makes no read call: code reads the digest's\n * readers.\n * 2. **The answer.** Code reads the tables through the owners' readers, and the\n * model is shown them and answers `submit_insights`. A digest thinks here\n * (`AI_INSIGHT_DIGEST_THINKING`), and writes an overview of the week and,\n * for each insight, what most likely drove it and one next step. The trace\n * (`runtime/ai-insight-check.ts`) keeps each insight whose every number is\n * in a row it cites and leaves out the rest. An answer that is not a call,\n * or whose every insight was left out, is asked for once more with the\n * reasons; what the second answer keeps is the answer.\n *\n * Both calls share one allowance of output, twice the routing ceiling, which\n * is what the step's least time is planned against.\n *\n * ## What reaches the model\n *\n * The question, the names and descriptions of the readers, the tables, the\n * site's publish state (published or not, its address, its pages' paths), and\n * for a datasets question the names of the datasets the member may see with\n * their fields' names and types. A table holds counts, sums and rates labeled\n * by a page path, a referring site, a form's, a service's, a product's or a\n * campaign's name, or the values of a dataset field with at most sixty\n * different values that at least three records share. No\n * record, visitor, contact, order, booking, submission or recipient is read\n * into a prompt, and every text cell is masked of email addresses and phone\n * numbers on its way into a table.\n *\n * ## What it writes\n *\n * The answer, at `orgs/{orgId}/aiInsights/{jobId}` under the job's own\n * expiry, and an output that names it and says how many insights it holds.\n * Nothing else: no draft, no setting, no message.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport const AI_INSIGHT_NO_SURFACE_COPY = 'This question does not say which page it was asked from.'\nexport const AI_INSIGHT_NO_SITE_COPY = 'Open the site whose numbers you are asking about.'\nexport const AI_INSIGHT_NO_READERS_COPY =\n 'There are no figures to answer from here yet: the features this page reports on are not on for this workspace.'\nexport const AI_INSIGHT_NO_TABLES_COPY = 'The figures could not be read. Try again in a moment.'\nexport const AI_INSIGHT_UNREADABLE_COPY = 'The AI did not answer with insights. Try asking in different words.'\n\n/** The digest's question: what the week meant, why and what to do, in the owner's words. */\nexport const AI_INSIGHT_DIGEST_QUESTION =\n 'What happened on this site last week, Monday to Sunday, why, and what should the owner do next? The owner already gets an email listing the week’s figures, so never recite them. Write the overview, then the moves worth talking about, each with what most likely drove it: compare the days and pages that moved with what changed on the site, where visits came from and any campaign. Only what the tables support.'\n\n/** The rules both calls are sent: static, byte-identical for every workspace. */\nexport const AI_INSIGHT_RULES = [\n '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.',\n '',\n `When you are given a question and a list of readers, call ${AI_INSIGHT_READ_TOOL_NAME} once with the readers whose tables answer it, most useful first, and the window each should cover. Choose only readers from the list, with their parameters' values taken from what the list and the question give you.`,\n '',\n `When you are given tables, call ${AI_INSIGHT_ANSWER_TOOL_NAME} once. Each table has a handle (t1, t2, …) and numbered rows. Rules for the insights:`,\n '- Say what matters most to the question first. Leave out what the tables do not support.',\n '- Read the figures like the owner’s analyst: say what a move means and connect the tables, never just repeat a row.',\n '- Every insight cites the table and the rows its figures come from.',\n '- Every number you write appears in a row you cite, as the table shows it or rounded. Never add, subtract, average or otherwise compute a figure yourself. The only other numbers you may write are the length of a table’s window, a date in it, and how many rows you cite.',\n '- Say a figure rose or fell only when a change you quote shows it.',\n '- Name nobody, and write no email address or phone number.',\n '- Plain sentences: no markdown, no headings, no lists.',\n '- 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.',\n '- Write for someone reading on a phone: say one thing, and only what they would want to know.',\n '- Write a date the way a person says it: Monday, Oct 26, never 2026-10-26.',\n '- Leave out a percent change that rests on a handful of views.',\n '- why says what most likely drove a move, in one short sentence, and must cite the row it rests on: a dated change, a source or a campaign. Write the reason alone: a label already calls it likely. Two things happening together does not prove one caused the other. When nothing in those tables explains a move, set why to null and say so in text.',\n '- A source or campaign whose change shows it held steady cannot explain a move: steady traffic does not make a page rise or fall.',\n '- next is one concrete step the owner can take in the console or on their site, for this insight. Name only something that exists, and never promise a result. null when none fits.',\n '- overview is for a weekly digest: what the week meant in two or three sentences of your own, not a list of figures. On a question, overview is null, and why and next are null unless the question asks why or what to do.',\n '- When the tables cannot answer part of the question, say so in gap in one sentence with no numbers; otherwise gap is null.',\n '- 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.',\n '- Write in the language of the question.',\n].join('\\n')\n\n/** The system blocks both calls send: the rules and the platform's acceptable-use rules. */\nexport const AI_JOB_INSIGHT_SYSTEM: AiSystemBlock[] = [\n { text: `${AI_INSIGHT_RULES}\\n\\n${AI_ACCEPTABLE_USE_BLOCK}`, cacheBreakpoint: true },\n]\n\n/**\n * The tools BOTH calls send, in this order (AGL-4076). The provider's cached\n * prefix opens with the tools, then the system blocks, so a call that sends\n * other tools than the call before it reads none of the system block that\n * call wrote: the answer call, sent the answer tool alone after a read call\n * sent the read tool alone, read nothing on every insight. Each call names\n * the one it is for (`toolChoice`), and its user turn says so.\n */\nexport function aiInsightTools(): AiTool[] {\n return [aiInsightReadTool(), aiInsightAnswerTool()]\n}\n\nconst ZERO_USAGE: AiUsage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/** What the step's calls have spent so far, in the outcome's shape. */\nclass InsightSpend {\n usage: AiUsage = { ...ZERO_USAGE }\n estCostUsd = 0\n stopReason: string | null = null\n\n constructor(readonly model: string) {}\n\n add(result: AiResult): void {\n this.usage = {\n inputTokens: this.usage.inputTokens + result.usage.inputTokens,\n outputTokens: this.usage.outputTokens + result.usage.outputTokens,\n cacheReadTokens: this.usage.cacheReadTokens + result.usage.cacheReadTokens,\n cacheWriteTokens: this.usage.cacheWriteTokens + result.usage.cacheWriteTokens,\n }\n this.estCostUsd = Math.round((this.estCostUsd + result.estCostUsd) * 1_000_000) / 1_000_000\n this.stopReason = result.stopReason\n }\n\n outcome(): Pick<AiJobStepOutcome, 'usage' | 'estCostUsd' | 'model' | 'stopReason' | 'effort'> {\n return { usage: this.usage, estCostUsd: this.estCostUsd, model: this.model, stopReason: this.stopReason, effort: null }\n }\n}\n\n/** The read call's user turn: the question, the window asked for, the readers and, for datasets, the datasets. */\nexport function aiInsightReadPrompt(input: {\n question: string\n days: number\n readers: readonly ResolvedPluginFigureReader[]\n datasets: string | null\n}): string {\n return [\n `Question: ${input.question}`,\n `The window picked on the page: ${input.days} days. Use it unless the question names another window a reader lists.`,\n 'Readers you may read here:',\n aiInsightReaderCatalog(input.readers),\n ...(input.datasets === null ? [] : ['', 'Datasets you may read, with their fields:', input.datasets]),\n '',\n `Call ${AI_INSIGHT_READ_TOOL_NAME} now.`,\n ].join('\\n')\n}\n\n/** The answer call's user turn: the question and every table. */\nexport function aiInsightAnswerPrompt(question: string, tables: readonly AiInsightTable[]): string {\n return [\n `Question: ${question}`,\n '',\n 'Tables:',\n '',\n tables.map(aiInsightTableText).join('\\n\\n'),\n '',\n `These are all the tables there are. Call ${AI_INSIGHT_ANSWER_TOOL_NAME} now.`,\n ].join('\\n')\n}\n\n/** What a re-ask tells the model: why nothing it wrote could be kept. */\nexport function aiInsightReaskMessage(check: AiInsightCheck | null): string {\n const reasons = check?.findings.length\n ? `None of those insights could be kept: ${[...new Set(check.findings)].slice(0, 8).join('; ')}.`\n : `That answer did not come through ${AI_INSIGHT_ANSWER_TOOL_NAME}.`\n return `${reasons} Answer again with ${AI_INSIGHT_ANSWER_TOOL_NAME}: cite the rows each insight's figures are in, and write every number as a row you cite shows it.`\n}\n\n/** The reads a surface falls back to when the model named none it may read: the digest's own readers. */\nfunction defaultReads(readers: readonly ResolvedPluginFigureReader[], days: number): AiInsightReadRequest[] {\n const ids = readers.map(({ reader }) => reader.id)\n const preferred = AI_INSIGHT_DIGEST_READERS.filter((id) => ids.includes(id))\n const chosen = preferred.length ? preferred : ids\n return chosen.map((id) => ({\n reader: id,\n days: aiInsightReaderDays(readers.find(({ reader }) => reader.id === id)?.reader.windows ?? [], days),\n params: {},\n }))\n}\n\nasync function readHost(\n firestore: Firestore,\n orgId: string,\n hostId: string | null,\n): Promise<{ host: Record<string, unknown> | null; ok: boolean }> {\n if (!hostId) return { host: null, ok: true }\n const snapshot = await firestore.collection('hosts').doc(hostId).get()\n const host = snapshot.exists ? ((snapshot.data() ?? {}) as Record<string, unknown>) : null\n return { host, ok: Boolean(host) && host?.['orgId'] === orgId }\n}\n\nexport const runAiJobInsightStep: AiJobStepRunner = async (context: AiJobStepContext) => {\n const { job, firestore, signal, now } = context\n const model = context.modelFor?.('job.insight') ?? aiModelForStep('job.insight')\n const spend = new InsightSpend(model)\n const stop = (failure: string): AiJobStepOutcome => ({ outputs: [], ...spend.outcome(), failure })\n\n const surface = aiInsightSurface(job.inputs)\n if (!surface) return stop(AI_INSIGHT_NO_SURFACE_COPY)\n const hostId = job.hostId ?? null\n if (aiInsightSurfaceNeedsSite(surface) && !hostId) return stop(AI_INSIGHT_NO_SITE_COPY)\n // The door checks the caller belongs to the org; that the site does is\n // checked here, before anything about it is read.\n const site = await readHost(firestore, job.orgId, hostId)\n if (!site.ok) return stop(AI_INSIGHT_NO_SITE_COPY)\n const readers = await aiInsightReaders({\n orgId: job.orgId,\n hostId,\n org: context.org ?? null,\n host: site.host,\n surface,\n })\n if (!readers.length) return stop(AI_INSIGHT_NO_READERS_COPY)\n\n const digest = surface === 'digest'\n const days = digest ? AI_INSIGHT_DIGEST_DAYS : aiInsightDays(job.inputs?.['days'])\n const question = digest ? AI_INSIGHT_DIGEST_QUESTION : job.brief.slice(0, AI_INSIGHT_QUESTION_MAX_CHARS)\n const route = AI_ROUTING_TABLE['job.insight']\n // The budget is sized for a digest's ceiling; a question keeps the row's.\n const fits = AI_JOB_INSIGHT_STEP_BUDGET.maxTokens(model)\n const maxTokens = digest ? fits : Math.min(fits, route.maxTokens)\n const allowance = AI_GENERATION_MAX_ATTEMPTS * maxTokens\n const left = () => allowance - spend.usage.outputTokens\n // What the business is and what the owner's edits showed (AGL-3661), so an\n // answer reads the numbers for THIS business. No contact details: an\n // insight names nobody. No publish state either: that is the Site status\n // table's to say, and the rules send the model there.\n const siteContext = await readAiSiteContext(firestore, { orgId: job.orgId, hostId, host: site.host ?? null })\n const system = [\n ...aiInstructionsWithSiteContext(\n AI_JOB_INSIGHT_SYSTEM,\n siteContext ? { ...siteContext, publish: null, contact: false } : null,\n ),\n ]\n // A development run's effort A/B arm (AGL-3781), else the digest's or the row's.\n const effort = aiDevEffortFor('job.insight') ?? (digest ? AI_INSIGHT_DIGEST_THINKING.effort : route.effort)\n const thinking = digest ? AI_INSIGHT_DIGEST_THINKING.thinking : route.thinking\n // Both tools on both calls, so the answer call reads the prefix the read call wrote (AGL-4076).\n const tools = aiInsightTools()\n const ask = (messages: AiMessage[], tool: 'read' | 'answer', ceiling: number) =>\n runAiRequest({\n model,\n system,\n messages,\n tools,\n toolChoice: tool === 'read' ? AI_INSIGHT_READ_TOOL_NAME : AI_INSIGHT_ANSWER_TOOL_NAME,\n maxTokens: Math.max(1, Math.min(ceiling, left())),\n ...(thinking ? { thinking } : {}),\n ...(effort ? { effort } : {}),\n stream: false,\n ...(signal ? { signal } : {}),\n })\n\n // 1. The reads.\n // A digest reads last Monday to Sunday, whatever minute the beat runs it.\n const readNow = digest ? aiInsightDigestPeriod(job.inputs, now).now : now\n const base = { orgId: job.orgId, hostId, uid: digest ? null : job.createdBy, now: readNow }\n let requests: AiInsightReadRequest[]\n if (digest) {\n requests = defaultReads(readers, days)\n } else {\n const datasets =\n surface === 'datasets'\n ? aiInsightDatasetCatalog(await aiDatasetCatalog(firestore, { orgId: job.orgId, hostId, uid: job.createdBy }))\n : null\n const result = await ask(\n [{ role: 'user', content: aiInsightReadPrompt({ question, days, readers, datasets }) }],\n 'read',\n AI_INSIGHT_READ_MAX_TOKENS,\n )\n spend.add(result)\n if (result.kind === 'refusal') return { outputs: [], ...spend.outcome(), refused: true }\n requests = parseAiInsightReads(result.toolUse.find((use) => use.name === AI_INSIGHT_READ_TOOL_NAME)?.input)\n }\n const maxTables = digest ? AI_INSIGHT_DIGEST_READERS.length : undefined\n let read = await readAiInsightTables(readers, requests, base, maxTables)\n if (!read.tables.length && !digest) read = await readAiInsightTables(readers, defaultReads(readers, days), base)\n if (read.refusals.length) console.warn('ai insight reads refused', { jobId: job.$id, refusals: read.refusals })\n if (!read.tables.length) return stop(AI_INSIGHT_NO_TABLES_COPY)\n // A site's question is told whether the site is live, so traffic is never\n // read as launch status. Appended, so the readers' refs stay as they were.\n const tables =\n !digest && site.host\n ? [...read.tables, aiSiteStatusTable(aiHostPublishContext(site.host), `t${read.tables.length + 1}`)]\n : read.tables\n\n // 2. The answer, and at most one re-ask.\n let messages: AiMessage[] = [{ role: 'user', content: aiInsightAnswerPrompt(question, tables) }]\n let checked: AiInsightCheck | null = null\n for (let attempt = 0; attempt < AI_GENERATION_MAX_ATTEMPTS && left() > 0; attempt += 1) {\n const result = await ask(messages, 'answer', maxTokens)\n spend.add(result)\n if (result.kind === 'refusal') return { outputs: [], ...spend.outcome(), refused: true }\n const answer = parseAiInsightAnswer(result.toolUse.find((use) => use.name === AI_INSIGHT_ANSWER_TOOL_NAME)?.input)\n const check = answer ? checkAiInsightAnswer(answer, tables) : null\n if (check) checked = check\n if (check && (check.kept.length || !answer?.insights.length)) break\n messages = [\n ...messages,\n { role: 'assistant', content: `Answered with ${AI_INSIGHT_ANSWER_TOOL_NAME}.` },\n { role: 'user', content: aiInsightReaskMessage(check) },\n ]\n }\n if (!checked) return stop(AI_INSIGHT_UNREADABLE_COPY)\n\n const record: AiInsightRecord = {\n jobId: job.$id,\n orgId: job.orgId,\n hostId,\n surface,\n createdBy: job.createdBy,\n question: digest ? str(job.brief) || 'Weekly insights' : question,\n days,\n overview: digest ? checked.overview : null,\n insights: checked.kept,\n gap: checked.gap,\n tables,\n left: checked.left.length,\n week: digest ? str(job.inputs?.['week']) || null : null,\n createdAtMs: now.getTime(),\n }\n if (checked.left.length) {\n console.info('ai insight left out untraced insights', { jobId: job.$id, findings: checked.findings })\n }\n // Keyed by the job, so a step run again replaces its own answer.\n await firestore\n .collection('orgs')\n .doc(job.orgId)\n .collection(AI_INSIGHTS_COLLECTION)\n .doc(job.$id)\n .set({ ...(JSON.parse(JSON.stringify(record)) as AiInsightRecord), expiresAt: job.expiresAt ?? assistExchangeExpiry(now) })\n return {\n outputs: [aiInsightOutput(job, record, str(site.host?.['subdomain']) || null)],\n ...spend.outcome(),\n }\n}\n\n/**\n * Whether a question may be asked here: a surface a person asks from, a site\n * of the job's own org where the surface needs one, and at least one reader\n * the workspace may read. A digest is made by the weekly sweep and never at a\n * door.\n */\nexport async function aiInsightAdmissionRefusal(\n context: AiJobAdmissionContext,\n): Promise<AiJobAdmissionRefusal | null> {\n const surface: AiInsightSurface | null = aiInsightSurface(context.inputs)\n if (!surface || !AI_INSIGHT_ASK_SURFACES.includes(surface)) {\n return { status: 400, error: 'Ask about your numbers from a site’s Analytics, Data or CRM Reports page.' }\n }\n if (aiInsightSurfaceNeedsSite(surface) && !context.hostId) {\n return { status: 400, error: AI_INSIGHT_NO_SITE_COPY }\n }\n const site = await readHost(context.firestore, context.orgId, context.hostId)\n if (!site.ok) return { status: 404, error: 'Unknown site' }\n const readers = await aiInsightReaders({\n orgId: context.orgId,\n hostId: context.hostId,\n org: context.org,\n host: site.host,\n surface,\n })\n return readers.length ? null : { status: 403, error: AI_INSIGHT_NO_READERS_COPY }\n}\n\n/**\n * The insight kind's registrations, called by the console surface\n * (`registerAiJobKinds` in `server.ts`), never made by importing this module\n * (AGL-3025).\n */\nexport function registerAiInsightJob(): void {\n registerAiJobStep('insight', runAiJobInsightStep, { minimumMs: AI_JOB_INSIGHT_STEP_MINIMUM_MS })\n registerAiJobAdmission('insight', aiInsightAdmissionRefusal)\n}\n"],"names":["AI_INSIGHT_ASK_SURFACES","AI_INSIGHT_DIGEST_DAYS","AI_INSIGHT_DIGEST_READERS","AI_INSIGHT_QUESTION_MAX_CHARS","AI_INSIGHTS_COLLECTION","aiInsightDays","aiInsightDigestPeriod","aiInsightOutput","aiInsightSurface","aiInsightSurfaceNeedsSite","aiHostPublishContext","aiSiteStatusTable","aiInstructionsWithSiteContext","readAiSiteContext","AI_ROUTING_TABLE","aiModelForStep","aiDevEffortFor","AI_ACCEPTABLE_USE_BLOCK","runAiRequest","AI_GENERATION_MAX_ATTEMPTS","checkAiInsightAnswer","AI_INSIGHT_ANSWER_TOOL_NAME","AI_INSIGHT_READ_TOOL_NAME","aiInsightAnswerTool","aiInsightReadTool","parseAiInsightAnswer","parseAiInsightReads","aiDatasetCatalog","aiInsightDatasetCatalog","aiInsightReaderCatalog","aiInsightReaderDays","aiInsightReaders","aiInsightTableText","readAiInsightTables","assistExchangeExpiry","registerAiJobAdmission","AI_INSIGHT_DIGEST_THINKING","AI_INSIGHT_READ_MAX_TOKENS","AI_JOB_INSIGHT_STEP_BUDGET","AI_JOB_INSIGHT_STEP_MINIMUM_MS","registerAiJobStep","AI_INSIGHT_NO_SURFACE_COPY","AI_INSIGHT_NO_SITE_COPY","AI_INSIGHT_NO_READERS_COPY","AI_INSIGHT_NO_TABLES_COPY","AI_INSIGHT_UNREADABLE_COPY","AI_INSIGHT_DIGEST_QUESTION","AI_INSIGHT_RULES","join","AI_JOB_INSIGHT_SYSTEM","text","cacheBreakpoint","aiInsightTools","ZERO_USAGE","inputTokens","outputTokens","cacheReadTokens","cacheWriteTokens","str","value","trim","InsightSpend","add","result","usage","estCostUsd","Math","round","stopReason","outcome","model","effort","aiInsightReadPrompt","input","question","days","readers","datasets","aiInsightAnswerPrompt","tables","map","aiInsightReaskMessage","check","reasons","findings","length","Set","slice","defaultReads","ids","reader","id","preferred","filter","includes","chosen","find","windows","params","readHost","firestore","orgId","hostId","snapshot","host","ok","collection","doc","get","exists","data","Boolean","runAiJobInsightStep","context","job","site","signal","now","modelFor","spend","stop","failure","outputs","surface","inputs","org","digest","brief","route","fits","maxTokens","min","allowance","left","siteContext","system","publish","contact","thinking","tools","ask","messages","tool","ceiling","toolChoice","max","stream","readNow","base","uid","createdBy","requests","role","content","kind","refused","toolUse","use","name","maxTables","undefined","read","refusals","console","warn","jobId","$id","checked","attempt","answer","kept","insights","record","overview","gap","week","createdAtMs","getTime","info","set","JSON","parse","stringify","expiresAt","aiInsightAdmissionRefusal","status","error","registerAiInsightJob","minimumMs"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SACEA,uBAAuB,EACvBC,sBAAsB,EACtBC,yBAAyB,EACzBC,6BAA6B,EAC7BC,sBAAsB,EACtBC,aAAa,EACbC,qBAAqB,EACrBC,eAAe,EACfC,gBAAgB,EAChBC,yBAAyB,QAIpB,yBAAqB;AAC5B,SAASC,oBAAoB,EAAEC,iBAAiB,QAAQ,sCAAkC;AAC1F,SAASC,6BAA6B,QAAQ,8BAA0B;AACxE,SAASC,iBAAiB,QAAQ,6BAAyB;AAC3D,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,0BAAsB;AACvE,SAASC,cAAc,QAAQ,2BAAuB;AACtD,SACEC,uBAAuB,EACvBC,YAAY,QAKP,2BAAuB;AAE9B,SAASC,0BAA0B,QAAQ,qCAAiC;AAC5E,SAASC,oBAAoB,QAA6B,iCAA6B;AACvF,SACEC,2BAA2B,EAC3BC,yBAAyB,EACzBC,mBAAmB,EACnBC,iBAAiB,EACjBC,oBAAoB,EACpBC,mBAAmB,QAEd,8BAA0B;AACjC,SAASC,gBAAgB,QAAQ,oCAAgC;AACjE,SACEC,uBAAuB,EACvBC,sBAAsB,EACtBC,mBAAmB,EACnBC,gBAAgB,EAChBC,kBAAkB,EAClBC,mBAAmB,QACd,oCAAgC;AACvC,SAASC,oBAAoB,QAAQ,2BAAuB;AAC5D,SAASC,sBAAsB,QAAgE,wBAAoB;AACnH,SACEC,0BAA0B,EAC1BC,0BAA0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B8F,QAAQ,CAAC6B,UAAU;QAC1D,OAAO;YAAE8D,QAAQ;YAAKC,OAAO;QAA4E;IAC3G;IACA,IAAIjL,0BAA0BkH,YAAY,CAACV,QAAQX,MAAM,EAAE;QACzD,OAAO;YAAEmF,QAAQ;YAAKC,OAAOhJ;QAAwB;IACvD;IACA,MAAMyE,OAAO,MAAMhB,SAASc,QAAQb,SAAS,EAAEa,QAAQZ,KAAK,EAAEY,QAAQX,MAAM;IAC5E,IAAI,CAACa,KAAKV,EAAE,EAAE,OAAO;QAAEgF,QAAQ;QAAKC,OAAO;IAAe;IAC1D,MAAM9G,UAAU,MAAM7C,iBAAiB;QACrCsE,OAAOY,QAAQZ,KAAK;QACpBC,QAAQW,QAAQX,MAAM;QACtBuB,KAAKZ,QAAQY,GAAG;QAChBrB,MAAMW,KAAKX,IAAI;QACfmB;IACF;IACA,OAAO/C,QAAQS,MAAM,GAAG,OAAO;QAAEoG,QAAQ;QAAKC,OAAO/I;IAA2B;AAClF;AAEA;;;;CAIC,GACD,OAAO,SAASgJ;IACdnJ,kBAAkB,WAAWwE,qBAAqB;QAAE4E,WAAWrJ;IAA+B;IAC9FJ,uBAAuB,WAAWqJ;AACpC"}
|
|
@@ -94,6 +94,10 @@ export interface SeoHostDocument {
|
|
|
94
94
|
howToUse?: string;
|
|
95
95
|
};
|
|
96
96
|
};
|
|
97
|
+
/** The one-block copy of the site's email, read when the entity has none (AGL-4136). */
|
|
98
|
+
business?: {
|
|
99
|
+
supportEmail?: string;
|
|
100
|
+
};
|
|
97
101
|
}
|
|
98
102
|
/**
|
|
99
103
|
* The fields a listing job writes: the ones the editor named (`inputs.fields`,
|
|
@@ -403,14 +403,17 @@ async function runProductListing(context, host) {
|
|
|
403
403
|
];
|
|
404
404
|
/** The site SEO form fields blank on the site now. */ export function aiSeoBlankSiteFields(host) {
|
|
405
405
|
var _ref, _ref1;
|
|
406
|
-
var _host_seo, _host_seo1;
|
|
406
|
+
var _host_seo, _host_seo1, _host_business;
|
|
407
407
|
const entity = (_ref = (_host_seo = host.seo) == null ? void 0 : _host_seo.entity) != null ? _ref : {};
|
|
408
408
|
const agent = (_ref1 = (_host_seo1 = host.seo) == null ? void 0 : _host_seo1.agent) != null ? _ref1 : {};
|
|
409
409
|
const blank = new Set();
|
|
410
410
|
if (entity.type === undefined || entity.type === null || entity.type === '') blank.add('seo.entity.type');
|
|
411
411
|
if (!str(entity.name)) blank.add('seo.entity.name');
|
|
412
412
|
if (!str(entity.description)) blank.add('seo.entity.description');
|
|
413
|
-
|
|
413
|
+
// The site's one email is the entity's, else the older one-block copy
|
|
414
|
+
// (AGL-4136); Setup → Business profile shows the copy in its Email field, so a
|
|
415
|
+
// site with only the copy has an email, and a proposal would replace it.
|
|
416
|
+
if (!str(entity.email) && !str((_host_business = host.business) == null ? void 0 : _host_business.supportEmail)) blank.add('seo.entity.email');
|
|
414
417
|
if (!str(entity.telephone)) blank.add('seo.entity.telephone');
|
|
415
418
|
if (!str(entity.contactType)) blank.add('seo.entity.contactType');
|
|
416
419
|
if (!str(agent.whenToUse)) blank.add('seo.agent.whenToUse');
|
|
@@ -431,7 +434,7 @@ async function runProductListing(context, host) {
|
|
|
431
434
|
}
|
|
432
435
|
/** `/llms.txt` as it reads with `values` saved over what the site stores now. */ export function aiSeoLlmsPreview(host, values, pages, collections) {
|
|
433
436
|
var _hostPublicOrigin, _values_seoagentwhenToUse, _values_seoagenthowToUse, _values_seoentityemail;
|
|
434
|
-
var _host_seo, _host_seo1, _host_seo_agent, _host_seo2, _host_seo_agent1, _host_seo3, _host_seo_entity, _host_seo4;
|
|
437
|
+
var _host_seo, _host_seo1, _host_seo_agent, _host_seo2, _host_seo_agent1, _host_seo3, _host_seo_entity, _host_seo4, _host_business;
|
|
435
438
|
return buildLlmsTxt({
|
|
436
439
|
siteName: str((_host_seo = host.seo) == null ? void 0 : _host_seo.title) || str(host.displayName) || 'Site',
|
|
437
440
|
origin: (_hostPublicOrigin = hostPublicOrigin(host)) != null ? _hostPublicOrigin : '',
|
|
@@ -443,7 +446,9 @@ async function runProductListing(context, host) {
|
|
|
443
446
|
pages,
|
|
444
447
|
collections,
|
|
445
448
|
hasSearch: true,
|
|
446
|
-
|
|
449
|
+
// As the site's own /llms.txt names it (AGL-4136): the entity's email,
|
|
450
|
+
// else the older one-block copy.
|
|
451
|
+
contactEmail: (_values_seoentityemail = values['seo.entity.email']) != null ? _values_seoentityemail : str((_host_seo4 = host.seo) == null ? void 0 : (_host_seo_entity = _host_seo4.entity) == null ? void 0 : _host_seo_entity.email) || str((_host_business = host.business) == null ? void 0 : _host_business.supportEmail) || undefined
|
|
447
452
|
});
|
|
448
453
|
}
|
|
449
454
|
async function proposeSite(context, host, scan) {
|