@aglyn/plugins-ai 1.6.0 → 1.8.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/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-import-step.d.ts +28 -2
- package/src/lib/jobs/ai-job-import-step.js +170 -14
- package/src/lib/jobs/ai-job-import-step.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-layout-language.js +2 -0
- package/src/lib/jobs/ai-job-layout-language.js.map +1 -1
- package/src/lib/jobs/ai-job-page-language.js +6 -2
- package/src/lib/jobs/ai-job-page-language.js.map +1 -1
- package/src/lib/jobs/ai-site-import-compile.d.ts +13 -3
- package/src/lib/jobs/ai-site-import-compile.js +336 -27
- package/src/lib/jobs/ai-site-import-compile.js.map +1 -1
- package/src/lib/jobs/ai-site-import-document.d.ts +3 -1
- package/src/lib/jobs/ai-site-import-document.js +36 -0
- package/src/lib/jobs/ai-site-import-document.js.map +1 -1
- package/src/lib/jobs/ai-site-import-look.d.ts +9 -0
- package/src/lib/jobs/ai-site-import-look.js +89 -6
- package/src/lib/jobs/ai-site-import-look.js.map +1 -1
- package/src/lib/layout-language/ai-layout-compiler.d.ts +16 -0
- package/src/lib/layout-language/ai-layout-compiler.js +351 -54
- package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
- package/src/lib/layout-language/ai-layout-frame-source.d.ts +88 -2
- package/src/lib/layout-language/ai-layout-frame-source.js +591 -30
- package/src/lib/layout-language/ai-layout-frame-source.js.map +1 -1
- package/src/lib/layout-language/ai-layout-frame.js +30 -18
- package/src/lib/layout-language/ai-layout-frame.js.map +1 -1
- package/src/lib/layout-language/ai-layout-language.d.ts +72 -3
- package/src/lib/layout-language/ai-layout-language.js +5 -3
- package/src/lib/layout-language/ai-layout-language.js.map +1 -1
- package/src/lib/layout-language/ai-layout-store.d.ts +8 -0
- package/src/lib/layout-language/ai-layout-store.js +32 -6
- package/src/lib/layout-language/ai-layout-store.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-import-fidelity.d.ts +31 -1
- package/src/lib/model/ai-site-import-fidelity.js +347 -25
- package/src/lib/model/ai-site-import-fidelity.js.map +1 -1
- package/src/lib/model/ai-site-import.d.ts +203 -6
- package/src/lib/model/ai-site-import.js +161 -5
- package/src/lib/model/ai-site-import.js.map +1 -1
- package/src/lib/model/ai-site-look.d.ts +8 -1
- package/src/lib/model/ai-site-look.js +8 -5
- package/src/lib/model/ai-site-look.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-doctrine-validators.d.ts +7 -1
- package/src/lib/runtime/ai-doctrine-validators.js +25 -2
- package/src/lib/runtime/ai-doctrine-validators.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/runtime/ai-node-tree.js +19 -2
- package/src/lib/runtime/ai-node-tree.js.map +1 -1
- package/src/lib/runtime/ai-page-links.d.ts +15 -0
- package/src/lib/runtime/ai-page-links.js +48 -0
- package/src/lib/runtime/ai-page-links.js.map +1 -1
- package/src/lib/site-import/fixtures/site-import-fidelity-replay.js +30 -5
- package/src/lib/site-import/fixtures/site-import-fidelity-replay.js.map +1 -1
- package/src/lib/site-import/fixtures/site-layout-recordings.d.ts +9 -0
- package/src/lib/site-import/fixtures/site-layout-recordings.js +24 -5
- package/src/lib/site-import/fixtures/site-layout-recordings.js.map +1 -1
- package/src/lib/site-import/site-import-crawl.d.ts +3 -1
- package/src/lib/site-import/site-import-crawl.js +8 -3
- package/src/lib/site-import/site-import-crawl.js.map +1 -1
- package/src/lib/site-import/site-import-css.d.ts +20 -0
- package/src/lib/site-import/site-import-css.js +106 -0
- package/src/lib/site-import/site-import-css.js.map +1 -1
- package/src/lib/site-import/site-import-html.d.ts +39 -0
- package/src/lib/site-import/site-import-html.js +515 -5
- package/src/lib/site-import/site-import-html.js.map +1 -1
- package/src/lib/site-import/site-import-layout.d.ts +16 -6
- package/src/lib/site-import/site-import-layout.js +524 -52
- package/src/lib/site-import/site-import-layout.js.map +1 -1
- package/src/lib/site-import/site-import-nav.js +286 -24
- package/src/lib/site-import/site-import-nav.js.map +1 -1
- package/src/lib/site-import/site-import-page.js +3 -0
- package/src/lib/site-import/site-import-page.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,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../../../../../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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M,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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-layout-language.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 { isHostImageToken, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport type { NodesMap } from '@aglyn/aglyn/types/nodes'\nimport { aiLayoutDesignChoices, type AiLayoutDesign } from '../layout-language/ai-layout-design'\nimport { aiCompileLayoutFrame, type AiLayoutFrameBrand } from '../layout-language/ai-layout-frame'\nimport { aiLayoutFrameSourceOf, aiLayoutFrameSourcePageIds, type AiLayoutFrameSource } from '../layout-language/ai-layout-frame-source'\nimport {\n aiLayoutFrameHollows,\n aiLayoutFrameHollowsSaid,\n aiLayoutFrameIsHollow,\n aiLayoutRepairFrameHollows,\n} from '../layout-language/ai-layout-frame-hollows'\nimport {\n AI_LAYOUT_FRAME_TOOL,\n AI_LAYOUT_LANGUAGE_TEXT,\n aiReadLayoutFrame,\n type AiLayoutSection,\n} from '../layout-language/ai-layout-language'\nimport type {\n AiLayoutPage,\n AiLayoutTargets,\n} from '../layout-language/ai-layout-links'\nimport { aiLayoutCopyCheck } from '../layout-language/ai-layout-gaps'\nimport { aiLayoutStoredTree } from '../layout-language/ai-layout-store'\nimport { AI_GENERATION_MAX_ATTEMPTS } from '../runtime/ai-generation-bounds'\nimport type { AiJob, AiJobPlan } from '../model/ai-jobs.types'\nimport { aiLayoutSpeaksOtherThanEnglish } from '../layout-language/ai-layout-labels'\nimport {\n aiHomeScreenIds,\n type AiSiteInventory,\n} from '../model/ai-site-inventory'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport type { AiGenerationCheck, AiValidatedTree } from '../runtime/ai-doctrine'\nimport {\n aiSettleMechanicalRules,\n aiSettleUnrelatedScreenLinks,\n validateAiDoctrineTree,\n type AiDoctrineNode,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { aiSiteKindDesignLines } from '../model/ai-site-kinds'\nimport type { AiStoreFrameLinks } from '../model/ai-site-store-pages'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { fenceUntrustedText, UNTRUSTED_TEXT_RULE } from '@aglyn/shared-util-tools/untrusted-text'\nimport { aiJobBriefLine } from './ai-job-generation'\nimport {\n AI_LAYOUT_SITE_PAGES_MAX,\n aiLayoutIsHomeSlug,\n aiLayoutSitePages,\n} from './ai-job-layout-site-pages'\nimport {\n AI_LAYOUT_FRAME_THINKING_TOKENS,\n aiLayoutPageTargets,\n} from './ai-job-page-language'\nimport { AI_SITE_NAME_TOKEN } from './ai-layout-site-facts'\n\n/**\n * A site's layout built in the compact layout language (AGL-3660): the layout\n * step's pass for a guided start's and a build's layout unit. The model\n * designs the header and the footer — their bands, the call to action, the\n * footer's columns and every word — in one short answer through\n * `submit_frame`, and the compiler writes the layout around what the site\n * owes it: its name as the brand, its pages as the navigation and the phone\n * menu, the Layout Slot, and the footer at the bottom of a short page\n * (`ai-layout-frame.ts`).\n */\n\n/**\n * The most a frame's answer asks for: two sections of a few blocks each (the\n * live runs of 2026-10-07 wrote 442 to 583), and the thinking before them.\n */\nexport const AI_JOB_LAYOUT_LANGUAGE_TOKENS = 1_200 + AI_LAYOUT_FRAME_THINKING_TOKENS\n\n/** A language layout pass's time, on the tier the layout step is served from. */\nexport const AI_JOB_LAYOUT_LANGUAGE_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.layout'],\n maxTokens: AI_JOB_LAYOUT_LANGUAGE_TOKENS,\n})\n\n/** The generation kind a frame is asked under, which the doctrine scopes. */\nexport const AI_LAYOUT_FRAME_KIND = 'layout-frame'\n\n/** The language, as the frame door's cached instructions. */\nexport const AI_JOB_LAYOUT_LANGUAGE_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n AI_LAYOUT_LANGUAGE_TEXT,\n '',\n \"Now you design a site's header and footer, each one section of the language, answered with submit_frame.\",\n \"- header: the platform writes the site's name and its navigation itself. Choose its band and align (start, or center for a centered navigation), and give it at most one button: the call to action every page shows.\",\n '- footer: a section like any other, usually a row of two or three columns: a few words about the business, the details the brief gives, and a list of links (items with to). Put no contact detail, opening hours or address in it that the brief does not give, and no gap in square brackets for one.',\n ].join('\\n'),\n cacheBreakpoint: true,\n },\n]\n\n/**\n * The unit input a site brought in from elsewhere gives its header and\n * footer (AGL-4084): its header's brand as the source draws it, and the words\n * the source's header and footer carry — its address, phone, email, hours\n * and profiles — word for word. Read defensively; `null` on every other job.\n */\nexport const AI_LAYOUT_SITE_BRAND_INPUT = 'siteBrand'\nexport const AI_LAYOUT_SITE_FACTS_INPUT = 'siteFacts'\n\n/**\n * The unit input a site brought in gives its header and footer where the\n * reader found the source's menu (AGL-4108): its menu, its buttons and its\n * footer, every link resolved to a page of the site or the source's own\n * address (`AiLayoutFrameSource`). With it the frame is drawn by code and no\n * model is asked; read defensively, `null` on every other job.\n */\nexport const AI_LAYOUT_SITE_FRAME_INPUT = 'siteFrame'\n\n/** A job's source frame (AGL-4108), held to what a link and a label may carry; `null` where it has none. */\nexport function aiLayoutSiteFrameOf(inputs: Readonly<Record<string, unknown>> | null | undefined): AiLayoutFrameSource | null {\n return aiLayoutFrameSourceOf(inputs?.[AI_LAYOUT_SITE_FRAME_INPUT])\n}\n\n/** The most characters of a site's own header and footer words a frame is shown. */\nexport const AI_LAYOUT_SITE_FACTS_MAX_CHARS = 4_000\n\nexport interface AiLayoutSiteFacts {\n /** Where they were read: the owner's own home page. */\n url: string\n /** The site's own description of itself. */\n description: string\n /** Its header's and footer's lines, as written. */\n lines: string[]\n}\n\nexport function aiLayoutSiteBrandOf(inputs: Readonly<Record<string, unknown>> | null | undefined): AiLayoutFrameBrand | null {\n const raw = inputs?.[AI_LAYOUT_SITE_BRAND_INPUT]\n if (!raw || typeof raw !== 'object') return null\n const value = raw as Record<string, unknown>\n const logo = value['logo'] as Record<string, unknown> | null | undefined\n const src = typeof logo?.['src'] === 'string' && logo['src'].trim() ? logo['src'].trim() : null\n // The logo's own words and shape, as the source names and draws it (AGL-4108).\n const alt = typeof value['alt'] === 'string' ? value['alt'].replace(/\\s+/g, ' ').trim().slice(0, 120) : ''\n const aspect = typeof value['aspect'] === 'number' && Number.isFinite(value['aspect']) && value['aspect'] > 0 ? Math.min(value['aspect'], 8) : null\n return { ...(src ? { logo: { src } } : {}), name: src ? value['name'] === true : true, ...(src && alt ? { alt } : {}), ...(src && aspect ? { aspect } : {}) }\n}\n\n/**\n * The brand a site's own logo gives its frame (AGL-4119), for the logo a\n * person brought to Create site: the logo alone, in the header and the footer.\n * By token rather than by value, so a logo changed later follows. `null` for\n * a site with none, whose frame carries its name as it always has.\n */\nexport function aiLayoutHostBrandOf(host: HostTokenSource | null | undefined): AiLayoutFrameBrand | null {\n if (!resolveHostToken('logo', host)) return null\n return {\n logo: { src: '{{host.logo}}' },\n ...(host?.logoDarkUrl?.trim() ? { logoDark: { src: '{{host.logoDark}}' } } : {}),\n name: false,\n footer: true,\n }\n}\n\n/** A job's brand: what a site brought in draws its logo as, else the site's own logo. */\nexport function aiLayoutFrameBrandOf(\n inputs: Readonly<Record<string, unknown>> | null | undefined,\n host: HostTokenSource | null | undefined,\n): AiLayoutFrameBrand | null {\n const brought = aiLayoutSiteBrandOf(inputs)\n return brought?.logo ? brought : (aiLayoutHostBrandOf(host) ?? brought)\n}\n\nexport function aiLayoutSiteFactsOf(inputs: Readonly<Record<string, unknown>> | null | undefined): AiLayoutSiteFacts | null {\n const raw = inputs?.[AI_LAYOUT_SITE_FACTS_INPUT]\n if (!raw || typeof raw !== 'object') return null\n const value = raw as Record<string, unknown>\n const lines = Array.isArray(value['lines']) ? value['lines'].filter((line): line is string => typeof line === 'string' && !!line.trim()) : []\n const description = typeof value['description'] === 'string' ? value['description'] : ''\n if (!lines.length && !description.trim()) return null\n return { url: typeof value['url'] === 'string' ? value['url'].slice(0, 2048) : '', description, lines }\n}\n\n/** A site's own header and footer words as one text, which its frame's contact details are held to (AGL-4084). */\nexport function aiLayoutSiteFactsText(inputs: Readonly<Record<string, unknown>> | null | undefined): string {\n const facts = aiLayoutSiteFactsOf(inputs)\n return facts ? [facts.description, ...facts.lines].filter(Boolean).join('\\n') : ''\n}\n\n/**\n * What a frame brought in from the owner's own site is told (AGL-4084): its\n * footer carries the details the source's header and footer give, as they\n * give them, and nothing else; the words themselves, fenced as data.\n */\nexport function aiLayoutSiteFactsLines(facts: AiLayoutSiteFacts | null): string[] {\n if (!facts) return []\n const text = [facts.description ? `About the site, in its own words: ${facts.description}` : '', ...facts.lines].filter(Boolean).join('\\n')\n return [\n \"This site's header and footer on its owner's current website carry the words below. Put in the footer the details they give (the address, phone number, email, hours and profiles), written exactly as they are written there, and its own words about itself; invent nothing they do not give, and print no word of these instructions.\",\n fenceUntrustedText(`The header and footer of ${facts.url || \"the owner's site\"}`, text, { maxChars: AI_LAYOUT_SITE_FACTS_MAX_CHARS }),\n ]\n}\n\n/** The frame door's system blocks: the language's, and for a site brought in the rule that fenced text is data (AGL-4084). */\nexport function aiJobLayoutLanguageInstructions(job: Pick<AiJob, 'inputs'>): readonly AiSystemBlock[] {\n return aiLayoutSiteFactsOf(job.inputs)\n ? [...AI_JOB_LAYOUT_LANGUAGE_INSTRUCTIONS, { text: UNTRUSTED_TEXT_RULE }]\n : AI_JOB_LAYOUT_LANGUAGE_INSTRUCTIONS\n}\n\n/** The site's name as the brand: the name the job was given, else the token the site's own name fills. */\nexport function aiLayoutSiteName(job: Pick<AiJob, 'inputs'>): string {\n const given = job.inputs?.['businessName']\n return typeof given === 'string' && given.trim()\n ? given.trim()\n : AI_SITE_NAME_TOKEN\n}\n\n/** The pages a frame's navigation links: the planned pages, else the site's own, in order. */\nexport function aiLayoutNavPages(\n job: Pick<AiJob, 'inputs'> & { plan?: Pick<AiJobPlan, 'language'> | null },\n inventory: AiSiteInventory | null,\n): AiLayoutPage[] {\n // The header and the footer link the pages the job was told (AGL-3660),\n // else the site's own, the home page always and first, labelled Home. The\n // model draws neither list, so it cannot drop a page. A site in another\n // language keeps its home page's own title: a Spanish start's \"Inicio\" was\n // linked as \"Home\" (AGL-3760).\n const planned = aiLayoutSitePages(job.inputs)\n const own = (inventory?.screens ?? [])\n .filter((row) => !row.template)\n .map((row) => ({ id: row.id, label: row.name, slug: row.slug }))\n const siteHome = planned.some((page) => aiLayoutIsHomeSlug(page.slug))\n ? []\n : own.filter((page) => aiLayoutIsHomeSlug(page.slug)).slice(0, 1)\n const pages = [...siteHome, ...(planned.length ? planned : own)].filter((page) => page.label.trim())\n const home = pages.find((page) => aiLayoutIsHomeSlug(page.slug))\n return [\n ...(home ? [aiLayoutSpeaksOtherThanEnglish(job.plan?.language) ? home : { ...home, label: 'Home' }] : []),\n ...pages.filter((page) => page !== home && !aiLayoutIsHomeSlug(page.slug)),\n ].slice(0, AI_LAYOUT_SITE_PAGES_MAX)\n}\n\n/** The home page the brand links: the planned home, else the site's. */\nexport function aiLayoutHomeId(\n pages: readonly AiLayoutPage[],\n inventory: AiSiteInventory | null,\n): string | null {\n const planned = pages.find((page) => aiLayoutIsHomeSlug(page.slug))\n return planned?.id ?? aiHomeScreenIds(inventory)[0] ?? null\n}\n\n/** The frame's user turn: the site, its brief, its pages and its form. */\nexport function aiLayoutFramePrompt(input: {\n job: Pick<AiJob, 'brief' | '$id'> & Partial<Pick<AiJob, 'inputs'>>\n siteName: string\n pages: readonly AiLayoutPage[]\n targets: AiLayoutTargets\n}): string {\n const { job, pages, targets } = input\n // A site brought in (AGL-4084) is told its own words, fenced, and no brief a footer could print.\n const facts = aiLayoutSiteFactsOf(job.inputs)\n return [\n `Site: ${input.siteName === AI_SITE_NAME_TOKEN ? 'the business the brief describes' : `\"${input.siteName}\"`}`,\n ...(facts ? aiLayoutSiteFactsLines(facts) : [aiJobBriefLine(job)]),\n ...aiSiteKindDesignLines(job.inputs),\n pages.length\n ? `Its pages, which the navigation links: ${pages.map((page) => `${page.label} (page:${page.id})`).join(', ')}.`\n : 'It has no pages yet.',\n targets.forms.length || targets.formPageId\n ? 'A call to action that asks a visitor to get in touch goes to form.'\n : 'The site has no form yet.',\n // A storefront's header (AGL-3676): its cart, and an announcement line.\n ...(aiLayoutShopPageId(targets)\n ? [\n \"This is an online store: give the header no button, since the platform puts the cart beside the navigation. Give the header one note instead: a short announcement for the bar above it, under 60 characters, about the shop from the brief (a promise it makes, such as its shipping, or what is new); never invent an offer, a discount, a price or a shipping threshold the brief does not give.\",\n ]\n : []),\n `Design seed: ${job.$id.slice(-6)}.`,\n ].join('\\n')\n}\n\n/** A store's Shop page, by its id: the page its catalog's whole list is placed on (AGL-3676). */\nexport function aiLayoutShopPageId(targets: Pick<AiLayoutTargets, 'listings'>): string | null {\n const products = (targets.listings ?? []).find((listing) => listing.kind === 'products')\n return products?.placements.find((placement) => placement.role === 'index')?.screenId ?? null\n}\n\n/** A validated language layout. */\nexport interface AiLayoutFrameBuilt {\n rootId: string\n nodes: NodesMap\n load: AiLoadEstimate | null\n /** What the last answer's gaps took out of the frame (`ai-layout-gaps.ts`). */\n dropped: string[]\n}\n\n/** What a frame is built with: the site, its pages and links, its look, and the layout door's own checks. */\nexport interface AiLayoutFrameInput {\n /** The header arrangement the site's look chose (AGL-3660); the answer's otherwise. */\n headerAlign?: 'start' | 'center'\n siteName: string\n homeId: string | null\n pages: readonly AiLayoutPage[]\n targets: AiLayoutTargets\n extend: (tree: AiValidatedTree) => AiDoctrineViolation[]\n /** The site's design (`aiLayoutDesignOf`), whose pages' closing band the footer sits under. */\n design?: AiLayoutDesign | null\n /** A store's own pages, which the header and footer link by path (AGL-3676). */\n storeLinks?: AiStoreFrameLinks | null\n /** The site's language, which the frame's own words are written in (AGL-3760). */\n language?: string\n /** The header's brand as a site brought in draws it (AGL-4084). */\n brand?: AiLayoutFrameBrand | null\n /** A site brought in's own header and footer (AGL-4108), drawn in place of the design's. */\n source?: AiLayoutFrameSource | null\n}\n\n/** The check a frame answer is held to: read, compiled, stored and checked as a layout, with the layout door's own checks. */\nexport function aiLayoutFrameCheck(input: AiLayoutFrameInput): AiGenerationCheck<AiLayoutFrameBuilt> {\n let answers = 0\n return (answer) => {\n // The last answer a generation takes has its gaps taken out rather than asked about again.\n answers += 1\n return aiLayoutFrameBuild(aiReadLayoutFrame(answer), input, answers >= AI_GENERATION_MAX_ATTEMPTS)\n }\n}\n\n/**\n * A site brought in's header and footer as its source builds them\n * (AGL-4108), with no model: compiled, stored and checked as a layout, held\n * to every check an answer is. `value` is `null` with the violations where it\n * does not pass, and the frame is then designed by the model instead.\n */\nexport function aiLayoutSourceFrameBuild(input: AiLayoutFrameInput & { source: AiLayoutFrameSource }): ReturnType<AiGenerationCheck<AiLayoutFrameBuilt>> {\n const band = input.source.header === 'brand' || input.source.header === 'dark' ? input.source.header : 'plain'\n return aiLayoutFrameBuild({ header: { band, align: 'start', blocks: [] }, footer: null }, input, true)\n}\n\n/** A frame compiled, stored and checked as a layout; `last` takes its gaps out rather than asking about them. */\nfunction aiLayoutFrameBuild(frame: { header: AiLayoutSection | null; footer: AiLayoutSection | null }, input: AiLayoutFrameInput, last: boolean): ReturnType<AiGenerationCheck<AiLayoutFrameBuilt>> {\n if (input.headerAlign && frame.header && !input.source) frame.header.align = input.headerAlign\n const compiled = aiCompileLayoutFrame(\n frame,\n {\n siteName: input.siteName,\n homeId: input.homeId,\n navPages: input.pages,\n closesDark: input.design ? aiLayoutDesignChoices(input.design).coverClose : false,\n // A site that sells carries its cart in the header (AGL-3676).\n cart: (input.targets.listings ?? []).some((listing) => listing.kind === 'products' && listing.cart !== false),\n // And a store's header is a storefront's: no button repeating its navigation, an announcement bar (AGL-3676).\n shopId: aiLayoutShopPageId(input.targets),\n // And its account and policies, written after it (AGL-3676).\n storeLinks: input.storeLinks ?? null,\n ...(input.language ? { language: input.language } : {}),\n ...(input.brand ? { brand: input.brand } : {}),\n ...(input.source ? { source: input.source } : {}),\n },\n input.targets,\n )\n // The pages a source's menu and footer link by id (AGL-4108).\n const sourcePages = input.source ? aiLayoutFrameSourcePageIds(input.source) : []\n // A site's own logo is a token no address rule knows (AGL-4119), and these\n // two are ours to name: no model writes them.\n const logoTokens = [input.brand?.logo?.src, input.brand?.logoDark?.src].filter(\n (src): src is string => Boolean(src && isHostImageToken(src)),\n )\n const context = {\n screenIds: [\n ...new Set([\n ...input.targets.pages.map((page) => page.id),\n ...input.pages.map((page) => page.id),\n ...(input.homeId ? [input.homeId] : []),\n ...sourcePages,\n ]),\n ],\n formIds: input.targets.forms.map((form) => form.id),\n homeScreenIds: input.targets.homeIds,\n // A link home under the home page's own title says home, in any language (AGL-3760).\n homeLabels: [\n ...input.pages.filter((page) => aiLayoutIsHomeSlug(page.slug)),\n ...input.targets.pages.filter((page) => input.targets.homeIds.includes(page.id)),\n ].map((page) => page.label),\n // A footer's \"Get in touch\" goes to the form, wherever it is placed (AGL-3729).\n ...(input.targets.formPageId ? { formScreenIds: [input.targets.formPageId] } : {}),\n codeBuilt: true,\n ...(logoTokens.length ? { bindingTokens: logoTokens } : {}),\n // A source's header and footer are its owner's own words and menu\n // (AGL-4108), drawn by code where they repeat: no model wrote a block\n // twice that a component should carry once.\n ...(input.source ? { ownWords: true, reusableComponents: false } : {}),\n }\n const stored = aiLayoutStoredTree(compiled.tree, 'layout', context)\n if (stored.ok === false) {\n console.error('ai layout frame: a compiled layout did not store', {\n error: stored.error,\n })\n return {\n value: null,\n violations: [\n {\n rule: null,\n code: 'layout-compile',\n message: 'This layout could not be built. Try again.',\n detail: stored.error,\n },\n ],\n }\n }\n // No gap and no internal reference in the words of a frame every published page shows.\n const navPages = [...input.targets.pages, ...input.pages]\n const copy = aiLayoutCopyCheck(\n stored.nodes,\n stored.rootId,\n {\n pages: navPages,\n ids: [...navPages.map((page) => page.id), ...input.targets.forms.map((form) => form.id)],\n },\n last,\n )\n const { dropped } = copy\n // An attribute a rule has one answer for is settled, not asked of the model again (AGL-3660).\n const nodes = aiSettleUnrelatedScreenLinks(\n aiSettleMechanicalRules(\n { rootId: stored.rootId, nodes: copy.nodes as unknown as Record<string, AiDoctrineNode> },\n 'layout',\n // And on the last answer, a link that goes nowhere, as the check below reads it (AGL-4076).\n last ? context : undefined,\n ),\n 'layout',\n context,\n ).nodes as unknown as typeof copy.nodes\n // The copy check can take words out of the footer: no heading or column\n // is left with nothing under it (AGL-3735), and none may remain.\n aiLayoutRepairFrameHollows(nodes as unknown as Record<string, unknown>)\n const hollow = aiLayoutFrameHollows(nodes as unknown as Record<string, unknown>)\n const report = validateAiDoctrineTree(\n { rootId: stored.rootId, nodes },\n 'layout',\n context,\n )\n const violations = [\n ...report.violations,\n ...(aiLayoutFrameIsHollow(hollow)\n ? [\n {\n rule: null,\n code: 'layout-frame-hollow',\n message: 'Every footer heading needs something under it, and every footer column more than a heading.',\n detail: aiLayoutFrameHollowsSaid(hollow).join('; '),\n },\n ]\n : []),\n ...copy.violations,\n ...input.extend({\n rootId: stored.rootId,\n nodes,\n repairs: [],\n sourceIds: {},\n score: report.score as AiValidatedTree['score'],\n load: report.load,\n }),\n ]\n return {\n value: violations.length\n ? null\n : { rootId: stored.rootId, nodes, load: report.load, dropped },\n violations,\n }\n}\n\n/** What a frame's links resolve against: the site's pages and its form, as a page's do. */\nexport function aiLayoutFrameTargets(\n job: Pick<AiJob, 'brief' | 'inputs'>,\n inventory: AiSiteInventory | null,\n): AiLayoutTargets {\n return aiLayoutPageTargets({ job, inventory, own: [] })\n}\n"],"names":["isHostImageToken","resolveHostToken","aiLayoutDesignChoices","aiCompileLayoutFrame","aiLayoutFrameSourceOf","aiLayoutFrameSourcePageIds","aiLayoutFrameHollows","aiLayoutFrameHollowsSaid","aiLayoutFrameIsHollow","aiLayoutRepairFrameHollows","AI_LAYOUT_LANGUAGE_TEXT","aiReadLayoutFrame","aiLayoutCopyCheck","aiLayoutStoredTree","AI_GENERATION_MAX_ATTEMPTS","aiLayoutSpeaksOtherThanEnglish","aiHomeScreenIds","AI_STEP_TIERS","aiSettleMechanicalRules","aiSettleUnrelatedScreenLinks","validateAiDoctrineTree","aiSiteKindDesignLines","aiJobStepBudget","fenceUntrustedText","UNTRUSTED_TEXT_RULE","aiJobBriefLine","AI_LAYOUT_SITE_PAGES_MAX","aiLayoutIsHomeSlug","aiLayoutSitePages","AI_LAYOUT_FRAME_THINKING_TOKENS","aiLayoutPageTargets","AI_SITE_NAME_TOKEN","AI_JOB_LAYOUT_LANGUAGE_TOKENS","AI_JOB_LAYOUT_LANGUAGE_BUDGET","tier","maxTokens","AI_LAYOUT_FRAME_KIND","AI_JOB_LAYOUT_LANGUAGE_INSTRUCTIONS","text","join","cacheBreakpoint","AI_LAYOUT_SITE_BRAND_INPUT","AI_LAYOUT_SITE_FACTS_INPUT","AI_LAYOUT_SITE_FRAME_INPUT","aiLayoutSiteFrameOf","inputs","AI_LAYOUT_SITE_FACTS_MAX_CHARS","aiLayoutSiteBrandOf","raw","value","logo","src","trim","alt","replace","slice","aspect","Number","isFinite","Math","min","name","aiLayoutHostBrandOf","host","logoDarkUrl","logoDark","footer","aiLayoutFrameBrandOf","brought","aiLayoutSiteFactsOf","lines","Array","isArray","filter","line","description","length","url","aiLayoutSiteFactsText","facts","Boolean","aiLayoutSiteFactsLines","maxChars","aiJobLayoutLanguageInstructions","job","aiLayoutSiteName","given","aiLayoutNavPages","inventory","planned","own","screens","row","template","map","id","label","slug","siteHome","some","page","pages","home","find","plan","language","aiLayoutHomeId","aiLayoutFramePrompt","input","targets","siteName","forms","formPageId","aiLayoutShopPageId","$id","products","listings","listing","kind","placements","placement","role","screenId","aiLayoutFrameCheck","answers","answer","aiLayoutFrameBuild","aiLayoutSourceFrameBuild","band","source","header","align","blocks","frame","last","headerAlign","compiled","homeId","navPages","closesDark","design","coverClose","cart","shopId","storeLinks","brand","sourcePages","logoTokens","context","screenIds","Set","formIds","form","homeScreenIds","homeIds","homeLabels","includes","formScreenIds","codeBuilt","bindingTokens","ownWords","reusableComponents","stored","tree","ok","console","error","violations","rule","code","message","detail","copy","nodes","rootId","ids","dropped","undefined","hollow","report","extend","repairs","sourceIds","score","load","aiLayoutFrameTargets"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,gBAAgB,QAA8B,qCAAoC;AAE7G,SAASC,qBAAqB,QAA6B,yCAAqC;AAChG,SAASC,oBAAoB,QAAiC,wCAAoC;AAClG,SAASC,qBAAqB,EAAEC,0BAA0B,QAAkC,+CAA2C;AACvI,SACEC,oBAAoB,EACpBC,wBAAwB,EACxBC,qBAAqB,EACrBC,0BAA0B,QACrB,gDAA4C;AACnD,SAEEC,uBAAuB,EACvBC,iBAAiB,QAEZ,2CAAuC;AAK9C,SAASC,iBAAiB,QAAQ,uCAAmC;AACrE,SAASC,kBAAkB,QAAQ,wCAAoC;AACvE,SAASC,0BAA0B,QAAQ,qCAAiC;AAE5E,SAASC,8BAA8B,QAAQ,yCAAqC;AACpF,SACEC,eAAe,QAEV,gCAA4B;AACnC,SAASC,aAAa,QAAQ,0BAAsB;AAEpD,SACEC,uBAAuB,EACvBC,4BAA4B,EAC5BC,sBAAsB,QAGjB,uCAAmC;AAE1C,SAASC,qBAAqB,QAAQ,4BAAwB;AAG9D,SAASC,eAAe,QAAQ,qBAAiB;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/ai/src/lib/jobs/ai-job-layout-language.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 { isHostImageToken, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport type { NodesMap } from '@aglyn/aglyn/types/nodes'\nimport { aiLayoutDesignChoices, type AiLayoutDesign } from '../layout-language/ai-layout-design'\nimport { aiCompileLayoutFrame, type AiLayoutFrameBrand } from '../layout-language/ai-layout-frame'\nimport { aiLayoutFrameSourceOf, aiLayoutFrameSourcePageIds, type AiLayoutFrameSource } from '../layout-language/ai-layout-frame-source'\nimport {\n aiLayoutFrameHollows,\n aiLayoutFrameHollowsSaid,\n aiLayoutFrameIsHollow,\n aiLayoutRepairFrameHollows,\n} from '../layout-language/ai-layout-frame-hollows'\nimport {\n AI_LAYOUT_FRAME_TOOL,\n AI_LAYOUT_LANGUAGE_TEXT,\n aiReadLayoutFrame,\n type AiLayoutSection,\n} from '../layout-language/ai-layout-language'\nimport type {\n AiLayoutPage,\n AiLayoutTargets,\n} from '../layout-language/ai-layout-links'\nimport { aiLayoutCopyCheck } from '../layout-language/ai-layout-gaps'\nimport { aiLayoutStoredTree } from '../layout-language/ai-layout-store'\nimport { AI_GENERATION_MAX_ATTEMPTS } from '../runtime/ai-generation-bounds'\nimport type { AiJob, AiJobPlan } from '../model/ai-jobs.types'\nimport { aiLayoutSpeaksOtherThanEnglish } from '../layout-language/ai-layout-labels'\nimport {\n aiHomeScreenIds,\n type AiSiteInventory,\n} from '../model/ai-site-inventory'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport type { AiGenerationCheck, AiValidatedTree } from '../runtime/ai-doctrine'\nimport {\n aiSettleMechanicalRules,\n aiSettleUnrelatedScreenLinks,\n validateAiDoctrineTree,\n type AiDoctrineNode,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { aiSiteKindDesignLines } from '../model/ai-site-kinds'\nimport type { AiStoreFrameLinks } from '../model/ai-site-store-pages'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { fenceUntrustedText, UNTRUSTED_TEXT_RULE } from '@aglyn/shared-util-tools/untrusted-text'\nimport { aiJobBriefLine } from './ai-job-generation'\nimport {\n AI_LAYOUT_SITE_PAGES_MAX,\n aiLayoutIsHomeSlug,\n aiLayoutSitePages,\n} from './ai-job-layout-site-pages'\nimport {\n AI_LAYOUT_FRAME_THINKING_TOKENS,\n aiLayoutPageTargets,\n} from './ai-job-page-language'\nimport { AI_SITE_NAME_TOKEN } from './ai-layout-site-facts'\n\n/**\n * A site's layout built in the compact layout language (AGL-3660): the layout\n * step's pass for a guided start's and a build's layout unit. The model\n * designs the header and the footer — their bands, the call to action, the\n * footer's columns and every word — in one short answer through\n * `submit_frame`, and the compiler writes the layout around what the site\n * owes it: its name as the brand, its pages as the navigation and the phone\n * menu, the Layout Slot, and the footer at the bottom of a short page\n * (`ai-layout-frame.ts`).\n */\n\n/**\n * The most a frame's answer asks for: two sections of a few blocks each (the\n * live runs of 2026-10-07 wrote 442 to 583), and the thinking before them.\n */\nexport const AI_JOB_LAYOUT_LANGUAGE_TOKENS = 1_200 + AI_LAYOUT_FRAME_THINKING_TOKENS\n\n/** A language layout pass's time, on the tier the layout step is served from. */\nexport const AI_JOB_LAYOUT_LANGUAGE_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.layout'],\n maxTokens: AI_JOB_LAYOUT_LANGUAGE_TOKENS,\n})\n\n/** The generation kind a frame is asked under, which the doctrine scopes. */\nexport const AI_LAYOUT_FRAME_KIND = 'layout-frame'\n\n/** The language, as the frame door's cached instructions. */\nexport const AI_JOB_LAYOUT_LANGUAGE_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n AI_LAYOUT_LANGUAGE_TEXT,\n '',\n \"Now you design a site's header and footer, each one section of the language, answered with submit_frame.\",\n \"- header: the platform writes the site's name and its navigation itself. Choose its band and align (start, or center for a centered navigation), and give it at most one button: the call to action every page shows.\",\n '- footer: a section like any other, usually a row of two or three columns: a few words about the business, the details the brief gives, and a list of links (items with to). Put no contact detail, opening hours or address in it that the brief does not give, and no gap in square brackets for one.',\n ].join('\\n'),\n cacheBreakpoint: true,\n },\n]\n\n/**\n * The unit input a site brought in from elsewhere gives its header and\n * footer (AGL-4084): its header's brand as the source draws it, and the words\n * the source's header and footer carry — its address, phone, email, hours\n * and profiles — word for word. Read defensively; `null` on every other job.\n */\nexport const AI_LAYOUT_SITE_BRAND_INPUT = 'siteBrand'\nexport const AI_LAYOUT_SITE_FACTS_INPUT = 'siteFacts'\n\n/**\n * The unit input a site brought in gives its header and footer where the\n * reader found the source's menu (AGL-4108): its menu, its buttons and its\n * footer, every link resolved to a page of the site or the source's own\n * address (`AiLayoutFrameSource`). With it the frame is drawn by code and no\n * model is asked; read defensively, `null` on every other job.\n */\nexport const AI_LAYOUT_SITE_FRAME_INPUT = 'siteFrame'\n\n/** A job's source frame (AGL-4108), held to what a link and a label may carry; `null` where it has none. */\nexport function aiLayoutSiteFrameOf(inputs: Readonly<Record<string, unknown>> | null | undefined): AiLayoutFrameSource | null {\n return aiLayoutFrameSourceOf(inputs?.[AI_LAYOUT_SITE_FRAME_INPUT])\n}\n\n/** The most characters of a site's own header and footer words a frame is shown. */\nexport const AI_LAYOUT_SITE_FACTS_MAX_CHARS = 4_000\n\nexport interface AiLayoutSiteFacts {\n /** Where they were read: the owner's own home page. */\n url: string\n /** The site's own description of itself. */\n description: string\n /** Its header's and footer's lines, as written. */\n lines: string[]\n}\n\nexport function aiLayoutSiteBrandOf(inputs: Readonly<Record<string, unknown>> | null | undefined): AiLayoutFrameBrand | null {\n const raw = inputs?.[AI_LAYOUT_SITE_BRAND_INPUT]\n if (!raw || typeof raw !== 'object') return null\n const value = raw as Record<string, unknown>\n const logo = value['logo'] as Record<string, unknown> | null | undefined\n const src = typeof logo?.['src'] === 'string' && logo['src'].trim() ? logo['src'].trim() : null\n // The logo's own words and shape, as the source names and draws it (AGL-4108).\n const alt = typeof value['alt'] === 'string' ? value['alt'].replace(/\\s+/g, ' ').trim().slice(0, 120) : ''\n const aspect = typeof value['aspect'] === 'number' && Number.isFinite(value['aspect']) && value['aspect'] > 0 ? Math.min(value['aspect'], 8) : null\n return {\n ...(src ? { logo: { src } } : {}),\n name: src ? value['name'] === true : true,\n ...(src && alt ? { alt } : {}),\n ...(src && aspect ? { aspect } : {}),\n // The footer opens with the logo too, where the source's does (AGL-4139).\n ...(src && value['footer'] === true ? { footer: true } : {}),\n }\n}\n\n/**\n * The brand a site's own logo gives its frame (AGL-4119), for the logo a\n * person brought to Create site: the logo alone, in the header and the footer.\n * By token rather than by value, so a logo changed later follows. `null` for\n * a site with none, whose frame carries its name as it always has.\n */\nexport function aiLayoutHostBrandOf(host: HostTokenSource | null | undefined): AiLayoutFrameBrand | null {\n if (!resolveHostToken('logo', host)) return null\n return {\n logo: { src: '{{host.logo}}' },\n ...(host?.logoDarkUrl?.trim() ? { logoDark: { src: '{{host.logoDark}}' } } : {}),\n name: false,\n footer: true,\n }\n}\n\n/** A job's brand: what a site brought in draws its logo as, else the site's own logo. */\nexport function aiLayoutFrameBrandOf(\n inputs: Readonly<Record<string, unknown>> | null | undefined,\n host: HostTokenSource | null | undefined,\n): AiLayoutFrameBrand | null {\n const brought = aiLayoutSiteBrandOf(inputs)\n return brought?.logo ? brought : (aiLayoutHostBrandOf(host) ?? brought)\n}\n\nexport function aiLayoutSiteFactsOf(inputs: Readonly<Record<string, unknown>> | null | undefined): AiLayoutSiteFacts | null {\n const raw = inputs?.[AI_LAYOUT_SITE_FACTS_INPUT]\n if (!raw || typeof raw !== 'object') return null\n const value = raw as Record<string, unknown>\n const lines = Array.isArray(value['lines']) ? value['lines'].filter((line): line is string => typeof line === 'string' && !!line.trim()) : []\n const description = typeof value['description'] === 'string' ? value['description'] : ''\n if (!lines.length && !description.trim()) return null\n return { url: typeof value['url'] === 'string' ? value['url'].slice(0, 2048) : '', description, lines }\n}\n\n/** A site's own header and footer words as one text, which its frame's contact details are held to (AGL-4084). */\nexport function aiLayoutSiteFactsText(inputs: Readonly<Record<string, unknown>> | null | undefined): string {\n const facts = aiLayoutSiteFactsOf(inputs)\n return facts ? [facts.description, ...facts.lines].filter(Boolean).join('\\n') : ''\n}\n\n/**\n * What a frame brought in from the owner's own site is told (AGL-4084): its\n * footer carries the details the source's header and footer give, as they\n * give them, and nothing else; the words themselves, fenced as data.\n */\nexport function aiLayoutSiteFactsLines(facts: AiLayoutSiteFacts | null): string[] {\n if (!facts) return []\n const text = [facts.description ? `About the site, in its own words: ${facts.description}` : '', ...facts.lines].filter(Boolean).join('\\n')\n return [\n \"This site's header and footer on its owner's current website carry the words below. Put in the footer the details they give (the address, phone number, email, hours and profiles), written exactly as they are written there, and its own words about itself; invent nothing they do not give, and print no word of these instructions.\",\n fenceUntrustedText(`The header and footer of ${facts.url || \"the owner's site\"}`, text, { maxChars: AI_LAYOUT_SITE_FACTS_MAX_CHARS }),\n ]\n}\n\n/** The frame door's system blocks: the language's, and for a site brought in the rule that fenced text is data (AGL-4084). */\nexport function aiJobLayoutLanguageInstructions(job: Pick<AiJob, 'inputs'>): readonly AiSystemBlock[] {\n return aiLayoutSiteFactsOf(job.inputs)\n ? [...AI_JOB_LAYOUT_LANGUAGE_INSTRUCTIONS, { text: UNTRUSTED_TEXT_RULE }]\n : AI_JOB_LAYOUT_LANGUAGE_INSTRUCTIONS\n}\n\n/** The site's name as the brand: the name the job was given, else the token the site's own name fills. */\nexport function aiLayoutSiteName(job: Pick<AiJob, 'inputs'>): string {\n const given = job.inputs?.['businessName']\n return typeof given === 'string' && given.trim()\n ? given.trim()\n : AI_SITE_NAME_TOKEN\n}\n\n/** The pages a frame's navigation links: the planned pages, else the site's own, in order. */\nexport function aiLayoutNavPages(\n job: Pick<AiJob, 'inputs'> & { plan?: Pick<AiJobPlan, 'language'> | null },\n inventory: AiSiteInventory | null,\n): AiLayoutPage[] {\n // The header and the footer link the pages the job was told (AGL-3660),\n // else the site's own, the home page always and first, labelled Home. The\n // model draws neither list, so it cannot drop a page. A site in another\n // language keeps its home page's own title: a Spanish start's \"Inicio\" was\n // linked as \"Home\" (AGL-3760).\n const planned = aiLayoutSitePages(job.inputs)\n const own = (inventory?.screens ?? [])\n .filter((row) => !row.template)\n .map((row) => ({ id: row.id, label: row.name, slug: row.slug }))\n const siteHome = planned.some((page) => aiLayoutIsHomeSlug(page.slug))\n ? []\n : own.filter((page) => aiLayoutIsHomeSlug(page.slug)).slice(0, 1)\n const pages = [...siteHome, ...(planned.length ? planned : own)].filter((page) => page.label.trim())\n const home = pages.find((page) => aiLayoutIsHomeSlug(page.slug))\n return [\n ...(home ? [aiLayoutSpeaksOtherThanEnglish(job.plan?.language) ? home : { ...home, label: 'Home' }] : []),\n ...pages.filter((page) => page !== home && !aiLayoutIsHomeSlug(page.slug)),\n ].slice(0, AI_LAYOUT_SITE_PAGES_MAX)\n}\n\n/** The home page the brand links: the planned home, else the site's. */\nexport function aiLayoutHomeId(\n pages: readonly AiLayoutPage[],\n inventory: AiSiteInventory | null,\n): string | null {\n const planned = pages.find((page) => aiLayoutIsHomeSlug(page.slug))\n return planned?.id ?? aiHomeScreenIds(inventory)[0] ?? null\n}\n\n/** The frame's user turn: the site, its brief, its pages and its form. */\nexport function aiLayoutFramePrompt(input: {\n job: Pick<AiJob, 'brief' | '$id'> & Partial<Pick<AiJob, 'inputs'>>\n siteName: string\n pages: readonly AiLayoutPage[]\n targets: AiLayoutTargets\n}): string {\n const { job, pages, targets } = input\n // A site brought in (AGL-4084) is told its own words, fenced, and no brief a footer could print.\n const facts = aiLayoutSiteFactsOf(job.inputs)\n return [\n `Site: ${input.siteName === AI_SITE_NAME_TOKEN ? 'the business the brief describes' : `\"${input.siteName}\"`}`,\n ...(facts ? aiLayoutSiteFactsLines(facts) : [aiJobBriefLine(job)]),\n ...aiSiteKindDesignLines(job.inputs),\n pages.length\n ? `Its pages, which the navigation links: ${pages.map((page) => `${page.label} (page:${page.id})`).join(', ')}.`\n : 'It has no pages yet.',\n targets.forms.length || targets.formPageId\n ? 'A call to action that asks a visitor to get in touch goes to form.'\n : 'The site has no form yet.',\n // A storefront's header (AGL-3676): its cart, and an announcement line.\n ...(aiLayoutShopPageId(targets)\n ? [\n \"This is an online store: give the header no button, since the platform puts the cart beside the navigation. Give the header one note instead: a short announcement for the bar above it, under 60 characters, about the shop from the brief (a promise it makes, such as its shipping, or what is new); never invent an offer, a discount, a price or a shipping threshold the brief does not give.\",\n ]\n : []),\n `Design seed: ${job.$id.slice(-6)}.`,\n ].join('\\n')\n}\n\n/** A store's Shop page, by its id: the page its catalog's whole list is placed on (AGL-3676). */\nexport function aiLayoutShopPageId(targets: Pick<AiLayoutTargets, 'listings'>): string | null {\n const products = (targets.listings ?? []).find((listing) => listing.kind === 'products')\n return products?.placements.find((placement) => placement.role === 'index')?.screenId ?? null\n}\n\n/** A validated language layout. */\nexport interface AiLayoutFrameBuilt {\n rootId: string\n nodes: NodesMap\n load: AiLoadEstimate | null\n /** What the last answer's gaps took out of the frame (`ai-layout-gaps.ts`). */\n dropped: string[]\n}\n\n/** What a frame is built with: the site, its pages and links, its look, and the layout door's own checks. */\nexport interface AiLayoutFrameInput {\n /** The header arrangement the site's look chose (AGL-3660); the answer's otherwise. */\n headerAlign?: 'start' | 'center'\n siteName: string\n homeId: string | null\n pages: readonly AiLayoutPage[]\n targets: AiLayoutTargets\n extend: (tree: AiValidatedTree) => AiDoctrineViolation[]\n /** The site's design (`aiLayoutDesignOf`), whose pages' closing band the footer sits under. */\n design?: AiLayoutDesign | null\n /** A store's own pages, which the header and footer link by path (AGL-3676). */\n storeLinks?: AiStoreFrameLinks | null\n /** The site's language, which the frame's own words are written in (AGL-3760). */\n language?: string\n /** The header's brand as a site brought in draws it (AGL-4084). */\n brand?: AiLayoutFrameBrand | null\n /** A site brought in's own header and footer (AGL-4108), drawn in place of the design's. */\n source?: AiLayoutFrameSource | null\n}\n\n/** The check a frame answer is held to: read, compiled, stored and checked as a layout, with the layout door's own checks. */\nexport function aiLayoutFrameCheck(input: AiLayoutFrameInput): AiGenerationCheck<AiLayoutFrameBuilt> {\n let answers = 0\n return (answer) => {\n // The last answer a generation takes has its gaps taken out rather than asked about again.\n answers += 1\n return aiLayoutFrameBuild(aiReadLayoutFrame(answer), input, answers >= AI_GENERATION_MAX_ATTEMPTS)\n }\n}\n\n/**\n * A site brought in's header and footer as its source builds them\n * (AGL-4108), with no model: compiled, stored and checked as a layout, held\n * to every check an answer is. `value` is `null` with the violations where it\n * does not pass, and the frame is then designed by the model instead.\n */\nexport function aiLayoutSourceFrameBuild(input: AiLayoutFrameInput & { source: AiLayoutFrameSource }): ReturnType<AiGenerationCheck<AiLayoutFrameBuilt>> {\n const band = input.source.header === 'brand' || input.source.header === 'dark' ? input.source.header : 'plain'\n return aiLayoutFrameBuild({ header: { band, align: 'start', blocks: [] }, footer: null }, input, true)\n}\n\n/** A frame compiled, stored and checked as a layout; `last` takes its gaps out rather than asking about them. */\nfunction aiLayoutFrameBuild(frame: { header: AiLayoutSection | null; footer: AiLayoutSection | null }, input: AiLayoutFrameInput, last: boolean): ReturnType<AiGenerationCheck<AiLayoutFrameBuilt>> {\n if (input.headerAlign && frame.header && !input.source) frame.header.align = input.headerAlign\n const compiled = aiCompileLayoutFrame(\n frame,\n {\n siteName: input.siteName,\n homeId: input.homeId,\n navPages: input.pages,\n closesDark: input.design ? aiLayoutDesignChoices(input.design).coverClose : false,\n // A site that sells carries its cart in the header (AGL-3676).\n cart: (input.targets.listings ?? []).some((listing) => listing.kind === 'products' && listing.cart !== false),\n // And a store's header is a storefront's: no button repeating its navigation, an announcement bar (AGL-3676).\n shopId: aiLayoutShopPageId(input.targets),\n // And its account and policies, written after it (AGL-3676).\n storeLinks: input.storeLinks ?? null,\n ...(input.language ? { language: input.language } : {}),\n ...(input.brand ? { brand: input.brand } : {}),\n ...(input.source ? { source: input.source } : {}),\n },\n input.targets,\n )\n // The pages a source's menu and footer link by id (AGL-4108).\n const sourcePages = input.source ? aiLayoutFrameSourcePageIds(input.source) : []\n // A site's own logo is a token no address rule knows (AGL-4119), and these\n // two are ours to name: no model writes them.\n const logoTokens = [input.brand?.logo?.src, input.brand?.logoDark?.src].filter(\n (src): src is string => Boolean(src && isHostImageToken(src)),\n )\n const context = {\n screenIds: [\n ...new Set([\n ...input.targets.pages.map((page) => page.id),\n ...input.pages.map((page) => page.id),\n ...(input.homeId ? [input.homeId] : []),\n ...sourcePages,\n ]),\n ],\n formIds: input.targets.forms.map((form) => form.id),\n homeScreenIds: input.targets.homeIds,\n // A link home under the home page's own title says home, in any language (AGL-3760).\n homeLabels: [\n ...input.pages.filter((page) => aiLayoutIsHomeSlug(page.slug)),\n ...input.targets.pages.filter((page) => input.targets.homeIds.includes(page.id)),\n ].map((page) => page.label),\n // A footer's \"Get in touch\" goes to the form, wherever it is placed (AGL-3729).\n ...(input.targets.formPageId ? { formScreenIds: [input.targets.formPageId] } : {}),\n codeBuilt: true,\n ...(logoTokens.length ? { bindingTokens: logoTokens } : {}),\n // A source's header and footer are its owner's own words and menu\n // (AGL-4108), drawn by code where they repeat: no model wrote a block\n // twice that a component should carry once.\n ...(input.source ? { ownWords: true, reusableComponents: false } : {}),\n }\n const stored = aiLayoutStoredTree(compiled.tree, 'layout', context)\n if (stored.ok === false) {\n console.error('ai layout frame: a compiled layout did not store', {\n error: stored.error,\n })\n return {\n value: null,\n violations: [\n {\n rule: null,\n code: 'layout-compile',\n message: 'This layout could not be built. Try again.',\n detail: stored.error,\n },\n ],\n }\n }\n // No gap and no internal reference in the words of a frame every published page shows.\n const navPages = [...input.targets.pages, ...input.pages]\n const copy = aiLayoutCopyCheck(\n stored.nodes,\n stored.rootId,\n {\n pages: navPages,\n ids: [...navPages.map((page) => page.id), ...input.targets.forms.map((form) => form.id)],\n },\n last,\n )\n const { dropped } = copy\n // An attribute a rule has one answer for is settled, not asked of the model again (AGL-3660).\n const nodes = aiSettleUnrelatedScreenLinks(\n aiSettleMechanicalRules(\n { rootId: stored.rootId, nodes: copy.nodes as unknown as Record<string, AiDoctrineNode> },\n 'layout',\n // And on the last answer, a link that goes nowhere, as the check below reads it (AGL-4076).\n last ? context : undefined,\n ),\n 'layout',\n context,\n ).nodes as unknown as typeof copy.nodes\n // The copy check can take words out of the footer: no heading or column\n // is left with nothing under it (AGL-3735), and none may remain.\n aiLayoutRepairFrameHollows(nodes as unknown as Record<string, unknown>)\n const hollow = aiLayoutFrameHollows(nodes as unknown as Record<string, unknown>)\n const report = validateAiDoctrineTree(\n { rootId: stored.rootId, nodes },\n 'layout',\n context,\n )\n const violations = [\n ...report.violations,\n ...(aiLayoutFrameIsHollow(hollow)\n ? [\n {\n rule: null,\n code: 'layout-frame-hollow',\n message: 'Every footer heading needs something under it, and every footer column more than a heading.',\n detail: aiLayoutFrameHollowsSaid(hollow).join('; '),\n },\n ]\n : []),\n ...copy.violations,\n ...input.extend({\n rootId: stored.rootId,\n nodes,\n repairs: [],\n sourceIds: {},\n score: report.score as AiValidatedTree['score'],\n load: report.load,\n }),\n ]\n return {\n value: violations.length\n ? null\n : { rootId: stored.rootId, nodes, load: report.load, dropped },\n violations,\n }\n}\n\n/** What a frame's links resolve against: the site's pages and its form, as a page's do. */\nexport function aiLayoutFrameTargets(\n job: Pick<AiJob, 'brief' | 'inputs'>,\n inventory: AiSiteInventory | null,\n): AiLayoutTargets {\n return aiLayoutPageTargets({ job, inventory, own: [] })\n}\n"],"names":["isHostImageToken","resolveHostToken","aiLayoutDesignChoices","aiCompileLayoutFrame","aiLayoutFrameSourceOf","aiLayoutFrameSourcePageIds","aiLayoutFrameHollows","aiLayoutFrameHollowsSaid","aiLayoutFrameIsHollow","aiLayoutRepairFrameHollows","AI_LAYOUT_LANGUAGE_TEXT","aiReadLayoutFrame","aiLayoutCopyCheck","aiLayoutStoredTree","AI_GENERATION_MAX_ATTEMPTS","aiLayoutSpeaksOtherThanEnglish","aiHomeScreenIds","AI_STEP_TIERS","aiSettleMechanicalRules","aiSettleUnrelatedScreenLinks","validateAiDoctrineTree","aiSiteKindDesignLines","aiJobStepBudget","fenceUntrustedText","UNTRUSTED_TEXT_RULE","aiJobBriefLine","AI_LAYOUT_SITE_PAGES_MAX","aiLayoutIsHomeSlug","aiLayoutSitePages","AI_LAYOUT_FRAME_THINKING_TOKENS","aiLayoutPageTargets","AI_SITE_NAME_TOKEN","AI_JOB_LAYOUT_LANGUAGE_TOKENS","AI_JOB_LAYOUT_LANGUAGE_BUDGET","tier","maxTokens","AI_LAYOUT_FRAME_KIND","AI_JOB_LAYOUT_LANGUAGE_INSTRUCTIONS","text","join","cacheBreakpoint","AI_LAYOUT_SITE_BRAND_INPUT","AI_LAYOUT_SITE_FACTS_INPUT","AI_LAYOUT_SITE_FRAME_INPUT","aiLayoutSiteFrameOf","inputs","AI_LAYOUT_SITE_FACTS_MAX_CHARS","aiLayoutSiteBrandOf","raw","value","logo","src","trim","alt","replace","slice","aspect","Number","isFinite","Math","min","name","footer","aiLayoutHostBrandOf","host","logoDarkUrl","logoDark","aiLayoutFrameBrandOf","brought","aiLayoutSiteFactsOf","lines","Array","isArray","filter","line","description","length","url","aiLayoutSiteFactsText","facts","Boolean","aiLayoutSiteFactsLines","maxChars","aiJobLayoutLanguageInstructions","job","aiLayoutSiteName","given","aiLayoutNavPages","inventory","planned","own","screens","row","template","map","id","label","slug","siteHome","some","page","pages","home","find","plan","language","aiLayoutHomeId","aiLayoutFramePrompt","input","targets","siteName","forms","formPageId","aiLayoutShopPageId","$id","products","listings","listing","kind","placements","placement","role","screenId","aiLayoutFrameCheck","answers","answer","aiLayoutFrameBuild","aiLayoutSourceFrameBuild","band","source","header","align","blocks","frame","last","headerAlign","compiled","homeId","navPages","closesDark","design","coverClose","cart","shopId","storeLinks","brand","sourcePages","logoTokens","context","screenIds","Set","formIds","form","homeScreenIds","homeIds","homeLabels","includes","formScreenIds","codeBuilt","bindingTokens","ownWords","reusableComponents","stored","tree","ok","console","error","violations","rule","code","message","detail","copy","nodes","rootId","ids","dropped","undefined","hollow","report","extend","repairs","sourceIds","score","load","aiLayoutFrameTargets"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,gBAAgB,QAA8B,qCAAoC;AAE7G,SAASC,qBAAqB,QAA6B,yCAAqC;AAChG,SAASC,oBAAoB,QAAiC,wCAAoC;AAClG,SAASC,qBAAqB,EAAEC,0BAA0B,QAAkC,+CAA2C;AACvI,SACEC,oBAAoB,EACpBC,wBAAwB,EACxBC,qBAAqB,EACrBC,0BAA0B,QACrB,gDAA4C;AACnD,SAEEC,uBAAuB,EACvBC,iBAAiB,QAEZ,2CAAuC;AAK9C,SAASC,iBAAiB,QAAQ,uCAAmC;AACrE,SAASC,kBAAkB,QAAQ,wCAAoC;AACvE,SAASC,0BAA0B,QAAQ,qCAAiC;AAE5E,SAASC,8BAA8B,QAAQ,yCAAqC;AACpF,SACEC,eAAe,QAEV,gCAA4B;AACnC,SAASC,aAAa,QAAQ,0BAAsB;AAEpD,SACEC,uBAAuB,EACvBC,4BAA4B,EAC5BC,sBAAsB,QAGjB,uCAAmC;AAE1C,SAASC,qBAAqB,QAAQ,4BAAwB;AAG9D,SAASC,eAAe,QAAQ,qBAAiB;AACjD,SAASC,kBAAkB,EAAEC,mBAAmB,QAAQ,0CAAyC;AACjG,SAASC,cAAc,QAAQ,yBAAqB;AACpD,SACEC,wBAAwB,EACxBC,kBAAkB,EAClBC,iBAAiB,QACZ,gCAA4B;AACnC,SACEC,+BAA+B,EA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|
-
var _ref, _input_motion;
|
|
930
|
+
var _compiled_videoIds, _ref, _input_motion;
|
|
931
931
|
const compiled = aiCompileImportedPage(_extends({
|
|
932
932
|
doc: input.doc,
|
|
933
933
|
sectionIds: input.sectionIds,
|
|
@@ -938,7 +938,11 @@ export const AI_JOB_PAGE_LANGUAGE_BUDGET = aiJobStepBudget({
|
|
|
938
938
|
}, input.language ? {
|
|
939
939
|
language: input.language
|
|
940
940
|
} : {}));
|
|
941
|
-
|
|
941
|
+
// A film's Video element keeps its id, as a section's root does: the button that plays it names it (AGL-4140).
|
|
942
|
+
const stored = aiLayoutStoredTree(compiled.tree, 'screen', context, [
|
|
943
|
+
...input.sectionIds,
|
|
944
|
+
...(_compiled_videoIds = compiled.videoIds) != null ? _compiled_videoIds : []
|
|
945
|
+
]);
|
|
942
946
|
if (stored.ok === false) {
|
|
943
947
|
console.error('ai imported page: a compiled page did not store', {
|
|
944
948
|
error: stored.error
|