@aglyn/plugins-ai 1.0.0-beta.271 → 1.0.0-beta.273

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/package.json +17 -17
  2. package/src/lib/activity/ai-activity-actions.d.ts +4 -3
  3. package/src/lib/activity/ai-activity-actions.js +3 -0
  4. package/src/lib/activity/ai-activity-actions.js.map +1 -1
  5. package/src/lib/components/ai-site-build-page.component.js +18 -0
  6. package/src/lib/components/ai-site-build-page.component.js.map +1 -1
  7. package/src/lib/components/ai-site-import-job.component.d.ts +41 -0
  8. package/src/lib/components/ai-site-import-job.component.js +707 -0
  9. package/src/lib/components/ai-site-import-job.component.js.map +1 -0
  10. package/src/lib/components/ai-site-import-start.component.d.ts +64 -0
  11. package/src/lib/components/ai-site-import-start.component.js +335 -0
  12. package/src/lib/components/ai-site-import-start.component.js.map +1 -0
  13. package/src/lib/components/ai-site-ownership-proof.component.d.ts +42 -0
  14. package/src/lib/components/ai-site-ownership-proof.component.js +353 -0
  15. package/src/lib/components/ai-site-ownership-proof.component.js.map +1 -0
  16. package/src/lib/components/ai-site-start-card.component.js +329 -252
  17. package/src/lib/components/ai-site-start-card.component.js.map +1 -1
  18. package/src/lib/jobs/ai-empty-site-sweep.d.ts +12 -1
  19. package/src/lib/jobs/ai-empty-site-sweep.js +15 -3
  20. package/src/lib/jobs/ai-empty-site-sweep.js.map +1 -1
  21. package/src/lib/jobs/ai-job-drafts.d.ts +14 -0
  22. package/src/lib/jobs/ai-job-drafts.js +24 -0
  23. package/src/lib/jobs/ai-job-drafts.js.map +1 -1
  24. package/src/lib/jobs/ai-job-import-step.d.ts +136 -0
  25. package/src/lib/jobs/ai-job-import-step.js +809 -0
  26. package/src/lib/jobs/ai-job-import-step.js.map +1 -0
  27. package/src/lib/jobs/ai-job-page-language.d.ts +39 -1
  28. package/src/lib/jobs/ai-job-page-language.js +62 -4
  29. package/src/lib/jobs/ai-job-page-language.js.map +1 -1
  30. package/src/lib/jobs/ai-job-page-step.d.ts +2 -2
  31. package/src/lib/jobs/ai-job-page-step.js +26 -4
  32. package/src/lib/jobs/ai-job-page-step.js.map +1 -1
  33. package/src/lib/jobs/ai-job-seo-step.js +8 -4
  34. package/src/lib/jobs/ai-job-seo-step.js.map +1 -1
  35. package/src/lib/jobs/ai-job-site-datasets.d.ts +39 -1
  36. package/src/lib/jobs/ai-job-site-datasets.js +111 -15
  37. package/src/lib/jobs/ai-job-site-datasets.js.map +1 -1
  38. package/src/lib/jobs/ai-job-site-step.d.ts +12 -3
  39. package/src/lib/jobs/ai-job-site-step.js +85 -11
  40. package/src/lib/jobs/ai-job-site-step.js.map +1 -1
  41. package/src/lib/jobs/ai-job-text-step.d.ts +15 -0
  42. package/src/lib/jobs/ai-job-text-step.js.map +1 -1
  43. package/src/lib/jobs/ai-jobs.d.ts +8 -0
  44. package/src/lib/jobs/ai-jobs.js +19 -3
  45. package/src/lib/jobs/ai-jobs.js.map +1 -1
  46. package/src/lib/jobs/ai-layout-owner-photos.d.ts +16 -1
  47. package/src/lib/jobs/ai-layout-owner-photos.js +49 -2
  48. package/src/lib/jobs/ai-layout-owner-photos.js.map +1 -1
  49. package/src/lib/jobs/ai-layout-stock-photos.d.ts +35 -0
  50. package/src/lib/jobs/ai-layout-stock-photos.js +114 -43
  51. package/src/lib/jobs/ai-layout-stock-photos.js.map +1 -1
  52. package/src/lib/jobs/ai-site-late-photos.d.ts +143 -0
  53. package/src/lib/jobs/ai-site-late-photos.js +486 -0
  54. package/src/lib/jobs/ai-site-late-photos.js.map +1 -0
  55. package/src/lib/jobs/ai-site-publish.d.ts +18 -0
  56. package/src/lib/jobs/ai-site-publish.js +123 -5
  57. package/src/lib/jobs/ai-site-publish.js.map +1 -1
  58. package/src/lib/jobs/ai-theme-brand-inputs.d.ts +61 -3
  59. package/src/lib/jobs/ai-theme-brand-inputs.js +117 -27
  60. package/src/lib/jobs/ai-theme-brand-inputs.js.map +1 -1
  61. package/src/lib/jobs/fixtures/ai-site-late-photos-laurel-fork.d.ts +83 -0
  62. package/src/lib/jobs/fixtures/ai-site-late-photos-laurel-fork.js +1553 -0
  63. package/src/lib/jobs/fixtures/ai-site-late-photos-laurel-fork.js.map +1 -0
  64. package/src/lib/layout-language/ai-layout-pictures.d.ts +50 -13
  65. package/src/lib/layout-language/ai-layout-pictures.js +81 -19
  66. package/src/lib/layout-language/ai-layout-pictures.js.map +1 -1
  67. package/src/lib/model/ai-credit-estimate.d.ts +20 -0
  68. package/src/lib/model/ai-credit-estimate.js +13 -0
  69. package/src/lib/model/ai-credit-estimate.js.map +1 -1
  70. package/src/lib/model/ai-job-activity.d.ts +2 -2
  71. package/src/lib/model/ai-job-activity.js +6 -4
  72. package/src/lib/model/ai-job-activity.js.map +1 -1
  73. package/src/lib/model/ai-job-notice.js +18 -4
  74. package/src/lib/model/ai-job-notice.js.map +1 -1
  75. package/src/lib/model/ai-jobs.types.d.ts +39 -2
  76. package/src/lib/model/ai-jobs.types.js +2 -1
  77. package/src/lib/model/ai-jobs.types.js.map +1 -1
  78. package/src/lib/model/ai-site-import-view.d.ts +130 -0
  79. package/src/lib/model/ai-site-import-view.js +182 -0
  80. package/src/lib/model/ai-site-import-view.js.map +1 -0
  81. package/src/lib/model/ai-site-import.d.ts +302 -0
  82. package/src/lib/model/ai-site-import.js +526 -0
  83. package/src/lib/model/ai-site-import.js.map +1 -0
  84. package/src/lib/model/ai-site-photos.d.ts +119 -0
  85. package/src/lib/model/ai-site-photos.js +128 -0
  86. package/src/lib/model/ai-site-photos.js.map +1 -0
  87. package/src/lib/model/ai-site-start.d.ts +22 -9
  88. package/src/lib/model/ai-site-start.js +64 -23
  89. package/src/lib/model/ai-site-start.js.map +1 -1
  90. package/src/lib/runtime/ai-doctrine-validators.d.ts +3 -1
  91. package/src/lib/runtime/ai-doctrine-validators.js +3 -1
  92. package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
  93. package/src/lib/runtime/seo-fields.d.ts +29 -4
  94. package/src/lib/runtime/seo-fields.js +58 -11
  95. package/src/lib/runtime/seo-fields.js.map +1 -1
  96. package/src/lib/server/ai-jobs-route.js +11 -0
  97. package/src/lib/server/ai-jobs-route.js.map +1 -1
  98. package/src/lib/server/ai-site-import-route.d.ts +89 -0
  99. package/src/lib/server/ai-site-import-route.js +356 -0
  100. package/src/lib/server/ai-site-import-route.js.map +1 -0
  101. package/src/lib/server.js +14 -0
  102. package/src/lib/server.js.map +1 -1
  103. package/src/lib/site-import/fixtures/site-import-crawl-recordings.d.ts +45 -0
  104. package/src/lib/site-import/fixtures/site-import-crawl-recordings.js +313 -0
  105. package/src/lib/site-import/fixtures/site-import-crawl-recordings.js.map +1 -0
  106. package/src/lib/site-import/fixtures/site-import-wave-recordings.d.ts +50 -0
  107. package/src/lib/site-import/fixtures/site-import-wave-recordings.js +217 -0
  108. package/src/lib/site-import/fixtures/site-import-wave-recordings.js.map +1 -0
  109. package/src/lib/site-import/site-import-crawl.d.ts +163 -0
  110. package/src/lib/site-import/site-import-crawl.js +467 -0
  111. package/src/lib/site-import/site-import-crawl.js.map +1 -0
  112. package/src/lib/site-import/site-import-flag.d.ts +23 -0
  113. package/src/lib/site-import/site-import-flag.js +23 -0
  114. package/src/lib/site-import/site-import-flag.js.map +1 -0
  115. package/src/lib/site-import/site-import-html.d.ts +94 -0
  116. package/src/lib/site-import/site-import-html.js +462 -0
  117. package/src/lib/site-import/site-import-html.js.map +1 -0
  118. package/src/lib/site-import/site-import-images.d.ts +54 -0
  119. package/src/lib/site-import/site-import-images.js +204 -0
  120. package/src/lib/site-import/site-import-images.js.map +1 -0
  121. package/src/lib/site-import/site-import-page.d.ts +48 -0
  122. package/src/lib/site-import/site-import-page.js +150 -0
  123. package/src/lib/site-import/site-import-page.js.map +1 -0
  124. package/src/lib/site-import/site-import-review.d.ts +40 -0
  125. package/src/lib/site-import/site-import-review.js +149 -0
  126. package/src/lib/site-import/site-import-review.js.map +1 -0
  127. package/src/lib/site-import/site-import-robots.d.ts +52 -0
  128. package/src/lib/site-import/site-import-robots.js +126 -0
  129. package/src/lib/site-import/site-import-robots.js.map +1 -0
  130. package/src/lib/tools/ai-seo-tool.d.ts +25 -1
  131. package/src/lib/tools/ai-seo-tool.js +61 -0
  132. package/src/lib/tools/ai-seo-tool.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-page-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 { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type { NodesMap } from '@aglyn/aglyn/types/nodes'\nimport { isAiPlanNewRef, type AiBuildPlanScreen } from '../model/ai-build-plan'\nimport type { AiJob, AiJobPlan } from '../model/ai-jobs.types'\nimport {\n aiHomeScreenIds,\n type AiSiteInventory,\n} from '../model/ai-site-inventory'\nimport { AI_LAYOUT_POST_ADDRESS_TOKENS, aiCompileLayoutPage } from '../layout-language/ai-layout-compiler'\nimport { aiSiteMotionStyle, aiWithSiteMotion, type AiSiteMotionStyle } from '../layout-language/ai-layout-motion'\nimport { aiLayoutListingAt, aiLayoutListingsOf, aiLayoutRecordHref, type AiLayoutListing } from '../layout-language/ai-layout-listings'\nimport {\n AI_LAYOUT_LANGUAGE_TEXT,\n AI_LAYOUT_PAGE_TOOL,\n aiReadLayoutPage,\n type AiLayoutSection,\n type AiLayoutSettlement,\n} from '../layout-language/ai-layout-language'\nimport type {\n AiLayoutPage,\n AiLayoutTargets,\n} from '../layout-language/ai-layout-links'\nimport { aiLayoutCopyCheck, aiLayoutWithoutSections } from '../layout-language/ai-layout-gaps'\nimport { aiLayoutPromisedCopyViolations, aiLayoutPromisedSections } from '../layout-language/ai-layout-promised-copy'\nimport { aiLayoutStoredTree } from '../layout-language/ai-layout-store'\nimport { AI_GENERATION_MAX_ATTEMPTS } from '../runtime/ai-generation-bounds'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { aiCacheWriteHourSum } from '../providers/cache-write-hour'\nimport {\n runValidatedGeneration,\n type AiGenerationCheck,\n type AiGenerationSpend,\n type AiValidatedGeneration,\n} from '../runtime/ai-doctrine'\nimport type { AiUsage } from '../providers/contract'\nimport {\n aiSettleMechanicalRules,\n aiSettleUnrelatedScreenLinks,\n validateAiDoctrineTree,\n type AiDoctrineNode,\n type AiDoctrineTreeContext,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { aiSiteKindDesignLines, aiSiteKindOfInputs } from '../model/ai-site-kinds'\nimport { aiSiteSeed } from '../model/ai-site-look'\nimport type { AiLayoutDesign } from '../layout-language/ai-layout-design'\nimport { aiOriginJobId } from './ai-job-draft-ids'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { aiGenerationWorstCaseOnTierMs, aiJobStepBudget } from './ai-job-budget'\nimport { aiJobBriefLine, aiPlanReferenceLines } from './ai-job-generation'\nimport { aiLayoutIsHomeSlug, aiLayoutSiteAliases, aiLayoutSitePages } from './ai-job-layout-site-pages'\nimport { aiLayoutInventedContactViolations } from './ai-layout-site-facts'\nimport { aiSiteContactOf } from '../model/ai-site-details'\n\n/**\n * A page built in the compact layout language (AGL-3660): the page step's\n * pass for a site's page units — a guided start's and a build's — in place of\n * the raw-tree section passes.\n *\n * ONE answer a page: every planned section, in the language, through\n * `submit_page`. The compiler writes the tree, the palette validator stores\n * it as it stores any generated tree, and the doctrine checks the whole page.\n * A section the answer left out or left empty is the one thing a re-ask asks\n * for: the sections that read are kept, and the second answer fills only\n * what is still missing. Then the page step's last pass runs as it always\n * has — the whole page held to the doctrine again, its listing written, the\n * draft reported — so the item ledger, the credits and Try again work exactly\n * as they did.\n */\n\n/** The unit input that says a page or a layout is built in the layout language. */\nexport const AI_LAYOUT_LANGUAGE_INPUT = 'layoutLanguage'\n\n/** The unit input naming the page of the site that places its form, where it is another page. */\nexport const AI_LAYOUT_FORM_PAGE_INPUT = 'layoutFormPage'\n\n/**\n * The unit input carrying the motion of the site a build adds to (AGL-3949):\n * its stored look's kind, seed and motion style (`aiLayoutSiteMotionOf`).\n */\nexport const AI_LAYOUT_SITE_MOTION_INPUT = 'siteMotion'\n\n/** The site a page's entrance motion is drawn for: its kind, seed and, where its look chose one, motion style. */\nexport interface AiLayoutSiteMotion {\n kind?: string\n seed: number\n motion?: AiSiteMotionStyle\n}\n\n/**\n * The motion a site's stored look names (`hosts/{id}.siteStyle`, or the\n * `AI_LAYOUT_SITE_MOTION_INPUT` read from it), read defensively: `null` for a\n * site whose look stored no seed, which a build then draws from its own job.\n */\nexport function aiLayoutSiteMotionOf(value: unknown): AiLayoutSiteMotion | null {\n if (!value || typeof value !== 'object') return null\n const style = value as Record<string, unknown>\n const seed = style['seed']\n if (typeof seed !== 'number' || !Number.isFinite(seed)) return null\n const kind = typeof style['kind'] === 'string' && style['kind'] ? style['kind'] : null\n const motion = aiSiteMotionStyle(style['motion'])\n return { ...(kind ? { kind } : {}), seed: seed >>> 0, ...(motion ? { motion } : {}) }\n}\n\n/** Whether this job builds its page or its layout in the layout language. */\nexport function aiJobUsesLayoutLanguage(job: Pick<AiJob, 'inputs'>): boolean {\n return job.inputs?.[AI_LAYOUT_LANGUAGE_INPUT] === true\n}\n\n/**\n * How the language doors think (AGL-3660): adaptively, at an effort named\n * rather than left to the model's default — a page and a site's frame are\n * designed, not transcribed.\n *\n * Low since AGL-3781. The live round of 2026-10-14 built the layout-language\n * briefs (`ai-job-layout-language-live.spec.ts`) at medium and at low: low\n * built 39 of 39 pages and 13 of 13 frames, 64 of 65 answers held their rules\n * on the first ask, and none was cut off at its ceiling. The ceilings keep\n * the thinking room sized at medium (`AI_LAYOUT_PAGE_THINKING_TOKENS`,\n * `AI_LAYOUT_FRAME_THINKING_TOKENS`), so a page that thinks longer still fits.\n */\nexport const AI_LAYOUT_LANGUAGE_THINKING = { thinking: 'adaptive', effort: 'low' } as const\n\n/**\n * Room for the thinking a page's answer does before it writes, inside the\n * same `max_tokens` as the answer: thinking is drawn from the ceiling first,\n * so a ceiling sized for the answer alone would cut a thoughtful answer off.\n *\n * Bounded by TIME, not by money: the page step's answer, its re-ask and the\n * follow-up must fit the least time a beat gives a step\n * (`AI_JOB_STEP_MAX_MINIMUM_MS`), and `aiJobStepBudget` quietly lowers every\n * ceiling to what fits. 2,000 here, with the follow-up's 500, is the most\n * that fits whole on the balanced tier; at 5,000 the budget cut a page's\n * ceiling to 879 tokens, under the answer itself.\n */\nexport const AI_LAYOUT_PAGE_THINKING_TOKENS = 2_000\n\n/** The same room for a site's header and footer, whose step has the time for more. */\nexport const AI_LAYOUT_FRAME_THINKING_TOKENS = 4_000\n\n/**\n * The most one page's answer asks for: the answer and the thinking before it.\n * A section in the language is about 120 to 250 tokens with its copy, so the\n * largest page a plan admits — eight sections — fits in 3,000 with room (the\n * live runs of 2026-10-07 wrote 683 to 1,745); the compiler, not the ceiling,\n * keeps a page small.\n */\nexport const AI_JOB_PAGE_LANGUAGE_TOKENS = 3_000 + AI_LAYOUT_PAGE_THINKING_TOKENS\n\n/**\n * The most one section of a page is written in, its copy included: the top of\n * the 120 to 250 tokens a section runs to. The Free site wall prices each\n * planned section at it (AGL-3660).\n */\nexport const AI_LAYOUT_SECTION_MOST_TOKENS = 250\n\n/**\n * The time a language page pass needs: its lookup rounds, its answer and its\n * re-ask at `AI_JOB_PAGE_LANGUAGE_TOKENS` on the tier the page step is served\n * from, with the step's reads and writes.\n */\n/** The most the follow-up asking only for the sections an answer left out may run to, its thinking included. */\nexport const AI_JOB_PAGE_LANGUAGE_FOLLOW_UP_TOKENS = 1_500 + 500\n\nexport const AI_JOB_PAGE_LANGUAGE_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.page'],\n maxTokens: AI_JOB_PAGE_LANGUAGE_TOKENS,\n // The follow-up for sections an answer left out is one more generation.\n ownReadsMs: aiGenerationWorstCaseOnTierMs({\n tier: AI_STEP_TIERS['job.page'],\n maxTokens: AI_JOB_PAGE_LANGUAGE_FOLLOW_UP_TOKENS,\n }),\n})\n\n/** The doctrine scope the language doors are told: values the compiler checks itself. */\nexport const AI_LAYOUT_PAGE_KIND = 'layout-page'\n\n/** The language, as the page door's cached instructions. */\nexport const AI_JOB_PAGE_LANGUAGE_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n AI_LAYOUT_LANGUAGE_TEXT,\n '',\n 'Answer with submit_page: the whole page, one entry in sections for each planned section, in order.',\n ].join('\\n'),\n cacheBreakpoint: true,\n },\n]\n\n/**\n * The page of a site plan that places its form: the form the plan creates, or\n * one the site has. Home only when no other page places it (AGL-3805).\n *\n * Every call to action that asks a visitor to get in touch goes here — the\n * header's button on every page, the footer's, a page's own — so a page whose\n * purpose is the form outranks the home page that closes on a copy of it. A\n * plan lists Home first, and a home page that ends \"visit us or order\" places\n * the form too: the first page placing it was Home, and a Spanish bakery's\n * header \"Pide tu pastel\" and footer \"Contáctanos\" (beta.253, job eg4maZMGtN)\n * linked the home page on every page, itself included, while /pasteles and\n * /visitanos held the form. Eight of the 21 newest AI-built sites linked their\n * header's call to action home the same way, six of them with such a page.\n */\nexport function aiLayoutFormPageOfPlan(\n plan: Pick<AiJobPlan, 'create' | 'screens'>,\n formIds: readonly string[] = [],\n): string | null {\n const created = new Set(\n plan.create\n .filter((entry) => entry.kind === 'form')\n .map((entry) => `new:${entry.name}`.toLowerCase()),\n )\n const forms = new Set(formIds)\n const placing = plan.screens.filter(\n (entry) =>\n typeof entry.id === 'string' &&\n entry.sections.some((section) =>\n section.uses.some((ref) =>\n isAiPlanNewRef(ref) ? created.has(ref.toLowerCase()) : forms.has(ref),\n ),\n ),\n )\n const screen = placing.find((entry) => !aiLayoutIsHomeSlug(entry.slug)) ?? placing[0]\n return screen?.id ?? null\n}\n\n/** Every word the job was given, which a page's contact details are held to. */\nexport function aiLayoutFacts(job: Pick<AiJob, 'brief' | 'inputs'>): string {\n const values = Object.values(job.inputs ?? {}).filter(\n (value): value is string => typeof value === 'string',\n )\n return [job.brief, ...values].join('\\n')\n}\n\n/** What a page's links resolve against: the site's pages, built and planned, its forms and components. */\nexport function aiLayoutPageTargets(input: {\n job: Pick<AiJob, 'brief' | 'inputs'>\n inventory: AiSiteInventory | null\n own: ReadonlyArray<string | null | undefined>\n}): AiLayoutTargets {\n const { job, inventory } = input\n const own = input.own.filter((id): id is string => !!id)\n const planned = aiLayoutSitePages(job.inputs)\n const pages: AiLayoutPage[] = [\n ...planned,\n // Planned pages merged into the blog (AGL-3676): a link to one goes to the blog.\n ...aiLayoutSiteAliases(job.inputs).filter((alias) => !planned.some((page) => page.id === alias.id)),\n ...(inventory?.screens ?? [])\n .filter(\n (row) => !row.template && !planned.some((page) => page.id === row.id),\n )\n .map((row) => ({ id: row.id, label: row.name, slug: row.slug })),\n ]\n const formPage = job.inputs?.[AI_LAYOUT_FORM_PAGE_INPUT]\n return {\n pageId: own[0] ?? null,\n pages: pages.filter((page) => !own.includes(page.id)),\n homeIds: aiHomeScreenIds(inventory),\n forms: (inventory?.forms ?? []).map((form) => ({\n id: form.id,\n name: form.name,\n })),\n formPageId:\n typeof formPage === 'string' && !own.includes(formPage) ? formPage : null,\n components: (inventory?.components ?? []).map((component) => ({\n id: component.id,\n name: component.name,\n props: component.props,\n })),\n facts: aiLayoutFacts(job),\n // The phone and email the person gave, which links call and write to (AGL-3979).\n contact: aiSiteContactOf(job.inputs),\n // The site's catalog and blog, and the sections that list them (AGL-3676),\n // and its datasets (AGL-3616).\n listings: aiLayoutListingsWithDatasets(aiLayoutListingsOf(job.inputs), inventory),\n }\n}\n\n/**\n * A page's listings with each dataset's held to the site's inventory\n * (AGL-3616): a records listing is kept only where the site has the dataset —\n * the tree check admits a repeat over no other, and a card left repeating\n * over nothing would show its `{{item.*}}` — and one that names no fields\n * takes the inventory's, in the dataset's order. Its cards link the record\n * pages the plan makes, else those the site already serves (AGL-3747).\n */\nexport function aiLayoutListingsWithDatasets(\n listings: readonly AiLayoutListing[],\n inventory: Pick<AiSiteInventory, 'datasets'> | null,\n): AiLayoutListing[] {\n return listings.flatMap((listing) => {\n if (listing.kind !== 'records') return [listing]\n const row = inventory?.datasets.find((dataset) => dataset.id === listing.datasetId)\n if (!row) return []\n // The photo field is the card's picture, never its words (AGL-3616).\n const imageField = listing.imageField ?? row.imageField\n // The address is the card's link to its record's page, never its words (AGL-3727).\n const addressField = listing.addressField ?? row.addressField\n // A record page the site already serves for the dataset (AGL-3747), where\n // the plan makes none of its own.\n const recordBase = listing.recordBase ?? row.recordBase\n const fields = (\n listing.fields?.length\n ? listing.fields\n : row.fields.map((name, index) => ({ id: row.fieldIds?.[index] || name, name, type: 'text' }))\n ).filter((field) => field.id !== imageField && field.id !== addressField)\n return fields.length\n ? [\n {\n ...listing,\n fields,\n ...(imageField ? { imageField } : {}),\n ...(recordBase && addressField ? { recordBase, addressField } : {}),\n },\n ]\n : []\n })\n}\n\n/**\n * The page check's context with what a section listing the blog's posts\n * binds (AGL-3676): each post's card links its post and shows its cover by\n * the tokens the page fills per post, which a page's store admits whole only\n * where a listing places them. A dataset's card shows its record's photo\n * the same way (AGL-3616), by `{{item.<photo field>}}`. And the page that\n * places the site's form, which a call to action asking a visitor to get in\n * touch links even when it is home (AGL-3729).\n */\nexport function aiLayoutListingContext(\n context: AiDoctrineTreeContext,\n targets: AiLayoutTargets,\n): AiDoctrineTreeContext {\n if (targets.formPageId) context = { ...context, formScreenIds: [targets.formPageId] }\n const here = (targets.listings ?? []).filter((listing) =>\n listing.placements.some((placement) => placement.screenId === targets.pageId),\n )\n const tokens = [\n ...(here.some((listing) => listing.kind === 'posts') ? AI_LAYOUT_POST_ADDRESS_TOKENS : []),\n ...here.flatMap((listing) => (listing.kind === 'records' && listing.imageField ? [`{{item.${listing.imageField}}}`] : [])),\n // Each card's link to its record's own page (AGL-3727), admitted whole.\n ...here.flatMap((listing) => {\n const href = aiLayoutRecordHref(listing)\n return href ? [href] : []\n }),\n ]\n if (!tokens.length) return context\n return { ...context, bindingTokens: [...new Set([...(context.bindingTokens ?? []), ...tokens])] }\n}\n\n/** The most of the text of the page a planned page starts from that its prompt shows: about 1,000 tokens (AGL-3832). */\nexport const AI_LAYOUT_START_PAGE_MAX_CHARS = 4_000\n\n/** The site's page a planned page starts from (its plan's `duplicateOf`), by its name and its words. */\nexport interface AiLayoutStartPage {\n label: string\n text: string\n}\n\n/**\n * The page a planned page starts from, as its prompt shows it (AGL-3832): its\n * words, never its tree. A page in the layout language is written whole, so\n * a copy of the page would be replaced by the answer, and what the copy was\n * for — what the site already says there — reaches the page only through\n * the model. Empty when the page has no words to show.\n */\nexport function aiLayoutStartPageLines(start: AiLayoutStartPage | null | undefined): string[] {\n const text = start?.text.trim() ?? ''\n if (!start || !text) return []\n const shown = text.length > AI_LAYOUT_START_PAGE_MAX_CHARS ? `${text.slice(0, AI_LAYOUT_START_PAGE_MAX_CHARS).trimEnd()} …` : text\n return [\n `This page starts from the site's page \"${start.label}\": keep its facts, names and details wherever a section below covers them, and design every section anew. Its text:`,\n shown,\n ]\n}\n\n/**\n * What a page is told about the site's form (AGL-3899). A page whose plan\n * places the form, or a site whose form has no page of its own, is told the\n * form; any other page is told where the form lives and that its call to\n * action links there. Told \"The site's form: …\" on every page, two of the\n * newest production homes drew the form on their own, beside the Contact\n * page that held it.\n */\nexport function aiLayoutFormLine(screen: Pick<AiBuildPlanScreen, 'sections'>, targets: AiLayoutTargets): string {\n if (!targets.forms.length) return 'The site has no saved form: place none.'\n const ids = new Set(targets.forms.map((form) => form.id))\n const placed = screen.sections.some((section) => section.uses.some((ref) => ids.has(ref)))\n const page = targets.formPageId ? targets.pages.find((entry) => entry.id === targets.formPageId) : undefined\n if (placed || !page) return `The site's form: ${targets.forms.map((form) => `${form.name} (${form.id})`).join(', ')}.`\n return `The site's form is on the ${page.label} page (page:${page.id}): place no form on this page, and make a call to action that asks visitors to get in touch a button to that page.`\n}\n\n/** The page's user turn: the page, the brief, the plan, its sections and where its links may go. */\nexport function aiLayoutPagePrompt(input: {\n job: Pick<AiJob, 'brief' | 'inputs' | '$id'>\n plan: AiJobPlan\n screen: AiBuildPlanScreen\n targets: AiLayoutTargets\n reusableComponents: boolean\n /** The site's page the plan starts this page from, read off the site (AGL-3832). */\n startsFrom?: AiLayoutStartPage | null\n /** The sections a re-ask still needs, by plan index; absent on the first ask. */\n missing?: readonly number[]\n}): string {\n const { job, plan, screen, targets } = input\n const sections = screen.sections.map((section, index) => {\n const places = section.uses.length\n ? `; places ${section.uses.join(', ')}`\n : ''\n // A section the site's records fill (AGL-3676): the platform places them,\n // so the design writes the words around them and no group for them.\n const listed = aiLayoutListingAt(targets.listings ?? [], targets.pageId, index)\n if (listed?.listing.kind === 'tracks') {\n // A music site's player (AGL-3716): placed empty, for the owner's own uploads.\n return `${index + 1}. \"${section.name}\"${places}; the platform places a music player here for the artist's own tracks, which they add themselves: write only its heading and a line inviting visitors to listen, and no cards, list, images or links for songs`\n }\n if (listed?.listing.kind === 'events') {\n // The site's own dated events (AGL-3755), listed by the platform with their dates.\n const names = listed.listing.records.length ? ` (${listed.listing.records.map((name) => `\"${name}\"`).join(', ')})` : ''\n return `${index + 1}. \"${section.name}\"${places}; the platform lists the site's upcoming events here${names} with their dates, places and photos: write only its heading and a line inviting visitors to come, and no cards, dates, list or links for events`\n }\n if (listed?.listing.kind === 'reviews') {\n // A store's own reviews (AGL-3676): shoppers write them; none is ever written here.\n return `${index + 1}. \"${section.name}\"${places}; the platform shows the store's real customer reviews here with their star ratings, once shoppers leave them: write only its heading, and no quotes, names, ratings or cards`\n }\n if (listed?.listing.kind === 'signup') {\n // A store's newsletter field (AGL-3676), placed by the platform.\n return `${index + 1}. \"${section.name}\"${places}; the platform places the newsletter sign-up field here: write its heading and one line on what subscribers hear about, from the brief, and no form, button or offer the brief does not make`\n }\n if (listed?.listing.kind === 'records') {\n // One of the site's datasets (AGL-3616), repeated by the platform over its records.\n // A section named for one group lists that group's records alone (AGL-3921).\n const shown = listed.filter?.records.length ? listed.filter.records : listed.listing.records\n const names = shown.length ? ` (${shown.slice(0, 6).map((name) => `“${name}”`).join(', ')})` : ''\n return `${index + 1}. \"${section.name}\"${places}; the platform lists the records of the dataset “${listed.listing.name}”${names} here itself, one card each: write only its heading and a line about them, and no cards, list or images for them`\n }\n if (listed) {\n return `${index + 1}. \"${section.name}\"${places}; the platform lists ${listed.listing.name}'s ${listed.listing.kind} here itself, with their photos and links: write only its heading and a line about them, and no cards, list or images for them`\n }\n const items = section.items ? `; shows ${section.items} items` : ''\n return `${index + 1}. \"${section.name}\"${places}${items}`\n })\n // A page merged into the blog is not offered: the blog is, by its own entry.\n const pages = targets.pages.filter((page) => !page.standsInFor).map((page) => `${page.label} (page:${page.id})`)\n const components = targets.components.map(\n (component) =>\n `${component.name} (${component.id}; props ${Object.keys(component.props).join(', ') || 'none'})`,\n )\n return [\n `Page: \"${screen.title}\" at ${screen.slug}`,\n aiJobBriefLine(job),\n // The kind of site the person picked sets how its pages are arranged (AGL-3660).\n ...aiSiteKindDesignLines(job.inputs),\n ...aiPlanReferenceLines(plan),\n ...aiLayoutStartPageLines(input.startsFrom),\n `Sections to design, in order:`,\n ...sections,\n pages.length\n ? `Other pages of this site: ${pages.join(', ')}.`\n : 'This site has no other page to link.',\n aiLayoutFormLine(screen, targets),\n ...(components.length\n ? [`Components this page may place: ${components.join('; ')}.`]\n : []),\n input.reusableComponents\n ? 'Where a section repeats an item, place the component its plan line names with cards whose to is that component.'\n : 'This site keeps no reusable components: draw repeated items as cards, steps, stats or a list.',\n // A per-job word, so two identical briefs are designed apart.\n `Design seed: ${job.$id.slice(-6)}.`,\n ].join('\\n')\n}\n\n/**\n * The site a page is designed for (AGL-3660): the kind its job names, the\n * seed its look was drawn with — the same for every page of the site, so the\n * site reads as one design — and whether the page is its home. `null` for a\n * job that names no kind of site, which compiles the compiler's first way.\n */\nexport function aiLayoutDesignOf(job: Pick<AiJob, '$id' | 'inputs'>, slug: string): AiLayoutDesign | null {\n const kind = aiSiteKindOfInputs(job.inputs)\n if (!kind) return null\n const style = job.inputs?.['siteStyle'] as Record<string, unknown> | undefined\n const seed = typeof style?.['seed'] === 'number' && Number.isFinite(style['seed']) ? (style['seed'] as number) >>> 0 : aiSiteSeed(aiOriginJobId(job))\n return { kind: kind.id, seed, home: aiLayoutIsHomeSlug(slug) }\n}\n\n/**\n * The site a page's entrance motion is drawn for (AGL-3838): its design where\n * the job names a kind of site, else the job's own seed, which moves in the\n * standard mood — so every page of one site moves alike. The motion style its\n * look chose rides along (AGL-3941); a job whose look chose none — one from\n * before the look did, a replay of one, a job with no look — moves in its\n * kind's mood. A unit a build makes on an existing site carries the site's\n * stored motion instead (`AI_LAYOUT_SITE_MOTION_INPUT`, AGL-3949), so a page\n * added later moves the way the site's own pages do.\n */\nexport function aiLayoutMotionSiteOf(\n job: Pick<AiJob, '$id' | 'inputs'>,\n slug: string,\n): AiLayoutSiteMotion {\n const style = job.inputs?.['siteStyle'] as Record<string, unknown> | undefined\n if (!style) {\n const stored = aiLayoutSiteMotionOf(job.inputs?.[AI_LAYOUT_SITE_MOTION_INPUT])\n if (stored) return stored\n }\n const motion = aiSiteMotionStyle(style?.['motion'])\n const { kind, seed } = aiLayoutDesignOf(job, slug) ?? { seed: aiSiteSeed(aiOriginJobId(job)) }\n return { ...(kind ? { kind } : {}), seed, ...(motion ? { motion } : {}) }\n}\n\n/** A validated language page, stored as the page keeps it. */\nexport interface AiLayoutPageBuilt {\n nodes: NodesMap\n load: AiLoadEstimate | null\n settled: AiLayoutSettlement[]\n /** What the last answer's gaps took out of the page (`ai-layout-gaps.ts`). */\n dropped: string[]\n /** How many repeated items each plan section shows, as built (AGL-3660). */\n items: number[]\n}\n\nexport interface AiLayoutPageCheckInput {\n screen: AiBuildPlanScreen\n sectionIds: readonly string[]\n targets: AiLayoutTargets\n context: AiDoctrineTreeContext\n reusableComponents: boolean\n /**\n * What earlier answers gave, by plan index, shared between the page's\n * generations: a follow-up asking only for missing sections fills the rest.\n */\n kept?: Array<AiLayoutSection | null>\n /** The plan indices this answer's sections fill, in order; absent, every section. */\n only?: readonly number[]\n /** The site the page is drawn for (`aiLayoutDesignOf`); absent, the compiler's first design. */\n design?: AiLayoutDesign | null\n /** The site's language, which the compiler's own words are written in (AGL-3760); absent, English. */\n language?: string\n /** The site the page's entrance motion is drawn for (`aiLayoutMotionSiteOf`); absent, its design. */\n motion?: AiLayoutSiteMotion\n /** Whether copy may promise what is coming (a coming-soon site, AGL-3887); absent, it may not. */\n promisesAllowed?: boolean\n}\n\n/**\n * The follow-up turn for the sections a page's answer left out (AGL-3660):\n * the page as before, told which sections it already has, and asked for only\n * the missing ones, in order — the one part of a page asked for again.\n */\nexport function aiLayoutMissingSectionsPrompt(input: {\n base: string\n screen: AiBuildPlanScreen\n missing: readonly number[]\n}): string {\n const names = input.missing.map((index) => `${index + 1}. \"${input.screen.sections[index].name}\"`)\n return [\n input.base,\n '',\n `The other sections of this page are already designed. Design ONLY these, in this order, one entry in sections each: ${names.join('; ')}. Give each at least one block.`,\n ].join('\\n')\n}\n\n/** The plan indices a page still lacks, after the answers so far. */\nexport function aiLayoutMissingSections(kept: ReadonlyArray<AiLayoutSection | null>): number[] {\n return kept.flatMap((section, index) => (section ? [] : [index]))\n}\n\n/** The violation a planned section the answer gave nothing usable for is named by. */\nexport const AI_LAYOUT_SECTION_MISSING_CODE = 'layout-section-missing'\n\n/** The code a section planned with items that shows none is refused under (AGL-3660). */\nexport const AI_LAYOUT_SECTION_EMPTY_CODE = 'layout-section-no-items'\n\n/** How many of a section's planned items it must show: one for a short list, two for anything longer. */\nconst leastItems = (planned: number) => (planned >= 3 ? 2 : planned >= 1 ? 1 : 0)\n\n/**\n * How many repeated items each section shows once stored (AGL-3660): the\n * elements the compiler drew for them, under the ids they are stored by,\n * that are still in the page after anything later took words out.\n */\nexport function aiLayoutShownItems(\n itemIds: readonly (readonly string[])[],\n storedIds: Readonly<Record<string, string>>,\n nodes: Readonly<Record<string, unknown>>,\n): number[] {\n return itemIds.map((ids) => ids.filter((id) => storedIds[id] !== undefined && storedIds[id] in nodes).length)\n}\n\n/** The plan indices of the sections that show fewer of their planned items than they must (AGL-3660). */\nexport function aiLayoutShortItemSections(\n screen: Pick<AiBuildPlanScreen, 'sections'>,\n items: readonly number[],\n quotesOnly: readonly number[] = [],\n): number[] {\n return screen.sections.flatMap((section, index) => {\n if (quotesOnly.includes(index)) return []\n const least = leastItems(section.items)\n return least && (items[index] ?? 0) < least ? [index] : []\n })\n}\n\n/**\n * What a page built in the layout language says about the planned sections\n * it was published without (AGL-3771): each one the last answer could not\n * fill, or left with only its heading once its gaps were taken out, rather\n * than the page refused. `null` when every section is shown.\n */\nexport function aiLayoutLeftOutNote(\n screen: Pick<AiBuildPlanScreen, 'sections'>,\n sectionIds: readonly string[],\n nodes: Readonly<Record<string, unknown>>,\n): string | null {\n const names = screen.sections.flatMap((section, index) =>\n index > 0 && sectionIds[index] && !(sectionIds[index] in nodes) ? [`“${section.name}”`] : [],\n )\n if (!names.length) return null\n return names.length === 1\n ? `Left out: the section ${names[0]}, which could not be built well enough to publish. Add it in the Besigner when you are ready.`\n : `Left out: the sections ${names.join(', ')}, which could not be built well enough to publish. Add them in the Besigner when you are ready.`\n}\n\n/**\n * The sections a page planned with repeated items — cards, steps, a list —\n * that show none, or too few, once the page is built (AGL-3660). A heading\n * and an intro over nothing is a section a visitor reads as broken, so it is\n * asked for again.\n */\nexport function aiLayoutEmptyItemSections(\n screen: Pick<AiBuildPlanScreen, 'sections'>,\n items: readonly number[],\n /** Sections whose only items were customer quotes, which no answer may give (AGL-3676). */\n quotesOnly: readonly number[] = [],\n /** Sections the page no longer shows (AGL-3771), which ask for nothing. */\n emptied: readonly number[] = [],\n): AiDoctrineViolation[] {\n const short = aiLayoutShortItemSections(screen, items, quotesOnly)\n return screen.sections.flatMap((section, index): AiDoctrineViolation[] => {\n if (!short.includes(index) || emptied.includes(index)) return []\n const shown = items[index] ?? 0\n return [\n {\n rule: null,\n code: AI_LAYOUT_SECTION_EMPTY_CODE,\n message: `Section ${index + 1} (\"${section.name}\") is planned with ${section.items} items and shows ${shown || 'none'}.`,\n detail: `Give section ${index + 1} one cards, steps, stats, list or faq block holding its ${section.items} items, each with a title and its words.`,\n },\n ]\n })\n}\n\n/**\n * Rule 1's repeats said as the layout language fixes them (AGL-3988). Its\n * own words ask for \"one reusable component with props\", which a page\n * answer cannot make: the beta.270 Sugar Hollow Galleries page was re-asked\n * with them and node ids it never wrote, broke the rule the same way, and\n * was refused. Each repeat now names the sections it sits in and how the\n * language says like blocks once: one group, an item each.\n */\nexport function aiLayoutRepeatsSaidInTheLanguage(\n violations: readonly AiDoctrineViolation[],\n nodes: Readonly<Record<string, { nodes?: string[] }>>,\n sectionIds: readonly string[],\n sections: ReadonlyArray<{ name: string }>,\n): AiDoctrineViolation[] {\n const parentOf = new Map<string, string>()\n for (const [id, node] of Object.entries(nodes)) for (const child of node?.nodes ?? []) parentOf.set(child, id)\n const sectionOf = (id: string): number => {\n for (let at: string | undefined = id; at !== undefined; at = parentOf.get(at)) {\n const index = sectionIds.indexOf(at)\n if (index >= 0) return index\n }\n return -1\n }\n return violations.map((violation) => {\n if (violation.code !== 'repeated-subtree') return violation\n const where = [...new Set((violation.nodeIds ?? []).map(sectionOf).filter((index) => index >= 0))]\n .sort((a, b) => a - b)\n .map((index) => `section ${index + 1} (\"${sections[index]?.name ?? ''}\")`)\n return {\n ...violation,\n detail: `${where.length ? `In ${where.join(' and ')}: ` : ''}write like blocks once, as one cards, steps or list block with an item for each (its title, its words and where it goes), never the same blocks repeated in several columns or groups.`,\n }\n })\n}\n\n/**\n * The check a language page answer is held to: each planned section read,\n * the page compiled, stored and checked whole. Sections that read are kept\n * across the re-ask, so the second answer is asked only for what was missing,\n * and a section it sends again that already read is not taken twice.\n */\nexport function aiLayoutPageCheck(\n input: AiLayoutPageCheckInput,\n): AiGenerationCheck<AiLayoutPageBuilt> {\n const kept: Array<AiLayoutSection | null> = input.kept ?? input.screen.sections.map(() => null)\n const fills = input.only ?? input.screen.sections.map((_, index) => index)\n const context = aiLayoutListingContext(input.context, input.targets)\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 const last = answers >= AI_GENERATION_MAX_ATTEMPTS\n const reading = aiReadLayoutPage(\n answer,\n fills.length,\n fills.map((index) => input.screen.sections[index]),\n )\n reading.sections.forEach((section, position) => {\n // A section the answer gives is taken as given; one it leaves out keeps\n // what an earlier answer gave, so a re-ask may send only what was missing.\n if (section) kept[fills[position]] = section\n })\n const missing = kept.flatMap((section, index) => (section ? [] : [index]))\n if (missing.length) {\n const names = missing.map(\n (index) => `${index + 1} (\"${input.screen.sections[index].name}\")`,\n )\n return {\n value: null,\n violations: [\n {\n rule: null,\n code: AI_LAYOUT_SECTION_MISSING_CODE,\n message: `The page left out section ${names.join(', ')}.`,\n detail: `Answer again with every section in order; the sections you already designed are kept, so only ${names.join(', ')} ${missing.length === 1 ? 'needs' : 'need'} its design. Give each at least one block.`,\n },\n ],\n }\n }\n const compiled = aiCompileLayoutPage(\n kept as AiLayoutSection[],\n { title: input.screen.title, sections: input.screen.sections },\n input.targets,\n {\n reusableComponents: input.reusableComponents,\n sectionIds: input.sectionIds,\n ...(input.design ? { design: input.design } : {}),\n ...(input.language ? { language: input.language } : {}),\n },\n )\n const stored = aiLayoutStoredTree(\n compiled.tree,\n 'screen',\n context,\n input.sectionIds,\n )\n if (stored.ok === false) {\n // The compiler writes only palette trees, which the property spec holds;\n // a refusal here is the platform's, and is reported as one.\n console.error('ai layout page: a compiled page 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 page 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 page that is published as built.\n const copy = aiLayoutCopyCheck(\n stored.nodes,\n CANVAS_ROOT_ELEMENT_ID,\n {\n pages: input.targets.pages,\n ids: [\n ...input.targets.pages.map((page) => page.id),\n ...input.targets.forms.map((form) => form.id),\n ...input.targets.components.map((component) => component.id),\n ...input.sectionIds,\n ...(input.targets.pageId ? [input.targets.pageId] : []),\n ],\n },\n last,\n )\n const dropped = [...copy.dropped]\n // An attribute a rule has one answer for is settled, not asked of the model again (AGL-3660),\n // and a link sent home for nothing is sent to the form or left out (AGL-3729).\n let nodes = aiSettleUnrelatedScreenLinks(\n aiSettleMechanicalRules(\n { rootId: CANVAS_ROOT_ELEMENT_ID, nodes: copy.nodes as unknown as Record<string, AiDoctrineNode> },\n 'page',\n ),\n 'page',\n { ...context, ownScreenIds: input.targets.pageId ? [input.targets.pageId] : [] },\n ).nodes as unknown as typeof copy.nodes\n // Each section's items as they are stored, after anything the gaps took out.\n const items = aiLayoutShownItems(compiled.itemIds, stored.storedIds, nodes as unknown as Record<string, unknown>)\n // The last answer's sections that still show none of their planned items\n // are taken out rather than the whole page refused (AGL-3771): a site\n // start's home refused for one such section published a site with\n // nothing at its address. The page's first section heads it, and is\n // never taken out.\n const emptied = last\n ? aiLayoutShortItemSections(input.screen, items, compiled.quotesOnly).filter((index) => index > 0 && !!input.sectionIds[index])\n : []\n if (emptied.length) {\n const without = aiLayoutWithoutSections(\n nodes,\n CANVAS_ROOT_ELEMENT_ID,\n emptied.map((index) => ({\n id: input.sectionIds[index],\n name: input.screen.sections[index].name,\n why: `planned with ${input.screen.sections[index].items} items and showing ${items[index] || 'none'}`,\n })),\n )\n nodes = without.nodes as typeof nodes\n dropped.push(...without.dropped)\n }\n // A section that promises its content later — \"We are building this\n // space\" — is asked for again, and the last answer's is taken out, the\n // page's first section aside (AGL-3887). A coming-soon site's is its point.\n const promised = input.promisesAllowed ? [] : aiLayoutPromisedSections(nodes, input.sectionIds)\n const promisedOut = last ? promised.filter(({ index }) => index > 0) : []\n if (promisedOut.length) {\n const without = aiLayoutWithoutSections(\n nodes,\n CANVAS_ROOT_ELEMENT_ID,\n promisedOut.map(({ index }) => ({\n id: input.sectionIds[index],\n name: input.screen.sections[index].name,\n why: 'which promised content that is not there',\n })),\n )\n nodes = without.nodes as typeof nodes\n dropped.push(...without.dropped)\n }\n const report = validateAiDoctrineTree(\n { rootId: CANVAS_ROOT_ELEMENT_ID, nodes },\n 'page',\n {\n ...context,\n scrollTargetIds: input.sectionIds,\n // The layout language draws its own picture cards (AGL-3660).\n repeatsCompiled: true,\n },\n )\n // A street address or opening hours the job was never given is invented\n // (rule 14, AGL-3596), the same check a layout is held to; a phone number\n // or an email the compiler already writes as its gap.\n const violations: AiDoctrineViolation[] = [\n ...aiLayoutRepeatsSaidInTheLanguage(report.violations, nodes as unknown as Record<string, { nodes?: string[] }>, input.sectionIds, input.screen.sections),\n ...copy.violations,\n ...aiLayoutEmptyItemSections(input.screen, items, compiled.quotesOnly, emptied),\n ...(last ? [] : aiLayoutPromisedCopyViolations(input.screen, promised)),\n ...aiLayoutInventedContactViolations(\n { rootId: CANVAS_ROOT_ELEMENT_ID, nodes: nodes as unknown as Record<string, AiDoctrineNode> },\n input.targets.facts,\n ),\n ]\n return {\n value: violations.length\n ? null\n : {\n // Entrance motion is the site's, decided here in code and never\n // asked of the model (AGL-3838): written once the page has passed,\n // so no check above reads a prop the palette does not list.\n nodes: aiWithSiteMotion(nodes, input.motion ?? input.design ?? { seed: 0 }, { sectionIds: input.sectionIds }),\n load: report.load,\n settled: [...reading.settled, ...compiled.settled],\n dropped,\n items,\n },\n violations,\n }\n }\n}\n\nexport interface AiLayoutPageRunInput {\n job: Pick<AiJob, 'brief' | 'inputs' | '$id'>\n plan: AiJobPlan\n screen: AiBuildPlanScreen\n sectionIds: readonly string[]\n targets: AiLayoutTargets\n context: AiDoctrineTreeContext\n reusableComponents: boolean\n inventory: AiSiteInventory | null\n model: string\n /** The site's page the plan starts this page from (AGL-3832). */\n startsFrom?: AiLayoutStartPage | null\n signal?: AbortSignal\n /** Wraps the check, for an eval that records each answer it reads. */\n observe?: (check: AiGenerationCheck<AiLayoutPageBuilt>) => AiGenerationCheck<AiLayoutPageBuilt>\n}\n\n/** Two generations' spend as one: every call is billed. */\nfunction spentTogether(first: AiGenerationSpend, second: AiGenerationSpend): AiGenerationSpend {\n const usage: AiUsage = {\n inputTokens: first.usage.inputTokens + second.usage.inputTokens,\n outputTokens: first.usage.outputTokens + second.usage.outputTokens,\n cacheReadTokens: first.usage.cacheReadTokens + second.usage.cacheReadTokens,\n cacheWriteTokens: first.usage.cacheWriteTokens + second.usage.cacheWriteTokens,\n ...aiCacheWriteHourSum(first.usage, second.usage),\n }\n return {\n attempts: first.attempts + second.attempts,\n usage,\n estCostUsd: Math.round((first.estCostUsd + second.estCostUsd) * 1_000_000) / 1_000_000,\n model: second.model,\n stopReason: second.stopReason,\n effort: second.effort,\n }\n}\n\n/**\n * A whole page in the layout language: one answer for every section, and,\n * where that answer and its re-ask still left a section out, one follow-up\n * asking for only those (AGL-3660). The sections that read are kept between\n * them, so the page is compiled whole once every section is designed.\n */\nexport async function aiRunLayoutPage(input: AiLayoutPageRunInput): Promise<AiValidatedGeneration<AiLayoutPageBuilt>> {\n const kept: Array<AiLayoutSection | null> = input.screen.sections.map(() => null)\n const observe = input.observe ?? ((check) => check)\n const base = aiLayoutPagePrompt({\n job: input.job,\n plan: input.plan,\n screen: input.screen,\n targets: input.targets,\n reusableComponents: input.reusableComponents,\n startsFrom: input.startsFrom ?? null,\n })\n const ask = (content: string, maxTokens: number, only?: readonly number[]) =>\n runValidatedGeneration<AiLayoutPageBuilt>(AI_LAYOUT_PAGE_KIND, {\n step: 'job.page',\n model: input.model,\n instructions: AI_JOB_PAGE_LANGUAGE_INSTRUCTIONS,\n inventory: input.inventory,\n messages: [{ role: 'user', content }],\n tool: AI_LAYOUT_PAGE_TOOL,\n maxTokens,\n cutOff: { noun: 'page', smaller: 'Write shorter copy, and fewer items in each group.' },\n ...AI_LAYOUT_LANGUAGE_THINKING,\n check: observe(\n aiLayoutPageCheck({\n screen: input.screen,\n sectionIds: input.sectionIds,\n targets: input.targets,\n context: input.context,\n reusableComponents: input.reusableComponents,\n kept,\n design: aiLayoutDesignOf(input.job, input.screen.slug),\n motion: aiLayoutMotionSiteOf(input.job, input.screen.slug),\n ...(only ? { only } : {}),\n ...(input.plan.language ? { language: input.plan.language } : {}),\n promisesAllowed: aiSiteKindOfInputs(input.job.inputs)?.id === 'coming-soon',\n }),\n ),\n ...(input.signal ? { signal: input.signal } : {}),\n })\n const first = await ask(base, AI_JOB_PAGE_LANGUAGE_BUDGET.maxTokens(input.model))\n const missing = aiLayoutMissingSections(kept)\n if (\n first.status !== 'needs_input' ||\n !missing.length ||\n !first.violations.every((violation) => violation.code === AI_LAYOUT_SECTION_MISSING_CODE)\n ) {\n return first\n }\n const second = await ask(\n aiLayoutMissingSectionsPrompt({ base, screen: input.screen, missing }),\n Math.min(AI_JOB_PAGE_LANGUAGE_FOLLOW_UP_TOKENS, AI_JOB_PAGE_LANGUAGE_BUDGET.maxTokens(input.model)),\n missing,\n )\n return { ...second, ...spentTogether(first, second) }\n}\n"],"names":["CANVAS_ROOT_ELEMENT_ID","isAiPlanNewRef","aiHomeScreenIds","AI_LAYOUT_POST_ADDRESS_TOKENS","aiCompileLayoutPage","aiSiteMotionStyle","aiWithSiteMotion","aiLayoutListingAt","aiLayoutListingsOf","aiLayoutRecordHref","AI_LAYOUT_LANGUAGE_TEXT","AI_LAYOUT_PAGE_TOOL","aiReadLayoutPage","aiLayoutCopyCheck","aiLayoutWithoutSections","aiLayoutPromisedCopyViolations","aiLayoutPromisedSections","aiLayoutStoredTree","AI_GENERATION_MAX_ATTEMPTS","AI_STEP_TIERS","aiCacheWriteHourSum","runValidatedGeneration","aiSettleMechanicalRules","aiSettleUnrelatedScreenLinks","validateAiDoctrineTree","aiSiteKindDesignLines","aiSiteKindOfInputs","aiSiteSeed","aiOriginJobId","aiGenerationWorstCaseOnTierMs","aiJobStepBudget","aiJobBriefLine","aiPlanReferenceLines","aiLayoutIsHomeSlug","aiLayoutSiteAliases","aiLayoutSitePages","aiLayoutInventedContactViolations","aiSiteContactOf","AI_LAYOUT_LANGUAGE_INPUT","AI_LAYOUT_FORM_PAGE_INPUT","AI_LAYOUT_SITE_MOTION_INPUT","aiLayoutSiteMotionOf","value","style","seed","Number","isFinite","kind","motion","aiJobUsesLayoutLanguage","job","inputs","AI_LAYOUT_LANGUAGE_THINKING","thinking","effort","AI_LAYOUT_PAGE_THINKING_TOKENS","AI_LAYOUT_FRAME_THINKING_TOKENS","AI_JOB_PAGE_LANGUAGE_TOKENS","AI_LAYOUT_SECTION_MOST_TOKENS","AI_JOB_PAGE_LANGUAGE_FOLLOW_UP_TOKENS","AI_JOB_PAGE_LANGUAGE_BUDGET","tier","maxTokens","ownReadsMs","AI_LAYOUT_PAGE_KIND","AI_JOB_PAGE_LANGUAGE_INSTRUCTIONS","text","join","cacheBreakpoint","aiLayoutFormPageOfPlan","plan","formIds","placing","created","Set","create","filter","entry","map","name","toLowerCase","forms","screens","id","sections","some","section","uses","ref","has","screen","find","slug","aiLayoutFacts","values","Object","brief","aiLayoutPageTargets","input","own","inventory","planned","pages","alias","page","row","template","label","formPage","pageId","includes","homeIds","form","formPageId","components","component","props","facts","contact","listings","aiLayoutListingsWithDatasets","flatMap","listing","datasets","dataset","datasetId","imageField","addressField","recordBase","fields","length","index","fieldIds","type","field","aiLayoutListingContext","context","targets","formScreenIds","here","placements","placement","screenId","tokens","href","bindingTokens","AI_LAYOUT_START_PAGE_MAX_CHARS","aiLayoutStartPageLines","start","trim","shown","slice","trimEnd","aiLayoutFormLine","ids","placed","undefined","aiLayoutPagePrompt","places","listed","names","records","items","standsInFor","keys","title","startsFrom","reusableComponents","$id","aiLayoutDesignOf","home","aiLayoutMotionSiteOf","stored","aiLayoutMissingSectionsPrompt","missing","base","aiLayoutMissingSections","kept","AI_LAYOUT_SECTION_MISSING_CODE","AI_LAYOUT_SECTION_EMPTY_CODE","leastItems","aiLayoutShownItems","itemIds","storedIds","nodes","aiLayoutShortItemSections","quotesOnly","least","aiLayoutLeftOutNote","sectionIds","aiLayoutEmptyItemSections","emptied","short","rule","code","message","detail","aiLayoutRepeatsSaidInTheLanguage","violations","parentOf","Map","node","entries","child","set","sectionOf","at","get","indexOf","violation","where","nodeIds","sort","a","b","aiLayoutPageCheck","fills","only","_","answers","answer","last","reading","forEach","position","compiled","design","language","tree","ok","console","error","copy","dropped","rootId","ownScreenIds","without","why","push","promised","promisesAllowed","promisedOut","report","scrollTargetIds","repeatsCompiled","load","settled","spentTogether","first","second","usage","inputTokens","outputTokens","cacheReadTokens","cacheWriteTokens","attempts","estCostUsd","Math","round","model","stopReason","aiRunLayoutPage","observe","check","ask","content","step","instructions","messages","role","tool","cutOff","noun","smaller","signal","status","every","min"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,2CAA0C;AAEjF,SAASC,cAAc,QAAgC,4BAAwB;AAE/E,SACEC,eAAe,QAEV,gCAA4B;AACnC,SAASC,6BAA6B,EAAEC,mBAAmB,QAAQ,2CAAuC;AAC1G,SAASC,iBAAiB,EAAEC,gBAAgB,QAAgC,yCAAqC;AACjH,SAASC,iBAAiB,EAAEC,kBAAkB,EAAEC,kBAAkB,QAA8B,2CAAuC;AACvI,SACEC,uBAAuB,EACvBC,mBAAmB,EACnBC,gBAAgB,QAGX,2CAAuC;AAK9C,SAASC,iBAAiB,EAAEC,uBAAuB,QAAQ,uCAAmC;AAC9F,SAASC,8BAA8B,EAAEC,wBAAwB,QAAQ,gDAA4C;AACrH,SAASC,kBAAkB,QAAQ,wCAAoC;AACvE,SAASC,0BAA0B,QAAQ,qCAAiC;AAC5E,SAASC,aAAa,QAAQ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KAAKhB,iCAC1D;QACA,OAAOsE;IACT;IACA,MAAMC,SAAS,MAAMe,IACnB3F,8BAA8B;QAAEE;QAAMrF,QAAQQ,MAAMR,MAAM;QAAEoF;IAAQ,IACpEmF,KAAKoB,GAAG,CAAC1N,uCAAuCC,4BAA4BE,SAAS,CAACoC,MAAMiK,KAAK,IACjGrF;IAEF,OAAO,aAAK2E,QAAWF,cAAcC,OAAOC;AAC9C"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-page-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 { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport { fenceUntrustedText, UNTRUSTED_TEXT_RULE } from '@aglyn/shared-util-tools/untrusted-text'\nimport type { NodesMap } from '@aglyn/aglyn/types/nodes'\nimport { isAiPlanNewRef, type AiBuildPlanScreen } from '../model/ai-build-plan'\nimport type { AiJob, AiJobPlan } from '../model/ai-jobs.types'\nimport {\n aiHomeScreenIds,\n type AiSiteInventory,\n} from '../model/ai-site-inventory'\nimport { AI_LAYOUT_POST_ADDRESS_TOKENS, aiCompileLayoutPage } from '../layout-language/ai-layout-compiler'\nimport { aiSiteMotionStyle, aiWithSiteMotion, type AiSiteMotionStyle } from '../layout-language/ai-layout-motion'\nimport { aiLayoutListingAt, aiLayoutListingsOf, aiLayoutRecordHref, type AiLayoutListing } from '../layout-language/ai-layout-listings'\nimport {\n AI_LAYOUT_LANGUAGE_TEXT,\n AI_LAYOUT_PAGE_TOOL,\n aiReadLayoutPage,\n type AiLayoutSection,\n type AiLayoutSettlement,\n} from '../layout-language/ai-layout-language'\nimport type {\n AiLayoutPage,\n AiLayoutTargets,\n} from '../layout-language/ai-layout-links'\nimport { aiLayoutCopyCheck, aiLayoutWithoutSections } from '../layout-language/ai-layout-gaps'\nimport { aiLayoutPromisedCopyViolations, aiLayoutPromisedSections } from '../layout-language/ai-layout-promised-copy'\nimport { aiLayoutStoredTree } from '../layout-language/ai-layout-store'\nimport { AI_GENERATION_MAX_ATTEMPTS } from '../runtime/ai-generation-bounds'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { aiCacheWriteHourSum } from '../providers/cache-write-hour'\nimport {\n runValidatedGeneration,\n type AiGenerationCheck,\n type AiGenerationSpend,\n type AiValidatedGeneration,\n} from '../runtime/ai-doctrine'\nimport type { AiUsage } from '../providers/contract'\nimport {\n aiSettleMechanicalRules,\n aiSettleUnrelatedScreenLinks,\n validateAiDoctrineTree,\n type AiDoctrineNode,\n type AiDoctrineTreeContext,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { aiSiteKindDesignLines, aiSiteKindOfInputs } from '../model/ai-site-kinds'\nimport { aiSiteSeed } from '../model/ai-site-look'\nimport type { AiLayoutDesign } from '../layout-language/ai-layout-design'\nimport { aiOriginJobId } from './ai-job-draft-ids'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { aiGenerationWorstCaseOnTierMs, aiJobStepBudget } from './ai-job-budget'\nimport { aiJobBriefLine, aiPlanReferenceLines } from './ai-job-generation'\nimport { aiLayoutIsHomeSlug, aiLayoutSiteAliases, aiLayoutSitePages } from './ai-job-layout-site-pages'\nimport { aiLayoutInventedContactViolations } from './ai-layout-site-facts'\nimport { aiSiteContactOf } from '../model/ai-site-details'\n\n/**\n * A page built in the compact layout language (AGL-3660): the page step's\n * pass for a site's page units — a guided start's and a build's — in place of\n * the raw-tree section passes.\n *\n * ONE answer a page: every planned section, in the language, through\n * `submit_page`. The compiler writes the tree, the palette validator stores\n * it as it stores any generated tree, and the doctrine checks the whole page.\n * A section the answer left out or left empty is the one thing a re-ask asks\n * for: the sections that read are kept, and the second answer fills only\n * what is still missing. Then the page step's last pass runs as it always\n * has — the whole page held to the doctrine again, its listing written, the\n * draft reported — so the item ledger, the credits and Try again work exactly\n * as they did.\n */\n\n/** The unit input that says a page or a layout is built in the layout language. */\nexport const AI_LAYOUT_LANGUAGE_INPUT = 'layoutLanguage'\n\n/** The unit input naming the page of the site that places its form, where it is another page. */\nexport const AI_LAYOUT_FORM_PAGE_INPUT = 'layoutFormPage'\n\n/**\n * The unit input carrying the motion of the site a build adds to (AGL-3949):\n * its stored look's kind, seed and motion style (`aiLayoutSiteMotionOf`).\n */\nexport const AI_LAYOUT_SITE_MOTION_INPUT = 'siteMotion'\n\n/** The site a page's entrance motion is drawn for: its kind, seed and, where its look chose one, motion style. */\nexport interface AiLayoutSiteMotion {\n kind?: string\n seed: number\n motion?: AiSiteMotionStyle\n}\n\n/**\n * The motion a site's stored look names (`hosts/{id}.siteStyle`, or the\n * `AI_LAYOUT_SITE_MOTION_INPUT` read from it), read defensively: `null` for a\n * site whose look stored no seed, which a build then draws from its own job.\n */\nexport function aiLayoutSiteMotionOf(value: unknown): AiLayoutSiteMotion | null {\n if (!value || typeof value !== 'object') return null\n const style = value as Record<string, unknown>\n const seed = style['seed']\n if (typeof seed !== 'number' || !Number.isFinite(seed)) return null\n const kind = typeof style['kind'] === 'string' && style['kind'] ? style['kind'] : null\n const motion = aiSiteMotionStyle(style['motion'])\n return { ...(kind ? { kind } : {}), seed: seed >>> 0, ...(motion ? { motion } : {}) }\n}\n\n/** Whether this job builds its page or its layout in the layout language. */\nexport function aiJobUsesLayoutLanguage(job: Pick<AiJob, 'inputs'>): boolean {\n return job.inputs?.[AI_LAYOUT_LANGUAGE_INPUT] === true\n}\n\n/**\n * How the language doors think (AGL-3660): adaptively, at an effort named\n * rather than left to the model's default — a page and a site's frame are\n * designed, not transcribed.\n *\n * Low since AGL-3781. The live round of 2026-10-14 built the layout-language\n * briefs (`ai-job-layout-language-live.spec.ts`) at medium and at low: low\n * built 39 of 39 pages and 13 of 13 frames, 64 of 65 answers held their rules\n * on the first ask, and none was cut off at its ceiling. The ceilings keep\n * the thinking room sized at medium (`AI_LAYOUT_PAGE_THINKING_TOKENS`,\n * `AI_LAYOUT_FRAME_THINKING_TOKENS`), so a page that thinks longer still fits.\n */\nexport const AI_LAYOUT_LANGUAGE_THINKING = { thinking: 'adaptive', effort: 'low' } as const\n\n/**\n * Room for the thinking a page's answer does before it writes, inside the\n * same `max_tokens` as the answer: thinking is drawn from the ceiling first,\n * so a ceiling sized for the answer alone would cut a thoughtful answer off.\n *\n * Bounded by TIME, not by money: the page step's answer, its re-ask and the\n * follow-up must fit the least time a beat gives a step\n * (`AI_JOB_STEP_MAX_MINIMUM_MS`), and `aiJobStepBudget` quietly lowers every\n * ceiling to what fits. 2,000 here, with the follow-up's 500, is the most\n * that fits whole on the balanced tier; at 5,000 the budget cut a page's\n * ceiling to 879 tokens, under the answer itself.\n */\nexport const AI_LAYOUT_PAGE_THINKING_TOKENS = 2_000\n\n/** The same room for a site's header and footer, whose step has the time for more. */\nexport const AI_LAYOUT_FRAME_THINKING_TOKENS = 4_000\n\n/**\n * The most one page's answer asks for: the answer and the thinking before it.\n * A section in the language is about 120 to 250 tokens with its copy, so the\n * largest page a plan admits — eight sections — fits in 3,000 with room (the\n * live runs of 2026-10-07 wrote 683 to 1,745); the compiler, not the ceiling,\n * keeps a page small.\n */\nexport const AI_JOB_PAGE_LANGUAGE_TOKENS = 3_000 + AI_LAYOUT_PAGE_THINKING_TOKENS\n\n/**\n * The most one section of a page is written in, its copy included: the top of\n * the 120 to 250 tokens a section runs to. The Free site wall prices each\n * planned section at it (AGL-3660).\n */\nexport const AI_LAYOUT_SECTION_MOST_TOKENS = 250\n\n/**\n * The time a language page pass needs: its lookup rounds, its answer and its\n * re-ask at `AI_JOB_PAGE_LANGUAGE_TOKENS` on the tier the page step is served\n * from, with the step's reads and writes.\n */\n/** The most the follow-up asking only for the sections an answer left out may run to, its thinking included. */\nexport const AI_JOB_PAGE_LANGUAGE_FOLLOW_UP_TOKENS = 1_500 + 500\n\nexport const AI_JOB_PAGE_LANGUAGE_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.page'],\n maxTokens: AI_JOB_PAGE_LANGUAGE_TOKENS,\n // The follow-up for sections an answer left out is one more generation.\n ownReadsMs: aiGenerationWorstCaseOnTierMs({\n tier: AI_STEP_TIERS['job.page'],\n maxTokens: AI_JOB_PAGE_LANGUAGE_FOLLOW_UP_TOKENS,\n }),\n})\n\n/** The doctrine scope the language doors are told: values the compiler checks itself. */\nexport const AI_LAYOUT_PAGE_KIND = 'layout-page'\n\n/** The language, as the page door's cached instructions. */\nexport const AI_JOB_PAGE_LANGUAGE_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n AI_LAYOUT_LANGUAGE_TEXT,\n '',\n 'Answer with submit_page: the whole page, one entry in sections for each planned section, in order.',\n ].join('\\n'),\n cacheBreakpoint: true,\n },\n]\n\n/**\n * The page of a site plan that places its form: the form the plan creates, or\n * one the site has. Home only when no other page places it (AGL-3805).\n *\n * Every call to action that asks a visitor to get in touch goes here — the\n * header's button on every page, the footer's, a page's own — so a page whose\n * purpose is the form outranks the home page that closes on a copy of it. A\n * plan lists Home first, and a home page that ends \"visit us or order\" places\n * the form too: the first page placing it was Home, and a Spanish bakery's\n * header \"Pide tu pastel\" and footer \"Contáctanos\" (beta.253, job eg4maZMGtN)\n * linked the home page on every page, itself included, while /pasteles and\n * /visitanos held the form. Eight of the 21 newest AI-built sites linked their\n * header's call to action home the same way, six of them with such a page.\n */\nexport function aiLayoutFormPageOfPlan(\n plan: Pick<AiJobPlan, 'create' | 'screens'>,\n formIds: readonly string[] = [],\n): string | null {\n const created = new Set(\n plan.create\n .filter((entry) => entry.kind === 'form')\n .map((entry) => `new:${entry.name}`.toLowerCase()),\n )\n const forms = new Set(formIds)\n const placing = plan.screens.filter(\n (entry) =>\n typeof entry.id === 'string' &&\n entry.sections.some((section) =>\n section.uses.some((ref) =>\n isAiPlanNewRef(ref) ? created.has(ref.toLowerCase()) : forms.has(ref),\n ),\n ),\n )\n const screen = placing.find((entry) => !aiLayoutIsHomeSlug(entry.slug)) ?? placing[0]\n return screen?.id ?? null\n}\n\n/**\n * Every word the job was given, which a page's contact details are held to:\n * the brief, its scalar inputs, and the text of a page brought in from the\n * owner's own site (AGL-3976), whose phone and address are the owner's.\n */\nexport function aiLayoutFacts(job: Pick<AiJob, 'brief' | 'inputs'>): string {\n const values = Object.values(job.inputs ?? {}).filter(\n (value): value is string => typeof value === 'string',\n )\n const imported = aiLayoutImportedPageOf(job.inputs)?.text ?? ''\n return [job.brief, ...values, ...(imported ? [imported] : [])].join('\\n')\n}\n\n/** What a page's links resolve against: the site's pages, built and planned, its forms and components. */\nexport function aiLayoutPageTargets(input: {\n job: Pick<AiJob, 'brief' | 'inputs'>\n inventory: AiSiteInventory | null\n own: ReadonlyArray<string | null | undefined>\n}): AiLayoutTargets {\n const { job, inventory } = input\n const own = input.own.filter((id): id is string => !!id)\n const planned = aiLayoutSitePages(job.inputs)\n const pages: AiLayoutPage[] = [\n ...planned,\n // Planned pages merged into the blog (AGL-3676): a link to one goes to the blog.\n ...aiLayoutSiteAliases(job.inputs).filter((alias) => !planned.some((page) => page.id === alias.id)),\n ...(inventory?.screens ?? [])\n .filter(\n (row) => !row.template && !planned.some((page) => page.id === row.id),\n )\n .map((row) => ({ id: row.id, label: row.name, slug: row.slug })),\n ]\n const formPage = job.inputs?.[AI_LAYOUT_FORM_PAGE_INPUT]\n return {\n pageId: own[0] ?? null,\n pages: pages.filter((page) => !own.includes(page.id)),\n homeIds: aiHomeScreenIds(inventory),\n forms: (inventory?.forms ?? []).map((form) => ({\n id: form.id,\n name: form.name,\n })),\n formPageId:\n typeof formPage === 'string' && !own.includes(formPage) ? formPage : null,\n components: (inventory?.components ?? []).map((component) => ({\n id: component.id,\n name: component.name,\n props: component.props,\n })),\n facts: aiLayoutFacts(job),\n // The phone and email the person gave, which links call and write to (AGL-3979).\n contact: aiSiteContactOf(job.inputs),\n // The site's catalog and blog, and the sections that list them (AGL-3676),\n // and its datasets (AGL-3616).\n listings: aiLayoutListingsWithDatasets(aiLayoutListingsOf(job.inputs), inventory),\n }\n}\n\n/**\n * A page's listings with each dataset's held to the site's inventory\n * (AGL-3616): a records listing is kept only where the site has the dataset —\n * the tree check admits a repeat over no other, and a card left repeating\n * over nothing would show its `{{item.*}}` — and one that names no fields\n * takes the inventory's, in the dataset's order. Its cards link the record\n * pages the plan makes, else those the site already serves (AGL-3747).\n */\nexport function aiLayoutListingsWithDatasets(\n listings: readonly AiLayoutListing[],\n inventory: Pick<AiSiteInventory, 'datasets'> | null,\n): AiLayoutListing[] {\n return listings.flatMap((listing) => {\n if (listing.kind !== 'records') return [listing]\n const row = inventory?.datasets.find((dataset) => dataset.id === listing.datasetId)\n if (!row) return []\n // The photo field is the card's picture, never its words (AGL-3616).\n const imageField = listing.imageField ?? row.imageField\n // The address is the card's link to its record's page, never its words (AGL-3727).\n const addressField = listing.addressField ?? row.addressField\n // A record page the site already serves for the dataset (AGL-3747), where\n // the plan makes none of its own.\n const recordBase = listing.recordBase ?? row.recordBase\n const fields = (\n listing.fields?.length\n ? listing.fields\n : row.fields.map((name, index) => ({ id: row.fieldIds?.[index] || name, name, type: 'text' }))\n ).filter((field) => field.id !== imageField && field.id !== addressField)\n return fields.length\n ? [\n {\n ...listing,\n fields,\n ...(imageField ? { imageField } : {}),\n ...(recordBase && addressField ? { recordBase, addressField } : {}),\n },\n ]\n : []\n })\n}\n\n/**\n * The page check's context with what a section listing the blog's posts\n * binds (AGL-3676): each post's card links its post and shows its cover by\n * the tokens the page fills per post, which a page's store admits whole only\n * where a listing places them. A dataset's card shows its record's photo\n * the same way (AGL-3616), by `{{item.<photo field>}}`. And the page that\n * places the site's form, which a call to action asking a visitor to get in\n * touch links even when it is home (AGL-3729).\n */\nexport function aiLayoutListingContext(\n context: AiDoctrineTreeContext,\n targets: AiLayoutTargets,\n): AiDoctrineTreeContext {\n if (targets.formPageId) context = { ...context, formScreenIds: [targets.formPageId] }\n const here = (targets.listings ?? []).filter((listing) =>\n listing.placements.some((placement) => placement.screenId === targets.pageId),\n )\n const tokens = [\n ...(here.some((listing) => listing.kind === 'posts') ? AI_LAYOUT_POST_ADDRESS_TOKENS : []),\n ...here.flatMap((listing) => (listing.kind === 'records' && listing.imageField ? [`{{item.${listing.imageField}}}`] : [])),\n // Each card's link to its record's own page (AGL-3727), admitted whole.\n ...here.flatMap((listing) => {\n const href = aiLayoutRecordHref(listing)\n return href ? [href] : []\n }),\n ]\n if (!tokens.length) return context\n return { ...context, bindingTokens: [...new Set([...(context.bindingTokens ?? []), ...tokens])] }\n}\n\n/** The most of the text of the page a planned page starts from that its prompt shows: about 1,000 tokens (AGL-3832). */\nexport const AI_LAYOUT_START_PAGE_MAX_CHARS = 4_000\n\n/** The site's page a planned page starts from (its plan's `duplicateOf`), by its name and its words. */\nexport interface AiLayoutStartPage {\n label: string\n text: string\n}\n\n/**\n * The page a planned page starts from, as its prompt shows it (AGL-3832): its\n * words, never its tree. A page in the layout language is written whole, so\n * a copy of the page would be replaced by the answer, and what the copy was\n * for — what the site already says there — reaches the page only through\n * the model. Empty when the page has no words to show.\n */\nexport function aiLayoutStartPageLines(start: AiLayoutStartPage | null | undefined): string[] {\n const text = start?.text.trim() ?? ''\n if (!start || !text) return []\n const shown = text.length > AI_LAYOUT_START_PAGE_MAX_CHARS ? `${text.slice(0, AI_LAYOUT_START_PAGE_MAX_CHARS).trimEnd()} …` : text\n return [\n `This page starts from the site's page \"${start.label}\": keep its facts, names and details wherever a section below covers them, and design every section anew. Its text:`,\n shown,\n ]\n}\n\n/**\n * The unit input carrying a page a site import brings in (AGL-3976): its\n * address on the owner's own website and its text as that site shows it. It\n * reaches the model only fenced as untrusted data, under\n * `UNTRUSTED_TEXT_RULE`, and only on a job the import step derives — a\n * member's own job carries none, because the create door's inputs are\n * scalars and this is an object.\n */\nexport const AI_LAYOUT_IMPORTED_PAGE_INPUT = 'importedPage'\n\n/** A page brought in, as the import step hands it to the page step. */\nexport interface AiLayoutImportedPage {\n /** Where the page is on the owner's website. */\n url: string\n /** Its title, headings and text in order, as the crawler extracted them. */\n text: string\n}\n\n/** The most characters of an imported page's text a prompt shows. */\nexport const AI_LAYOUT_IMPORTED_PAGE_MAX_CHARS = 6_000\n\n/** The imported page a job's inputs carry, read defensively; `null` on every other job. */\nexport function aiLayoutImportedPageOf(inputs: Readonly<Record<string, unknown>> | null | undefined): AiLayoutImportedPage | null {\n const raw = inputs?.[AI_LAYOUT_IMPORTED_PAGE_INPUT]\n if (!raw || typeof raw !== 'object') return null\n const { url, text } = raw as Record<string, unknown>\n if (typeof url !== 'string' || typeof text !== 'string' || !text.trim()) return null\n return { url: url.slice(0, 2048), text }\n}\n\n/**\n * What a page brought in from the owner's site is told (AGL-3976): rewrite\n * it into the planned sections, keeping its facts, and the text itself,\n * fenced. The fence and the system block's rule are what keep the page's own\n * words — \"ignore your instructions\" on a hostile page — data.\n */\nexport function aiLayoutImportedPageLines(page: AiLayoutImportedPage | null): string[] {\n if (!page) return []\n return [\n 'This page is the site owner\\'s own page, brought in from their current website. Rewrite its content into the sections below, in its own language: keep its facts, names, prices, hours, services and details wherever a section covers them, and leave a gap in square brackets for a fact it does not give rather than invent one. Leave out cookie notices, sign-in, carts, the old site\\'s own tools and anything about the website builder it was made with. Draw no form, embed or script of its own, and design every section anew. Its text, as that site shows it:',\n fenceUntrustedText(`The owner's page ${page.url}`, page.text, { maxChars: AI_LAYOUT_IMPORTED_PAGE_MAX_CHARS }),\n ]\n}\n\n/**\n * The page door's system blocks for this job: the language's cached\n * instructions, and for a page brought in from the owner's site the rule\n * that fenced text is data (AGL-3976), a static block of its own so every\n * imported page shares one cached prefix and no other page's changes.\n */\nexport function aiJobPageLanguageInstructions(job: Pick<AiJob, 'inputs'>): readonly AiSystemBlock[] {\n return aiLayoutImportedPageOf(job.inputs)\n ? [...AI_JOB_PAGE_LANGUAGE_INSTRUCTIONS, { text: UNTRUSTED_TEXT_RULE }]\n : AI_JOB_PAGE_LANGUAGE_INSTRUCTIONS\n}\n\n/**\n * What a page is told about the site's form (AGL-3899). A page whose plan\n * places the form, or a site whose form has no page of its own, is told the\n * form; any other page is told where the form lives and that its call to\n * action links there. Told \"The site's form: …\" on every page, two of the\n * newest production homes drew the form on their own, beside the Contact\n * page that held it.\n */\nexport function aiLayoutFormLine(screen: Pick<AiBuildPlanScreen, 'sections'>, targets: AiLayoutTargets): string {\n if (!targets.forms.length) return 'The site has no saved form: place none.'\n const ids = new Set(targets.forms.map((form) => form.id))\n const placed = screen.sections.some((section) => section.uses.some((ref) => ids.has(ref)))\n const page = targets.formPageId ? targets.pages.find((entry) => entry.id === targets.formPageId) : undefined\n if (placed || !page) return `The site's form: ${targets.forms.map((form) => `${form.name} (${form.id})`).join(', ')}.`\n return `The site's form is on the ${page.label} page (page:${page.id}): place no form on this page, and make a call to action that asks visitors to get in touch a button to that page.`\n}\n\n/** The page's user turn: the page, the brief, the plan, its sections and where its links may go. */\nexport function aiLayoutPagePrompt(input: {\n job: Pick<AiJob, 'brief' | 'inputs' | '$id'>\n plan: AiJobPlan\n screen: AiBuildPlanScreen\n targets: AiLayoutTargets\n reusableComponents: boolean\n /** The site's page the plan starts this page from, read off the site (AGL-3832). */\n startsFrom?: AiLayoutStartPage | null\n /** The sections a re-ask still needs, by plan index; absent on the first ask. */\n missing?: readonly number[]\n}): string {\n const { job, plan, screen, targets } = input\n const sections = screen.sections.map((section, index) => {\n const places = section.uses.length\n ? `; places ${section.uses.join(', ')}`\n : ''\n // A section the site's records fill (AGL-3676): the platform places them,\n // so the design writes the words around them and no group for them.\n const listed = aiLayoutListingAt(targets.listings ?? [], targets.pageId, index)\n if (listed?.listing.kind === 'tracks') {\n // A music site's player (AGL-3716): placed empty, for the owner's own uploads.\n return `${index + 1}. \"${section.name}\"${places}; the platform places a music player here for the artist's own tracks, which they add themselves: write only its heading and a line inviting visitors to listen, and no cards, list, images or links for songs`\n }\n if (listed?.listing.kind === 'events') {\n // The site's own dated events (AGL-3755), listed by the platform with their dates.\n const names = listed.listing.records.length ? ` (${listed.listing.records.map((name) => `\"${name}\"`).join(', ')})` : ''\n return `${index + 1}. \"${section.name}\"${places}; the platform lists the site's upcoming events here${names} with their dates, places and photos: write only its heading and a line inviting visitors to come, and no cards, dates, list or links for events`\n }\n if (listed?.listing.kind === 'reviews') {\n // A store's own reviews (AGL-3676): shoppers write them; none is ever written here.\n return `${index + 1}. \"${section.name}\"${places}; the platform shows the store's real customer reviews here with their star ratings, once shoppers leave them: write only its heading, and no quotes, names, ratings or cards`\n }\n if (listed?.listing.kind === 'signup') {\n // A store's newsletter field (AGL-3676), placed by the platform.\n return `${index + 1}. \"${section.name}\"${places}; the platform places the newsletter sign-up field here: write its heading and one line on what subscribers hear about, from the brief, and no form, button or offer the brief does not make`\n }\n if (listed?.listing.kind === 'records') {\n // One of the site's datasets (AGL-3616), repeated by the platform over its records.\n // A section named for one group lists that group's records alone (AGL-3921).\n const shown = listed.filter?.records.length ? listed.filter.records : listed.listing.records\n const names = shown.length ? ` (${shown.slice(0, 6).map((name) => `“${name}”`).join(', ')})` : ''\n return `${index + 1}. \"${section.name}\"${places}; the platform lists the records of the dataset “${listed.listing.name}”${names} here itself, one card each: write only its heading and a line about them, and no cards, list or images for them`\n }\n if (listed) {\n return `${index + 1}. \"${section.name}\"${places}; the platform lists ${listed.listing.name}'s ${listed.listing.kind} here itself, with their photos and links: write only its heading and a line about them, and no cards, list or images for them`\n }\n const items = section.items ? `; shows ${section.items} items` : ''\n return `${index + 1}. \"${section.name}\"${places}${items}`\n })\n // A page merged into the blog is not offered: the blog is, by its own entry.\n const pages = targets.pages.filter((page) => !page.standsInFor).map((page) => `${page.label} (page:${page.id})`)\n const components = targets.components.map(\n (component) =>\n `${component.name} (${component.id}; props ${Object.keys(component.props).join(', ') || 'none'})`,\n )\n return [\n `Page: \"${screen.title}\" at ${screen.slug}`,\n aiJobBriefLine(job),\n // The kind of site the person picked sets how its pages are arranged (AGL-3660).\n ...aiSiteKindDesignLines(job.inputs),\n ...aiPlanReferenceLines(plan),\n ...aiLayoutStartPageLines(input.startsFrom),\n // A page brought in from the owner's own site (AGL-3976), fenced.\n ...aiLayoutImportedPageLines(aiLayoutImportedPageOf(job.inputs)),\n `Sections to design, in order:`,\n ...sections,\n pages.length\n ? `Other pages of this site: ${pages.join(', ')}.`\n : 'This site has no other page to link.',\n aiLayoutFormLine(screen, targets),\n ...(components.length\n ? [`Components this page may place: ${components.join('; ')}.`]\n : []),\n input.reusableComponents\n ? 'Where a section repeats an item, place the component its plan line names with cards whose to is that component.'\n : 'This site keeps no reusable components: draw repeated items as cards, steps, stats or a list.',\n // A per-job word, so two identical briefs are designed apart.\n `Design seed: ${job.$id.slice(-6)}.`,\n ].join('\\n')\n}\n\n/**\n * The site a page is designed for (AGL-3660): the kind its job names, the\n * seed its look was drawn with — the same for every page of the site, so the\n * site reads as one design — and whether the page is its home. `null` for a\n * job that names no kind of site, which compiles the compiler's first way.\n */\nexport function aiLayoutDesignOf(job: Pick<AiJob, '$id' | 'inputs'>, slug: string): AiLayoutDesign | null {\n const kind = aiSiteKindOfInputs(job.inputs)\n if (!kind) return null\n const style = job.inputs?.['siteStyle'] as Record<string, unknown> | undefined\n const seed = typeof style?.['seed'] === 'number' && Number.isFinite(style['seed']) ? (style['seed'] as number) >>> 0 : aiSiteSeed(aiOriginJobId(job))\n return { kind: kind.id, seed, home: aiLayoutIsHomeSlug(slug) }\n}\n\n/**\n * The site a page's entrance motion is drawn for (AGL-3838): its design where\n * the job names a kind of site, else the job's own seed, which moves in the\n * standard mood — so every page of one site moves alike. The motion style its\n * look chose rides along (AGL-3941); a job whose look chose none — one from\n * before the look did, a replay of one, a job with no look — moves in its\n * kind's mood. A unit a build makes on an existing site carries the site's\n * stored motion instead (`AI_LAYOUT_SITE_MOTION_INPUT`, AGL-3949), so a page\n * added later moves the way the site's own pages do.\n */\nexport function aiLayoutMotionSiteOf(\n job: Pick<AiJob, '$id' | 'inputs'>,\n slug: string,\n): AiLayoutSiteMotion {\n const style = job.inputs?.['siteStyle'] as Record<string, unknown> | undefined\n if (!style) {\n const stored = aiLayoutSiteMotionOf(job.inputs?.[AI_LAYOUT_SITE_MOTION_INPUT])\n if (stored) return stored\n }\n const motion = aiSiteMotionStyle(style?.['motion'])\n const { kind, seed } = aiLayoutDesignOf(job, slug) ?? { seed: aiSiteSeed(aiOriginJobId(job)) }\n return { ...(kind ? { kind } : {}), seed, ...(motion ? { motion } : {}) }\n}\n\n/** A validated language page, stored as the page keeps it. */\nexport interface AiLayoutPageBuilt {\n nodes: NodesMap\n load: AiLoadEstimate | null\n settled: AiLayoutSettlement[]\n /** What the last answer's gaps took out of the page (`ai-layout-gaps.ts`). */\n dropped: string[]\n /** How many repeated items each plan section shows, as built (AGL-3660). */\n items: number[]\n}\n\nexport interface AiLayoutPageCheckInput {\n screen: AiBuildPlanScreen\n sectionIds: readonly string[]\n targets: AiLayoutTargets\n context: AiDoctrineTreeContext\n reusableComponents: boolean\n /**\n * What earlier answers gave, by plan index, shared between the page's\n * generations: a follow-up asking only for missing sections fills the rest.\n */\n kept?: Array<AiLayoutSection | null>\n /** The plan indices this answer's sections fill, in order; absent, every section. */\n only?: readonly number[]\n /** The site the page is drawn for (`aiLayoutDesignOf`); absent, the compiler's first design. */\n design?: AiLayoutDesign | null\n /** The site's language, which the compiler's own words are written in (AGL-3760); absent, English. */\n language?: string\n /** The site the page's entrance motion is drawn for (`aiLayoutMotionSiteOf`); absent, its design. */\n motion?: AiLayoutSiteMotion\n /** Whether copy may promise what is coming (a coming-soon site, AGL-3887); absent, it may not. */\n promisesAllowed?: boolean\n}\n\n/**\n * The follow-up turn for the sections a page's answer left out (AGL-3660):\n * the page as before, told which sections it already has, and asked for only\n * the missing ones, in order — the one part of a page asked for again.\n */\nexport function aiLayoutMissingSectionsPrompt(input: {\n base: string\n screen: AiBuildPlanScreen\n missing: readonly number[]\n}): string {\n const names = input.missing.map((index) => `${index + 1}. \"${input.screen.sections[index].name}\"`)\n return [\n input.base,\n '',\n `The other sections of this page are already designed. Design ONLY these, in this order, one entry in sections each: ${names.join('; ')}. Give each at least one block.`,\n ].join('\\n')\n}\n\n/** The plan indices a page still lacks, after the answers so far. */\nexport function aiLayoutMissingSections(kept: ReadonlyArray<AiLayoutSection | null>): number[] {\n return kept.flatMap((section, index) => (section ? [] : [index]))\n}\n\n/** The violation a planned section the answer gave nothing usable for is named by. */\nexport const AI_LAYOUT_SECTION_MISSING_CODE = 'layout-section-missing'\n\n/** The code a section planned with items that shows none is refused under (AGL-3660). */\nexport const AI_LAYOUT_SECTION_EMPTY_CODE = 'layout-section-no-items'\n\n/** How many of a section's planned items it must show: one for a short list, two for anything longer. */\nconst leastItems = (planned: number) => (planned >= 3 ? 2 : planned >= 1 ? 1 : 0)\n\n/**\n * How many repeated items each section shows once stored (AGL-3660): the\n * elements the compiler drew for them, under the ids they are stored by,\n * that are still in the page after anything later took words out.\n */\nexport function aiLayoutShownItems(\n itemIds: readonly (readonly string[])[],\n storedIds: Readonly<Record<string, string>>,\n nodes: Readonly<Record<string, unknown>>,\n): number[] {\n return itemIds.map((ids) => ids.filter((id) => storedIds[id] !== undefined && storedIds[id] in nodes).length)\n}\n\n/** The plan indices of the sections that show fewer of their planned items than they must (AGL-3660). */\nexport function aiLayoutShortItemSections(\n screen: Pick<AiBuildPlanScreen, 'sections'>,\n items: readonly number[],\n quotesOnly: readonly number[] = [],\n): number[] {\n return screen.sections.flatMap((section, index) => {\n if (quotesOnly.includes(index)) return []\n const least = leastItems(section.items)\n return least && (items[index] ?? 0) < least ? [index] : []\n })\n}\n\n/**\n * What a page built in the layout language says about the planned sections\n * it was published without (AGL-3771): each one the last answer could not\n * fill, or left with only its heading once its gaps were taken out, rather\n * than the page refused. `null` when every section is shown.\n */\nexport function aiLayoutLeftOutNote(\n screen: Pick<AiBuildPlanScreen, 'sections'>,\n sectionIds: readonly string[],\n nodes: Readonly<Record<string, unknown>>,\n): string | null {\n const names = screen.sections.flatMap((section, index) =>\n index > 0 && sectionIds[index] && !(sectionIds[index] in nodes) ? [`“${section.name}”`] : [],\n )\n if (!names.length) return null\n return names.length === 1\n ? `Left out: the section ${names[0]}, which could not be built well enough to publish. Add it in the Besigner when you are ready.`\n : `Left out: the sections ${names.join(', ')}, which could not be built well enough to publish. Add them in the Besigner when you are ready.`\n}\n\n/**\n * The sections a page planned with repeated items — cards, steps, a list —\n * that show none, or too few, once the page is built (AGL-3660). A heading\n * and an intro over nothing is a section a visitor reads as broken, so it is\n * asked for again.\n */\nexport function aiLayoutEmptyItemSections(\n screen: Pick<AiBuildPlanScreen, 'sections'>,\n items: readonly number[],\n /** Sections whose only items were customer quotes, which no answer may give (AGL-3676). */\n quotesOnly: readonly number[] = [],\n /** Sections the page no longer shows (AGL-3771), which ask for nothing. */\n emptied: readonly number[] = [],\n): AiDoctrineViolation[] {\n const short = aiLayoutShortItemSections(screen, items, quotesOnly)\n return screen.sections.flatMap((section, index): AiDoctrineViolation[] => {\n if (!short.includes(index) || emptied.includes(index)) return []\n const shown = items[index] ?? 0\n return [\n {\n rule: null,\n code: AI_LAYOUT_SECTION_EMPTY_CODE,\n message: `Section ${index + 1} (\"${section.name}\") is planned with ${section.items} items and shows ${shown || 'none'}.`,\n detail: `Give section ${index + 1} one cards, steps, stats, list or faq block holding its ${section.items} items, each with a title and its words.`,\n },\n ]\n })\n}\n\n/**\n * Rule 1's repeats said as the layout language fixes them (AGL-3988). Its\n * own words ask for \"one reusable component with props\", which a page\n * answer cannot make: the beta.270 Sugar Hollow Galleries page was re-asked\n * with them and node ids it never wrote, broke the rule the same way, and\n * was refused. Each repeat now names the sections it sits in and how the\n * language says like blocks once: one group, an item each.\n */\nexport function aiLayoutRepeatsSaidInTheLanguage(\n violations: readonly AiDoctrineViolation[],\n nodes: Readonly<Record<string, { nodes?: string[] }>>,\n sectionIds: readonly string[],\n sections: ReadonlyArray<{ name: string }>,\n): AiDoctrineViolation[] {\n const parentOf = new Map<string, string>()\n for (const [id, node] of Object.entries(nodes)) for (const child of node?.nodes ?? []) parentOf.set(child, id)\n const sectionOf = (id: string): number => {\n for (let at: string | undefined = id; at !== undefined; at = parentOf.get(at)) {\n const index = sectionIds.indexOf(at)\n if (index >= 0) return index\n }\n return -1\n }\n return violations.map((violation) => {\n if (violation.code !== 'repeated-subtree') return violation\n const where = [...new Set((violation.nodeIds ?? []).map(sectionOf).filter((index) => index >= 0))]\n .sort((a, b) => a - b)\n .map((index) => `section ${index + 1} (\"${sections[index]?.name ?? ''}\")`)\n return {\n ...violation,\n detail: `${where.length ? `In ${where.join(' and ')}: ` : ''}write like blocks once, as one cards, steps or list block with an item for each (its title, its words and where it goes), never the same blocks repeated in several columns or groups.`,\n }\n })\n}\n\n/**\n * The check a language page answer is held to: each planned section read,\n * the page compiled, stored and checked whole. Sections that read are kept\n * across the re-ask, so the second answer is asked only for what was missing,\n * and a section it sends again that already read is not taken twice.\n */\nexport function aiLayoutPageCheck(\n input: AiLayoutPageCheckInput,\n): AiGenerationCheck<AiLayoutPageBuilt> {\n const kept: Array<AiLayoutSection | null> = input.kept ?? input.screen.sections.map(() => null)\n const fills = input.only ?? input.screen.sections.map((_, index) => index)\n const context = aiLayoutListingContext(input.context, input.targets)\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 const last = answers >= AI_GENERATION_MAX_ATTEMPTS\n const reading = aiReadLayoutPage(\n answer,\n fills.length,\n fills.map((index) => input.screen.sections[index]),\n )\n reading.sections.forEach((section, position) => {\n // A section the answer gives is taken as given; one it leaves out keeps\n // what an earlier answer gave, so a re-ask may send only what was missing.\n if (section) kept[fills[position]] = section\n })\n const missing = kept.flatMap((section, index) => (section ? [] : [index]))\n if (missing.length) {\n const names = missing.map(\n (index) => `${index + 1} (\"${input.screen.sections[index].name}\")`,\n )\n return {\n value: null,\n violations: [\n {\n rule: null,\n code: AI_LAYOUT_SECTION_MISSING_CODE,\n message: `The page left out section ${names.join(', ')}.`,\n detail: `Answer again with every section in order; the sections you already designed are kept, so only ${names.join(', ')} ${missing.length === 1 ? 'needs' : 'need'} its design. Give each at least one block.`,\n },\n ],\n }\n }\n const compiled = aiCompileLayoutPage(\n kept as AiLayoutSection[],\n { title: input.screen.title, sections: input.screen.sections },\n input.targets,\n {\n reusableComponents: input.reusableComponents,\n sectionIds: input.sectionIds,\n ...(input.design ? { design: input.design } : {}),\n ...(input.language ? { language: input.language } : {}),\n },\n )\n const stored = aiLayoutStoredTree(\n compiled.tree,\n 'screen',\n context,\n input.sectionIds,\n )\n if (stored.ok === false) {\n // The compiler writes only palette trees, which the property spec holds;\n // a refusal here is the platform's, and is reported as one.\n console.error('ai layout page: a compiled page 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 page 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 page that is published as built.\n const copy = aiLayoutCopyCheck(\n stored.nodes,\n CANVAS_ROOT_ELEMENT_ID,\n {\n pages: input.targets.pages,\n ids: [\n ...input.targets.pages.map((page) => page.id),\n ...input.targets.forms.map((form) => form.id),\n ...input.targets.components.map((component) => component.id),\n ...input.sectionIds,\n ...(input.targets.pageId ? [input.targets.pageId] : []),\n ],\n },\n last,\n )\n const dropped = [...copy.dropped]\n // An attribute a rule has one answer for is settled, not asked of the model again (AGL-3660),\n // and a link sent home for nothing is sent to the form or left out (AGL-3729).\n let nodes = aiSettleUnrelatedScreenLinks(\n aiSettleMechanicalRules(\n { rootId: CANVAS_ROOT_ELEMENT_ID, nodes: copy.nodes as unknown as Record<string, AiDoctrineNode> },\n 'page',\n ),\n 'page',\n { ...context, ownScreenIds: input.targets.pageId ? [input.targets.pageId] : [] },\n ).nodes as unknown as typeof copy.nodes\n // Each section's items as they are stored, after anything the gaps took out.\n const items = aiLayoutShownItems(compiled.itemIds, stored.storedIds, nodes as unknown as Record<string, unknown>)\n // The last answer's sections that still show none of their planned items\n // are taken out rather than the whole page refused (AGL-3771): a site\n // start's home refused for one such section published a site with\n // nothing at its address. The page's first section heads it, and is\n // never taken out.\n const emptied = last\n ? aiLayoutShortItemSections(input.screen, items, compiled.quotesOnly).filter((index) => index > 0 && !!input.sectionIds[index])\n : []\n if (emptied.length) {\n const without = aiLayoutWithoutSections(\n nodes,\n CANVAS_ROOT_ELEMENT_ID,\n emptied.map((index) => ({\n id: input.sectionIds[index],\n name: input.screen.sections[index].name,\n why: `planned with ${input.screen.sections[index].items} items and showing ${items[index] || 'none'}`,\n })),\n )\n nodes = without.nodes as typeof nodes\n dropped.push(...without.dropped)\n }\n // A section that promises its content later — \"We are building this\n // space\" — is asked for again, and the last answer's is taken out, the\n // page's first section aside (AGL-3887). A coming-soon site's is its point.\n const promised = input.promisesAllowed ? [] : aiLayoutPromisedSections(nodes, input.sectionIds)\n const promisedOut = last ? promised.filter(({ index }) => index > 0) : []\n if (promisedOut.length) {\n const without = aiLayoutWithoutSections(\n nodes,\n CANVAS_ROOT_ELEMENT_ID,\n promisedOut.map(({ index }) => ({\n id: input.sectionIds[index],\n name: input.screen.sections[index].name,\n why: 'which promised content that is not there',\n })),\n )\n nodes = without.nodes as typeof nodes\n dropped.push(...without.dropped)\n }\n const report = validateAiDoctrineTree(\n { rootId: CANVAS_ROOT_ELEMENT_ID, nodes },\n 'page',\n {\n ...context,\n scrollTargetIds: input.sectionIds,\n // The layout language draws its own picture cards (AGL-3660).\n repeatsCompiled: true,\n },\n )\n // A street address or opening hours the job was never given is invented\n // (rule 14, AGL-3596), the same check a layout is held to; a phone number\n // or an email the compiler already writes as its gap.\n const violations: AiDoctrineViolation[] = [\n ...aiLayoutRepeatsSaidInTheLanguage(report.violations, nodes as unknown as Record<string, { nodes?: string[] }>, input.sectionIds, input.screen.sections),\n ...copy.violations,\n ...aiLayoutEmptyItemSections(input.screen, items, compiled.quotesOnly, emptied),\n ...(last ? [] : aiLayoutPromisedCopyViolations(input.screen, promised)),\n ...aiLayoutInventedContactViolations(\n { rootId: CANVAS_ROOT_ELEMENT_ID, nodes: nodes as unknown as Record<string, AiDoctrineNode> },\n input.targets.facts,\n ),\n ]\n return {\n value: violations.length\n ? null\n : {\n // Entrance motion is the site's, decided here in code and never\n // asked of the model (AGL-3838): written once the page has passed,\n // so no check above reads a prop the palette does not list.\n nodes: aiWithSiteMotion(nodes, input.motion ?? input.design ?? { seed: 0 }, { sectionIds: input.sectionIds }),\n load: report.load,\n settled: [...reading.settled, ...compiled.settled],\n dropped,\n items,\n },\n violations,\n }\n }\n}\n\nexport interface AiLayoutPageRunInput {\n job: Pick<AiJob, 'brief' | 'inputs' | '$id'>\n plan: AiJobPlan\n screen: AiBuildPlanScreen\n sectionIds: readonly string[]\n targets: AiLayoutTargets\n context: AiDoctrineTreeContext\n reusableComponents: boolean\n inventory: AiSiteInventory | null\n model: string\n /** The site's page the plan starts this page from (AGL-3832). */\n startsFrom?: AiLayoutStartPage | null\n signal?: AbortSignal\n /** Wraps the check, for an eval that records each answer it reads. */\n observe?: (check: AiGenerationCheck<AiLayoutPageBuilt>) => AiGenerationCheck<AiLayoutPageBuilt>\n}\n\n/** Two generations' spend as one: every call is billed. */\nfunction spentTogether(first: AiGenerationSpend, second: AiGenerationSpend): AiGenerationSpend {\n const usage: AiUsage = {\n inputTokens: first.usage.inputTokens + second.usage.inputTokens,\n outputTokens: first.usage.outputTokens + second.usage.outputTokens,\n cacheReadTokens: first.usage.cacheReadTokens + second.usage.cacheReadTokens,\n cacheWriteTokens: first.usage.cacheWriteTokens + second.usage.cacheWriteTokens,\n ...aiCacheWriteHourSum(first.usage, second.usage),\n }\n return {\n attempts: first.attempts + second.attempts,\n usage,\n estCostUsd: Math.round((first.estCostUsd + second.estCostUsd) * 1_000_000) / 1_000_000,\n model: second.model,\n stopReason: second.stopReason,\n effort: second.effort,\n }\n}\n\n/**\n * A whole page in the layout language: one answer for every section, and,\n * where that answer and its re-ask still left a section out, one follow-up\n * asking for only those (AGL-3660). The sections that read are kept between\n * them, so the page is compiled whole once every section is designed.\n */\nexport async function aiRunLayoutPage(input: AiLayoutPageRunInput): Promise<AiValidatedGeneration<AiLayoutPageBuilt>> {\n const kept: Array<AiLayoutSection | null> = input.screen.sections.map(() => null)\n const observe = input.observe ?? ((check) => check)\n const base = aiLayoutPagePrompt({\n job: input.job,\n plan: input.plan,\n screen: input.screen,\n targets: input.targets,\n reusableComponents: input.reusableComponents,\n startsFrom: input.startsFrom ?? null,\n })\n const ask = (content: string, maxTokens: number, only?: readonly number[]) =>\n runValidatedGeneration<AiLayoutPageBuilt>(AI_LAYOUT_PAGE_KIND, {\n step: 'job.page',\n model: input.model,\n instructions: aiJobPageLanguageInstructions(input.job),\n inventory: input.inventory,\n messages: [{ role: 'user', content }],\n tool: AI_LAYOUT_PAGE_TOOL,\n maxTokens,\n cutOff: { noun: 'page', smaller: 'Write shorter copy, and fewer items in each group.' },\n ...AI_LAYOUT_LANGUAGE_THINKING,\n check: observe(\n aiLayoutPageCheck({\n screen: input.screen,\n sectionIds: input.sectionIds,\n targets: input.targets,\n context: input.context,\n reusableComponents: input.reusableComponents,\n kept,\n design: aiLayoutDesignOf(input.job, input.screen.slug),\n motion: aiLayoutMotionSiteOf(input.job, input.screen.slug),\n ...(only ? { only } : {}),\n ...(input.plan.language ? { language: input.plan.language } : {}),\n promisesAllowed: aiSiteKindOfInputs(input.job.inputs)?.id === 'coming-soon',\n }),\n ),\n ...(input.signal ? { signal: input.signal } : {}),\n })\n const first = await ask(base, AI_JOB_PAGE_LANGUAGE_BUDGET.maxTokens(input.model))\n const missing = aiLayoutMissingSections(kept)\n if (\n first.status !== 'needs_input' ||\n !missing.length ||\n !first.violations.every((violation) => violation.code === AI_LAYOUT_SECTION_MISSING_CODE)\n ) {\n return first\n }\n const second = await ask(\n aiLayoutMissingSectionsPrompt({ base, screen: input.screen, missing }),\n Math.min(AI_JOB_PAGE_LANGUAGE_FOLLOW_UP_TOKENS, AI_JOB_PAGE_LANGUAGE_BUDGET.maxTokens(input.model)),\n missing,\n )\n return { ...second, ...spentTogether(first, second) }\n}\n"],"names":["CANVAS_ROOT_ELEMENT_ID","fenceUntrustedText","UNTRUSTED_TEXT_RULE","isAiPlanNewRef","aiHomeScreenIds","AI_LAYOUT_POST_ADDRESS_TOKENS","aiCompileLayoutPage","aiSiteMotionStyle","aiWithSiteMotion","aiLayoutListingAt","aiLayoutListingsOf","aiLayoutRecordHref","AI_LAYOUT_LANGUAGE_TEXT","AI_LAYOUT_PAGE_TOOL","aiReadLayoutPage","aiLayoutCopyCheck","aiLayoutWithoutSections","aiLayoutPromisedCopyViolations","aiLayoutPromisedSections","aiLayoutStoredTree","AI_GENERATION_MAX_ATTEMPTS","AI_STEP_TIERS","aiCacheWriteHourSum","runValidatedGeneration","aiSettleMechanicalRules","aiSettleUnrelatedScreenLinks","validateAiDoctrineTree","aiSiteKindDesignLines","aiSiteKindOfInputs","aiSiteSeed","aiOriginJobId","aiGenerationWorstCaseOnTierMs","aiJobStepBudget","aiJobBriefLine","aiPlanReferenceLines","aiLayoutIsHomeSlug","aiLayoutSiteAliases","aiLayoutSitePages","aiLayoutInventedContactViolations","aiSiteContactOf","AI_LAYOUT_LANGUAGE_INPUT","AI_LAYOUT_FORM_PAGE_INPUT","AI_LAYOUT_SITE_MOTION_INPUT","aiLayoutSiteMotionOf","value","style","seed","Number","isFinite","kind","motion","aiJobUsesLayoutLanguage","job","inputs","AI_LAYOUT_LANGUAGE_THINKING","thinking","effort","AI_LAYOUT_PAGE_THINKING_TOKENS","AI_LAYOUT_FRAME_THINKING_TOKENS","AI_JOB_PAGE_LANGUAGE_TOKENS","AI_LAYOUT_SECTION_MOST_TOKENS","AI_JOB_PAGE_LANGUAGE_FOLLOW_UP_TOKENS","AI_JOB_PAGE_LANGUAGE_BUDGET","tier","maxTokens","ownReadsMs","AI_LAYOUT_PAGE_KIND","AI_JOB_PAGE_LANGUAGE_INSTRUCTIONS","text","join","cacheBreakpoint","aiLayoutFormPageOfPlan","plan","formIds","placing","created","Set","create","filter","entry","map","name","toLowerCase","forms","screens","id","sections","some","section","uses","ref","has","screen","find","slug","aiLayoutFacts","aiLayoutImportedPageOf","values","Object","imported","brief","aiLayoutPageTargets","input","own","inventory","planned","pages","alias","page","row","template","label","formPage","pageId","includes","homeIds","form","formPageId","components","component","props","facts","contact","listings","aiLayoutListingsWithDatasets","flatMap","listing","datasets","dataset","datasetId","imageField","addressField","recordBase","fields","length","index","fieldIds","type","field","aiLayoutListingContext","context","targets","formScreenIds","here","placements","placement","screenId","tokens","href","bindingTokens","AI_LAYOUT_START_PAGE_MAX_CHARS","aiLayoutStartPageLines","start","trim","shown","slice","trimEnd","AI_LAYOUT_IMPORTED_PAGE_INPUT","AI_LAYOUT_IMPORTED_PAGE_MAX_CHARS","raw","url","aiLayoutImportedPageLines","maxChars","aiJobPageLanguageInstructions","aiLayoutFormLine","ids","placed","undefined","aiLayoutPagePrompt","places","listed","names","records","items","standsInFor","keys","title","startsFrom","reusableComponents","$id","aiLayoutDesignOf","home","aiLayoutMotionSiteOf","stored","aiLayoutMissingSectionsPrompt","missing","base","aiLayoutMissingSections","kept","AI_LAYOUT_SECTION_MISSING_CODE","AI_LAYOUT_SECTION_EMPTY_CODE","leastItems","aiLayoutShownItems","itemIds","storedIds","nodes","aiLayoutShortItemSections","quotesOnly","least","aiLayoutLeftOutNote","sectionIds","aiLayoutEmptyItemSections","emptied","short","rule","code","message","detail","aiLayoutRepeatsSaidInTheLanguage","violations","parentOf","Map","node","entries","child","set","sectionOf","at","get","indexOf","violation","where","nodeIds","sort","a","b","aiLayoutPageCheck","fills","only","_","answers","answer","last","reading","forEach","position","compiled","design","language","tree","ok","console","error","copy","dropped","rootId","ownScreenIds","without","why","push","promised","promisesAllowed","promisedOut","report","scrollTargetIds","repeatsCompiled","load","settled","spentTogether","first","second","usage","inputTokens","outputTokens","cacheReadTokens","cacheWriteTokens","attempts","estCostUsd","Math","round","model","stopReason","aiRunLayoutPage","observe","check","ask","content","step","instructions","messages","role","tool","cutOff","noun","smaller","signal","status","every","min"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,2CAA0C;AACjF,SAASC,kBAAkB,EAAEC,mBAAmB,QAAQ,0CAAyC;AAEjG,SAASC,cAAc,QAAgC,4BAAwB;AAE/E,SACEC,eAAe,QAEV,gCAA4B;AACnC,SAASC,6BAA6B,EAAEC,mBAAmB,QAAQ,2CAAuC;AAC1G,SAASC,iBAAiB,EAAEC,gBAAgB,QAAgC,yCAAqC;AACjH,SAASC,iBAAiB,EAAEC,kBAAkB,EAAEC,kBAAkB,QAA8B,2CAAuC;AACvI,SACEC,uBAAuB,EACvBC,mBAAmB,EACnBC,gBAAgB,QAGX,2CAAuC;AAK9C,SAASC,iBAAiB,EAAEC,uBAAuB,QAAQ,uCAAmC;AAC9F,SAASC,8BAA8B,EAAEC,wBAAwB,QAAQ,gDAA4C;AACrH,SAASC,kBAAkB,QAAQ,wCAAoC;AACvE,SAASC,0BAA0B,QAAQ,qCAAiC;AAC5E,SAASC,aAAa,QAAQ,0BAAsB;AACpD,SAASC,mBAAmB,QAAQ,mCAA+B;AACnE,SACEC,sBAAsB,QAIjB,4BAAwB;AAE/B,SACEC,uBAAuB,EACvBC,4BAA4B,EAC5BC,sBAAsB,QAIjB,uCAAmC;AAE1C,SAASC,qBAAqB,EAAEC,kBAAkB,QAAQ,4BAAwB;AAClF,SAASC,UAAU,QAAQ,2BAAuB;AAElD,SAASC,aAAa,QAAQ,wBAAoB;AAElD,SAASC,6BAA6B,EAAEC,eAAe,QAAQ,qBAAiB;AAChF,SAASC,cAAc,EAAEC,oBAAoB,QAAQ,yBAAqB;AAC1E,SAASC,kBAAkB,EAAEC,mBAAmB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;gBACrD5C,QAAQoI,qBAAqBhF,MAAMlD,GAAG,EAAEkD,MAAMV,MAAM,CAACE,IAAI;eACrDsI,OAAO;gBAAEA;YAAK,IAAI,CAAC,GACnB9H,MAAM9B,IAAI,CAACsK,QAAQ,GAAG;gBAAEA,UAAUxI,MAAM9B,IAAI,CAACsK,QAAQ;YAAC,IAAI,CAAC;gBAC/Da,iBAAiB/N,EAAAA,sBAAAA,mBAAmB0E,MAAMlD,GAAG,CAACC,MAAM,sBAAnCzB,oBAAsCyD,EAAE,MAAK;;WAG9DiB,MAAMuL,MAAM,GAAG;YAAEA,QAAQvL,MAAMuL,MAAM;QAAC,IAAI,CAAC;;IAEnD,MAAM1B,QAAQ,MAAMgB,IAAIzF,MAAM5H,4BAA4BE,SAAS,CAACsC,MAAMwK,KAAK;IAC/E,MAAMrF,UAAUE,wBAAwBC;IACxC,IACEuE,MAAM2B,MAAM,KAAK,iBACjB,CAACrG,QAAQnD,MAAM,IACf,CAAC6H,MAAMlD,UAAU,CAAC8E,KAAK,CAAC,CAACnE,YAAcA,UAAUf,IAAI,KAAKhB,iCAC1D;QACA,OAAOsE;IACT;IACA,MAAMC,SAAS,MAAMe,IACnB3F,8BAA8B;QAAEE;QAAM9F,QAAQU,MAAMV,MAAM;QAAE6F;IAAQ,IACpEmF,KAAKoB,GAAG,CAACnO,uCAAuCC,4BAA4BE,SAAS,CAACsC,MAAMwK,KAAK,IACjGrF;IAEF,OAAO,aAAK2E,QAAWF,cAAcC,OAAOC;AAC9C"}
@@ -24,7 +24,7 @@ import { type AiJobAdmission } from './ai-job-admission';
24
24
  import { readAiDraftNodes } from './ai-job-drafts';
25
25
  import { AI_JOB_PAGE_SECTION_MAX_TOKENS, AI_JOB_PAGE_SECTION_TOKENS, AI_JOB_PAGE_STEP_BUDGET, AI_JOB_PAGE_STEP_MINIMUM_MS, aiJobPageSectionMaxTokens } from './ai-job-page-budget';
26
26
  import { type AiLayoutPicturePhoto } from '../layout-language/ai-layout-pictures';
27
- import { aiLayoutStockPhotoSource } from './ai-layout-stock-photos';
27
+ import { aiLayoutSitePhotoSource } from './ai-layout-owner-photos';
28
28
  import { type AiLayoutStartPage } from './ai-job-page-language';
29
29
  import { type AiSiteUnit } from './ai-job-site-step';
30
30
  import type { AiJobStepRunner } from './ai-job-text-step';
@@ -252,7 +252,7 @@ export interface AiJobPageStepDeps {
252
252
  /** The runners a plan's creations are built by (AGL-3031); the registry's otherwise. */
253
253
  runnerFor?: typeof aiJobStepRunnerFor;
254
254
  /** The stock photo source of a language page's pictures (AGL-3660); core's provider otherwise. */
255
- stockPhotos?: typeof aiLayoutStockPhotoSource;
255
+ stockPhotos?: typeof aiLayoutSitePhotoSource;
256
256
  }
257
257
  export declare function createAiJobPageStep(deps?: AiJobPageStepDeps): AiJobStepRunner;
258
258
  export declare const runAiJobPageStep: AiJobStepRunner;
@@ -39,8 +39,8 @@ import { AI_JOB_PAGE_SECTION_MAX_TOKENS, AI_JOB_PAGE_SECTION_TOKENS, AI_JOB_PAGE
39
39
  import { AI_JOB_PAGE_INSTRUCTIONS, AI_PAGE_SECTION_TOOL, aiEmptyPage, aiPageCheckContext, aiPageLinkablePages, aiPageRecordNote, aiPageRecordTemplate, aiPageRecordTokens, aiPageSectionCheck, aiPageSectionNodeId, aiPageSectionPrompt, aiPageSectionSmaller, aiPageSectionWithRecordImage, aiPageWithSection } from "./ai-job-page-sections.js";
40
40
  import { aiLayoutSitePages } from "./ai-job-layout-site-pages.js";
41
41
  import { aiResolveLayoutPictures } from "../layout-language/ai-layout-pictures.js";
42
- import { aiLayoutSitePhotoSource } from "./ai-layout-owner-photos.js";
43
- import { AI_STOCK_PHOTO_AVOID_INPUT, AI_STOCK_PHOTO_JOB_PHOTOS_INPUT, AI_STOCK_PHOTO_PAGES_INPUT, aiStockJobPhotosOf, aiStockPhotoWordsOf, aiStockPlacedPhotos, aiStockPlacedSrcs } from "./ai-layout-stock-photos.js";
42
+ import { aiLayoutPagePhotosOf, aiLayoutSitePhotoSource } from "./ai-layout-owner-photos.js";
43
+ import { AI_STOCK_PHOTO_AVOID_INPUT, AI_STOCK_PHOTO_JOB_PHOTOS_INPUT, AI_STOCK_PHOTO_LATE_PASS_INPUT, AI_STOCK_PHOTO_PAGES_INPUT, aiStockJobPhotosOf, aiStockPhotoWordsOf, aiStockPlacedPhotos, aiStockPlacedSrcs } from "./ai-layout-stock-photos.js";
44
44
  import { AI_PLAN_ITEMS_MIN, aiPlanCopiedPageViolations } from "./ai-job-plan-conformance.js";
45
45
  import { AI_JOB_PAGE_LANGUAGE_BUDGET, aiJobUsesLayoutLanguage, aiLayoutListingContext, aiLayoutPageTargets, aiLayoutLeftOutNote, aiLayoutMotionSiteOf, aiRunLayoutPage } from "./ai-job-page-language.js";
46
46
  import { aiWithSiteMotion } from "../layout-language/ai-layout-motion.js";
@@ -814,6 +814,7 @@ export function createAiJobPageStep(deps = {}) {
814
814
  }
815
815
  if (language) {
816
816
  var _screen_id, _deps_stockPhotos;
817
+ var _job_inputs;
817
818
  // ── The whole page in one answer, in the layout language ──
818
819
  const targets = aiLayoutPageTargets({
819
820
  job,
@@ -863,6 +864,9 @@ export function createAiJobPageStep(deps = {}) {
863
864
  draftId
864
865
  });
865
866
  const photoWords = aiStockPhotoWordsOf(job);
867
+ // The pictures left on a starter, which a site start's late photo pass fills (AGL-3988).
868
+ const latePass = ((_job_inputs = job.inputs) == null ? void 0 : _job_inputs[AI_STOCK_PHOTO_LATE_PASS_INPUT]) === true;
869
+ let starters = [];
866
870
  const pictured = await aiResolveLayoutPictures(result.value.nodes, _extends({
867
871
  rootId: CANVAS_ROOT_ELEMENT_ID,
868
872
  sectionIds,
@@ -872,6 +876,10 @@ export function createAiJobPageStep(deps = {}) {
872
876
  jobPhotos
873
877
  } : {}, photoWords.language ? {
874
878
  language: photoWords.language
879
+ } : {}, latePass ? {
880
+ onStarters: (slots)=>{
881
+ starters = slots;
882
+ }
875
883
  } : {}, {
876
884
  // The owner's own photos first (AGL-3957), the stock library for the rest.
877
885
  source: ((_deps_stockPhotos = deps.stockPhotos) != null ? _deps_stockPhotos : aiLayoutSitePhotoSource)(_extends({
@@ -884,7 +892,10 @@ export function createAiJobPageStep(deps = {}) {
884
892
  jobId: aiOriginJobId(job)
885
893
  }, avoid.length ? {
886
894
  avoid
887
- } : {}, signal ? {
895
+ } : {}, {
896
+ // A page brought in from the owner's site places its own pictures first (AGL-3976).
897
+ pagePhotos: aiLayoutPagePhotosOf(job.inputs)
898
+ }, signal ? {
888
899
  signal
889
900
  } : {}))
890
901
  }));
@@ -925,9 +936,20 @@ export function createAiJobPageStep(deps = {}) {
925
936
  failure: AI_JOB_PAGE_DELETED_COPY
926
937
  });
927
938
  }
939
+ // Which of its pictures took a starter, by its draft: none clears what an earlier pass said.
928
940
  return _extends({}, spent, {
929
941
  continue: true
930
- });
942
+ }, latePass ? {
943
+ sitePhotos: {
944
+ pages: [
945
+ {
946
+ screen: draftId,
947
+ slots: starters
948
+ }
949
+ ],
950
+ lists: []
951
+ }
952
+ } : {});
931
953
  }
932
954
  const maxTokens = aiJobPageSectionMaxTokens(model);
933
955
  const maxElements = aiJobPageSectionMaxElements(maxTokens);