@aglyn/plugins-ai 1.0.0-beta.266 → 1.0.0-beta.269

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 (60) hide show
  1. package/package.json +18 -18
  2. package/src/lib/components/ai-job-site.d.ts +8 -1
  3. package/src/lib/components/ai-job-site.js +7 -0
  4. package/src/lib/components/ai-job-site.js.map +1 -1
  5. package/src/lib/components/ai-site-build-page.component.js +37 -0
  6. package/src/lib/components/ai-site-build-page.component.js.map +1 -1
  7. package/src/lib/components/ai-site-start-card.component.js +25 -6
  8. package/src/lib/components/ai-site-start-card.component.js.map +1 -1
  9. package/src/lib/components/ai-site-start-steps.component.d.ts +8 -2
  10. package/src/lib/components/ai-site-start-steps.component.js +55 -26
  11. package/src/lib/components/ai-site-start-steps.component.js.map +1 -1
  12. package/src/lib/components/ai-site-start-tracking.d.ts +11 -3
  13. package/src/lib/components/ai-site-start-tracking.js +28 -9
  14. package/src/lib/components/ai-site-start-tracking.js.map +1 -1
  15. package/src/lib/components/assist-jobs-drawer.component.js +24 -2
  16. package/src/lib/components/assist-jobs-drawer.component.js.map +1 -1
  17. package/src/lib/jobs/ai-empty-site-sweep.d.ts +154 -0
  18. package/src/lib/jobs/ai-empty-site-sweep.js +346 -0
  19. package/src/lib/jobs/ai-empty-site-sweep.js.map +1 -0
  20. package/src/lib/jobs/ai-job-page-language.d.ts +7 -1
  21. package/src/lib/jobs/ai-job-page-language.js +16 -3
  22. package/src/lib/jobs/ai-job-page-language.js.map +1 -1
  23. package/src/lib/jobs/ai-job-site-look.d.ts +2 -1
  24. package/src/lib/jobs/ai-job-site-look.js +6 -2
  25. package/src/lib/jobs/ai-job-site-look.js.map +1 -1
  26. package/src/lib/jobs/ai-job-site-step.js +11 -6
  27. package/src/lib/jobs/ai-job-site-step.js.map +1 -1
  28. package/src/lib/jobs/ai-jobs-beat.d.ts +11 -3
  29. package/src/lib/jobs/ai-jobs-beat.js +23 -6
  30. package/src/lib/jobs/ai-jobs-beat.js.map +1 -1
  31. package/src/lib/jobs/ai-jobs.js +46 -7
  32. package/src/lib/jobs/ai-jobs.js.map +1 -1
  33. package/src/lib/jobs/ai-layout-stock-photos.d.ts +43 -0
  34. package/src/lib/jobs/ai-layout-stock-photos.js +735 -22
  35. package/src/lib/jobs/ai-layout-stock-photos.js.map +1 -1
  36. package/src/lib/jobs/fixtures/ai-stock-photo-agl3923-recordings.d.ts +35 -0
  37. package/src/lib/jobs/fixtures/ai-stock-photo-agl3923-recordings.js +379 -0
  38. package/src/lib/jobs/fixtures/ai-stock-photo-agl3923-recordings.js.map +1 -0
  39. package/src/lib/jobs/fixtures/ai-stock-photo-brightvale-recordings.d.ts +35 -0
  40. package/src/lib/jobs/fixtures/ai-stock-photo-brightvale-recordings.js +294 -0
  41. package/src/lib/jobs/fixtures/ai-stock-photo-brightvale-recordings.js.map +1 -0
  42. package/src/lib/jobs/fixtures/ai-stock-photo-mexicano-recordings.d.ts +31 -0
  43. package/src/lib/jobs/fixtures/ai-stock-photo-mexicano-recordings.js +325 -0
  44. package/src/lib/jobs/fixtures/ai-stock-photo-mexicano-recordings.js.map +1 -0
  45. package/src/lib/layout-language/ai-layout-design.js +5 -0
  46. package/src/lib/layout-language/ai-layout-design.js.map +1 -1
  47. package/src/lib/layout-language/ai-layout-motion.d.ts +60 -7
  48. package/src/lib/layout-language/ai-layout-motion.js +231 -4
  49. package/src/lib/layout-language/ai-layout-motion.js.map +1 -1
  50. package/src/lib/layout-language/ai-layout-pictures.d.ts +8 -0
  51. package/src/lib/layout-language/ai-layout-pictures.js +68 -4
  52. package/src/lib/layout-language/ai-layout-pictures.js.map +1 -1
  53. package/src/lib/model/ai-jobs.types.d.ts +20 -0
  54. package/src/lib/model/ai-jobs.types.js.map +1 -1
  55. package/src/lib/model/ai-site-look.d.ts +10 -1
  56. package/src/lib/model/ai-site-look.js +14 -3
  57. package/src/lib/model/ai-site-look.js.map +1 -1
  58. package/src/lib/model/ai-site-start-handoff.d.ts +49 -0
  59. package/src/lib/model/ai-site-start-handoff.js +88 -0
  60. package/src/lib/model/ai-site-start-handoff.js.map +1 -0
@@ -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 { aiWithSiteMotion } 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'\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/** 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 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.\n */\nexport function aiLayoutMotionSiteOf(job: Pick<AiJob, '$id' | 'inputs'>, slug: string): { kind?: string; seed: number } {\n return aiLayoutDesignOf(job, slug) ?? { seed: aiSiteSeed(aiOriginJobId(job)) }\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?: { kind?: string; seed: number }\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 * 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 ...report.violations,\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","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","AI_LAYOUT_LANGUAGE_INPUT","AI_LAYOUT_FORM_PAGE_INPUT","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","kind","map","name","toLowerCase","forms","screens","id","sections","some","section","uses","ref","has","screen","find","slug","aiLayoutFacts","values","Object","value","brief","aiLayoutPageTargets","input","own","inventory","planned","pages","alias","page","row","template","label","formPage","pageId","includes","homeIds","form","formPageId","components","component","props","facts","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","style","seed","Number","isFinite","home","aiLayoutMotionSiteOf","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","aiLayoutPageCheck","fills","only","_","answers","answer","last","reading","forEach","position","violations","compiled","design","language","stored","tree","ok","console","error","copy","dropped","rootId","ownScreenIds","without","why","push","promised","promisesAllowed","promisedOut","report","scrollTargetIds","repeatsCompiled","motion","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","violation","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,gBAAgB,QAAQ,yCAAqC;AACtE,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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;;IAEnD,MAAM1B,QAAQ,MAAMgB,IAAI1E,MAAMvH,4BAA4BE,SAAS,CAACsC,MAAMoJ,KAAK;IAC/E,MAAMtE,UAAUE,wBAAwBC;IACxC,IACEwD,MAAM2B,MAAM,KAAK,iBACjB,CAACtF,QAAQ/C,MAAM,IACf,CAAC0G,MAAM1B,UAAU,CAACsD,KAAK,CAAC,CAACC,YAAcA,UAAUpE,IAAI,KAAKhB,iCAC1D;QACA,OAAOuD;IACT;IACA,MAAMC,SAAS,MAAMe,IACnB5E,8BAA8B;QAAEE;QAAMxF,QAAQS,MAAMT,MAAM;QAAEuF;IAAQ,IACpEoE,KAAKqB,GAAG,CAAChN,uCAAuCC,4BAA4BE,SAAS,CAACsC,MAAMoJ,KAAK,IACjGtE;IAEF,OAAO,aAAK4D,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 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'\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/** 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 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.\n */\nexport function aiLayoutMotionSiteOf(\n job: Pick<AiJob, '$id' | 'inputs'>,\n slug: string,\n): { kind?: string; seed: number; motion?: AiSiteMotionStyle } {\n const style = job.inputs?.['siteStyle'] as Record<string, unknown> | undefined\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?: { kind?: string; seed: number; motion?: AiSiteMotionStyle }\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 * 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 ...report.violations,\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","AI_LAYOUT_LANGUAGE_INPUT","AI_LAYOUT_FORM_PAGE_INPUT","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","kind","map","name","toLowerCase","forms","screens","id","sections","some","section","uses","ref","has","screen","find","slug","aiLayoutFacts","values","Object","value","brief","aiLayoutPageTargets","input","own","inventory","planned","pages","alias","page","row","template","label","formPage","pageId","includes","homeIds","form","formPageId","components","component","props","facts","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","style","seed","Number","isFinite","home","aiLayoutMotionSiteOf","motion","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","aiLayoutPageCheck","fills","only","_","answers","answer","last","reading","forEach","position","violations","compiled","design","language","stored","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","violation","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,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,kBAA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,CAAC,CAACC,YAAcA,UAAUnE,IAAI,KAAKhB,iCAC1D;QACA,OAAOsD;IACT;IACA,MAAMC,SAAS,MAAMe,IACnB3E,8BAA8B;QAAEE;QAAMzF,QAAQS,MAAMT,MAAM;QAAEwF;IAAQ,IACpEmE,KAAKqB,GAAG,CAAChN,uCAAuCC,4BAA4BE,SAAS,CAACsC,MAAMoJ,KAAK,IACjGrE;IAEF,OAAO,aAAK2D,QAAWF,cAAcC,OAAOC;AAC9C"}
@@ -25,7 +25,8 @@ import { type AiJobStepContext, type AiJobStepOutcome } from './ai-job-text-step
25
25
  * A site's look, designed first (AGL-3660): the scaffold's theme unit.
26
26
  *
27
27
  * One short answer from the fast tier — the base theme, two hues, a ground,
28
- * a font pairing and the building blocks' styles, chosen for this business
28
+ * a font pairing, the building blocks' styles and how the pages move
29
+ * (AGL-3941), chosen for this business
29
30
  * within its kind — then code builds the theme (`ai-site-look.ts`) and saves
30
31
  * it the way Setup → Theme saves a pick and its edits: the base theme
31
32
  * selected, the site's own look as the override over it, and the style
@@ -23,6 +23,7 @@ import { listServerThemePresets } from "@aglyn/aglyn/plugin-manager/plugin-theme
23
23
  import { runThemeLibraryAction } from "@aglyn/tenant-data-admin/server/theme-library-write";
24
24
  import { AI_SITE_FONT_PAIRINGS, aiSiteKindFor, aiSiteKindOfInputs } from "../model/ai-site-kinds.js";
25
25
  import { AI_SITE_LOOK_TOOL, AI_SITE_LOOK_TOOL_NAME, aiReadSiteLook, aiSiteSeed, aiSiteStyleFor, aiSiteTheme } from "../model/ai-site-look.js";
26
+ import { AI_SITE_MOTION_STYLE_RANGES, aiSiteMotionStylesFor } from "../layout-language/ai-layout-motion.js";
26
27
  import { aiCatalogEntry, aiDefaultModelFor } from "../providers/catalog.js";
27
28
  import { aiModelForStep } from "../providers/routing.js";
28
29
  import { runValidatedGeneration } from "../runtime/ai-doctrine.js";
@@ -33,7 +34,8 @@ import { AI_JOB_BRIEF_MAX_CHARS } from "./ai-job-text-step.js";
33
34
  * A site's look, designed first (AGL-3660): the scaffold's theme unit.
34
35
  *
35
36
  * One short answer from the fast tier — the base theme, two hues, a ground,
36
- * a font pairing and the building blocks' styles, chosen for this business
37
+ * a font pairing, the building blocks' styles and how the pages move
38
+ * (AGL-3941), chosen for this business
37
39
  * within its kind — then code builds the theme (`ai-site-look.ts`) and saves
38
40
  * it the way Setup → Theme saves a pick and its edits: the base theme
39
41
  * selected, the site's own look as the override over it, and the style
@@ -62,7 +64,8 @@ import { AI_JOB_BRIEF_MAX_CHARS } from "./ai-job-text-step.js";
62
64
  '- Prefer a base theme, font pairing and corners from the lists the request gives for this kind of site; the lists are in no order, so weigh each for this business.',
63
65
  '- hue is the brand color and accent sits beside it; pick colors people would expect of this business, and let the design seed tip a close call.',
64
66
  '- A hex color written in the brief is the brand color: put it in brand. Otherwise brand is null.',
65
- '- Choose the building blocks to suit the kind: quiet, flat cards and small eyebrows for minimal sites; raised cards and capitals for bold ones; soft tinted cards for calm ones.'
67
+ '- Choose the building blocks to suit the kind: quiet, flat cards and small eyebrows for minimal sites; raised cards and capitals for bold ones; soft tinted cards for calm ones.',
68
+ '- motion is how the pages arrive as a visitor scrolls: choose from the motion list the request gives, for this business, never by habit; a quiet practice suits little motion, a lively studio more.'
66
69
  ].join('\n'),
67
70
  cacheBreakpoint: true
68
71
  }
@@ -102,6 +105,7 @@ import { AI_JOB_BRIEF_MAX_CHARS } from "./ai-job-text-step.js";
102
105
  `Base themes that suit it: ${shuffled(input.bases, seed).map((entry)=>`${entry.base} (${entry.words})`).join('; ')}.`,
103
106
  `Font pairings that suit it: ${shuffled(pairings, seed + 1).map((pairing)=>`${pairing.id} (${pairing.feel})`).join('; ')}.`,
104
107
  `Corners that suit it: ${kind.look.corners.join(', ')}. Its palette runs ${kind.look.chroma === 'neutral' ? 'neutral, ink and paper with one accent color' : kind.look.chroma}.`,
108
+ `Motion that suits it: ${shuffled(aiSiteMotionStylesFor(kind.id), seed + 2).map((motion)=>`${motion} (${AI_SITE_MOTION_STYLE_RANGES[motion].words})`).join('; ')}.`,
105
109
  `Design seed: ${job.$id.slice(-6)}.`
106
110
  ].filter(Boolean).join('\n');
107
111
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-site-look.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 { DEFAULT_SITE_THEME } from '@aglyn/aglyn/app-utils/default-site'\nimport { diffOverride, overrideWriteValue } from '@aglyn/aglyn/app-utils/artifact-overrides'\nimport { themeArtifactContent, type ThemeHostDocument } from '@aglyn/aglyn/app-utils/site-theme'\nimport { readThemeSelection, SITE_THEME_ENTRY_ID } from '@aglyn/aglyn/app-utils/theme-library'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport { listServerThemePresets } from '@aglyn/aglyn/plugin-manager/plugin-theme-presets'\nimport type { HostTheme } from '@aglyn/shared-data-types'\nimport { runThemeLibraryAction } from '@aglyn/tenant-data-admin/server/theme-library-write'\nimport type { AiJob, AiJobOutput } from '../model/ai-jobs.types'\nimport { AI_SITE_FONT_PAIRINGS, aiSiteKindFor, aiSiteKindOfInputs, type AiSiteBase, type AiSiteKind } from '../model/ai-site-kinds'\nimport {\n AI_SITE_LOOK_TOOL,\n AI_SITE_LOOK_TOOL_NAME,\n aiReadSiteLook,\n aiSiteSeed,\n aiSiteStyleFor,\n aiSiteTheme,\n type AiSiteLookAnswer,\n type AiSiteStyle,\n} from '../model/ai-site-look'\nimport { aiCatalogEntry, aiDefaultModelFor } from '../providers/catalog'\nimport { aiModelForStep } from '../providers/routing'\nimport { runValidatedGeneration, type AiGenerationCheck } from '../runtime/ai-doctrine'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiGenerationSpent, aiUnspentOutcome } from './ai-job-generation'\nimport { AI_JOB_BRIEF_MAX_CHARS, type AiJobStepContext, type AiJobStepOutcome } from './ai-job-text-step'\n\n/**\n * A site's look, designed first (AGL-3660): the scaffold's theme unit.\n *\n * One short answer from the fast tier — the base theme, two hues, a ground,\n * a font pairing and the building blocks' styles, chosen for this business\n * within its kind — then code builds the theme (`ai-site-look.ts`) and saves\n * it the way Setup → Theme saves a pick and its edits: the base theme\n * selected, the site's own look as the override over it, and the style\n * tokens on the site for later edits to keep. The header, the footer and\n * every page are built after it, so they render in it from their first draft.\n *\n * The look never fails a site. An answer that could not be read leaves the\n * kind and the seed to choose; a site whose owner already changed its theme\n * keeps it.\n */\n\n/** The answer is a dozen short values, about 150 tokens; the ceiling leaves room to spare. */\nexport const AI_SITE_LOOK_MAX_TOKENS = 600\n\n/** A look pass's time, on the fast tier the look is asked on. */\nexport const AI_SITE_LOOK_BUDGET = aiJobStepBudget({ tier: 'fast', maxTokens: AI_SITE_LOOK_MAX_TOKENS })\n\n/**\n * The generation kind a look is asked under: values code builds a theme\n * from, composing nothing, so the doctrine's short fields block leads it.\n */\nexport const AI_SITE_LOOK_KIND = 'site-look'\n\n/** The base themes as the model reads them; `starter` is the one a new site is born with. */\nconst STARTER_WORDS = 'the starter theme a new site is born with: a soft neutral ground, rounder corners and calm buttons'\n\n/** The look door's cached instructions. */\nexport const AI_SITE_LOOK_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n \"You choose the look of a new small-business website: the platform's base theme it starts from, and the choices that make it this business's own.\",\n `Answer by calling ${AI_SITE_LOOK_TOOL_NAME} exactly once, at once, and write nothing else: no reasoning, no prose.`,\n '- Choose for this business, its audience and its kind of site, never a default: a roofer and a florist should not share a color, a law firm and a yoga studio should not share a typeface.',\n '- Prefer a base theme, font pairing and corners from the lists the request gives for this kind of site; the lists are in no order, so weigh each for this business.',\n '- hue is the brand color and accent sits beside it; pick colors people would expect of this business, and let the design seed tip a close call.',\n '- A hex color written in the brief is the brand color: put it in brand. Otherwise brand is null.',\n '- Choose the building blocks to suit the kind: quiet, flat cards and small eyebrows for minimal sites; raised cards and capitals for bold ones; soft tinted cards for calm ones.',\n ].join('\\n'),\n cacheBreakpoint: true,\n },\n]\n\n/** A list in a seed's order (Fisher–Yates over a small LCG). */\nfunction shuffled<T>(list: readonly T[], seed: number): T[] {\n const out = [...list]\n let state = seed >>> 0 || 1\n for (let index = out.length - 1; index > 0; index -= 1) {\n state = (Math.imul(state, 1664525) + 1013904223) >>> 0\n const other = state % (index + 1)\n ;[out[index], out[other]] = [out[other] as T, out[index] as T]\n }\n return out\n}\n\n/** The look's user turn: the site, its kind and what suits it, and the seed. */\nexport function aiSiteLookPrompt(input: {\n job: Pick<AiJob, 'brief' | '$id' | 'inputs'>\n kind: AiSiteKind\n bases: ReadonlyArray<{ base: AiSiteBase; words: string }>\n}): string {\n const { job, kind } = input\n const text = (key: string) => (typeof job.inputs?.[key] === 'string' ? (job.inputs[key] as string).trim() : '')\n const pairings = AI_SITE_FONT_PAIRINGS.filter((pairing) => kind.look.fonts.includes(pairing.id))\n // The lists in the job's own order: a model reads the first of a list as\n // the answer, and every site of a kind would get the same base and type.\n const seed = aiSiteSeed(job.$id)\n return [\n `Kind of site: ${kind.label}. ${kind.design}`,\n text('businessName') ? `Business name: ${text('businessName')}` : '',\n text('businessType') ? `Business: ${text('businessType')}` : '',\n text('audience') ? `For: ${text('audience')}` : '',\n text('brand') ? `Brand: ${text('brand')}` : '',\n `Brief: ${job.brief.slice(0, AI_JOB_BRIEF_MAX_CHARS)}`,\n `Base themes that suit it: ${shuffled(input.bases, seed).map((entry) => `${entry.base} (${entry.words})`).join('; ')}.`,\n `Font pairings that suit it: ${shuffled(pairings, seed + 1).map((pairing) => `${pairing.id} (${pairing.feel})`).join('; ')}.`,\n `Corners that suit it: ${kind.look.corners.join(', ')}. Its palette runs ${kind.look.chroma === 'neutral' ? 'neutral, ink and paper with one accent color' : kind.look.chroma}.`,\n `Design seed: ${job.$id.slice(-6)}.`,\n ]\n .filter(Boolean)\n .join('\\n')\n}\n\n/** The answer, read leniently; a call with nothing usable is still an answer, and the seed fills it. */\nexport const aiSiteLookCheck: AiGenerationCheck<AiSiteLookAnswer> = (answer) => ({\n value: aiReadSiteLook(answer),\n violations: [],\n})\n\n/** The model a look is asked on: the fast tier of the job's provider, unless the creator picked a model. */\nexport function aiSiteLookModel(job: Pick<AiJob, 'model'>, resolved: string | undefined): string {\n const fallback = resolved ?? aiModelForStep('job.theme')\n const picked = typeof job.model === 'string' ? job.model.trim() : ''\n if (picked && picked !== 'auto') return fallback\n const entry = aiCatalogEntry(fallback)\n return (entry ? aiDefaultModelFor(entry.provider, 'fast') : undefined) ?? fallback\n}\n\n/** The preset id a base names. */\nexport const aiSiteBasePresetId = (base: AiSiteBase) => `theme-presets.${base}`\n\n/** The bases a kind suits that this deployment has, best first, with what each looks like. */\nexport function aiSiteLookBases(kind: AiSiteKind): Array<{ base: AiSiteBase; words: string }> {\n const presets = listServerThemePresets()\n return kind.look.bases.flatMap((base): Array<{ base: AiSiteBase; words: string }> => {\n if (base === 'starter') return [{ base, words: STARTER_WORDS }]\n const preset = presets.find((entry) => entry.id === aiSiteBasePresetId(base))\n return preset ? [{ base, words: preset.description ?? preset.name }] : []\n })\n}\n\n/** Plain JSON, deep-sorted, for comparing two themes as stored. */\nfunction stable(value: unknown): string {\n return JSON.stringify(value, (_key, inner) =>\n inner && typeof inner === 'object' && !Array.isArray(inner)\n ? Object.fromEntries(Object.entries(inner as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b)))\n : inner,\n )\n}\n\n/**\n * Whether a site still has the theme it was born with (AGL-3497), or none:\n * the only theme a look may replace. A site whose owner picked a theme, edited\n * one, or installed one keeps it.\n */\nexport function aiSiteThemeUntouched(host: ThemeHostDocument & Record<string, unknown>): boolean {\n if (host.themeOverride) return false\n const selection = readThemeSelection(host)\n if (selection.kind === 'default') return true\n if (selection.kind !== 'custom' || selection.id !== SITE_THEME_ENTRY_ID) return false\n return stable(themeArtifactContent(host.theme)) === stable(themeArtifactContent(DEFAULT_SITE_THEME))\n}\n\nexport type AiSiteThemeWrite = 'applied' | 'kept' | 'missing'\n\n/**\n * Saves a look on its site in one transaction: the base theme picked through\n * the theme library (so the site's starter theme is filed in its library, as\n * a person's switch files it), the look as the override over the base, and\n * the style tokens. Again for the same job is a no-op.\n */\nexport async function aiSaveSiteTheme(\n firestore: FirebaseFirestore.Firestore,\n input: { hostId: string; jobId: string; style: AiSiteStyle },\n): Promise<{ write: AiSiteThemeWrite; baseName: string }> {\n const hostRef = firestore.collection('hosts').doc(input.hostId)\n const preset =\n input.style.base === 'starter'\n ? null\n : (listServerThemePresets().find((entry) => entry.id === aiSiteBasePresetId(input.style.base)) ?? null)\n const base: HostTheme = preset ? themeArtifactContent(preset.theme) : DEFAULT_SITE_THEME\n const baseName = preset?.name ?? 'Site theme'\n const edited = aiSiteTheme({ ...input.style, base: preset ? input.style.base : 'starter' }, base)\n const override = overrideWriteValue(diffOverride(base, edited), null)\n const siteStyle = { ...input.style, base: preset ? input.style.base : 'starter', jobId: input.jobId }\n const write = await firestore.runTransaction(async (tx): Promise<AiSiteThemeWrite> => {\n const snapshot = await tx.get(hostRef)\n if (!snapshot.exists) return 'missing'\n const host = snapshot.data() as ThemeHostDocument & Record<string, unknown>\n const stored = host['siteStyle'] as { jobId?: unknown } | undefined\n if (stored?.jobId === input.jobId) return 'applied'\n if (!aiSiteThemeUntouched(host)) return 'kept'\n const extra = { themeOverride: override, siteStyle }\n if (preset) {\n const plan = await runThemeLibraryAction(\n tx,\n hostRef,\n { action: 'select', target: { kind: 'preset', id: preset.id, name: preset.name, theme: base } },\n extra,\n )\n if (plan.ok === false) throw new Error(`the site's base theme could not be picked: ${plan.error}`)\n } else {\n tx.update(hostRef, { theme: DEFAULT_SITE_THEME, ...extra })\n }\n return 'applied'\n })\n if (write === 'applied') {\n // The theme is live the moment it is written; cached pages go now.\n await dropPluginSiteCache({ hostIds: [input.hostId], reason: 'ai site look' })\n }\n return { write, baseName }\n}\n\n/** The sentence a look's row and output carry. */\nfunction lookLabel(style: AiSiteStyle, baseName: string): string {\n const pairing = AI_SITE_FONT_PAIRINGS.find((entry) => entry.id === style.fonts)\n return `Your look: ${baseName} base, ${pairing ? `${pairing.heading.family} type` : 'its own type'}, ${style.cards} cards`\n}\n\nexport interface AiSiteLookDeps {\n save?: typeof aiSaveSiteTheme\n generate?: typeof runValidatedGeneration\n others?: typeof aiWorkspaceSiteStyles\n}\n\n/** The most of a workspace's sites a look is drawn apart from. */\nexport const AI_SITE_LOOK_SIBLINGS = 50\n\n/**\n * The looks of a workspace's other sites (AGL-3660), so a new one is drawn\n * apart from each: none shares their base, hue family, heading font and\n * buttons. A read that fails draws apart from nothing.\n */\nexport async function aiWorkspaceSiteStyles(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; hostId: string },\n): Promise<AiSiteStyle[]> {\n try {\n const snapshot = await firestore\n .collection('hosts')\n .where('orgId', '==', input.orgId)\n .limit(AI_SITE_LOOK_SIBLINGS)\n .get()\n return snapshot.docs.flatMap((doc) => {\n const style = doc.get('siteStyle') as AiSiteStyle | undefined\n return doc.id !== input.hostId && style && typeof style.base === 'string' ? [style] : []\n })\n } catch (error) {\n console.warn('ai site look: the workspace sites could not be read; drawing apart from none', { orgId: input.orgId, error })\n return []\n }\n}\n\n/**\n * The theme unit's pass: ask for the look, build it, save it. `job` is the\n * unit's derived job, carrying the scaffold's inputs and its origin job id,\n * which is what the seed is drawn from — so a resumed pass draws the same.\n */\nexport async function aiRunSiteLook(\n context: AiJobStepContext,\n job: AiJob,\n deps: AiSiteLookDeps = {},\n): Promise<AiJobStepOutcome> {\n const save = deps.save ?? aiSaveSiteTheme\n const generate = deps.generate ?? runValidatedGeneration\n const model = aiSiteLookModel(job, context.modelFor?.('job.theme'))\n if (!job.hostId) return { ...aiUnspentOutcome(model), failure: 'This site job names no site.' }\n const kind = aiSiteKindOfInputs(job.inputs) ?? aiSiteKindFor(job.brief)\n const origin = typeof job.inputs?.['originJobId'] === 'string' ? (job.inputs['originJobId'] as string) : job.$id\n const result = await generate<AiSiteLookAnswer>(AI_SITE_LOOK_KIND, {\n step: 'job.theme',\n model,\n instructions: AI_SITE_LOOK_INSTRUCTIONS as AiSystemBlock[],\n messages: [{ role: 'user', content: aiSiteLookPrompt({ job: { ...job, $id: origin }, kind, bases: aiSiteLookBases(kind) }) }],\n tool: AI_SITE_LOOK_TOOL,\n maxTokens: AI_SITE_LOOK_BUDGET.maxTokens(model),\n thinking: 'off',\n check: aiSiteLookCheck,\n ...(context.signal ? { signal: context.signal } : {}),\n })\n const spent = aiGenerationSpent(result)\n if (result.status === 'refused') return { ...spent, refused: true }\n // An answer that could not be used leaves the kind and the seed to choose.\n const answer = result.status === 'ok' ? result.value : {}\n const brand = typeof job.inputs?.['brand'] === 'string' ? (job.inputs['brand'] as string) : null\n const others = deps.others ?? aiWorkspaceSiteStyles\n const avoid = await others(context.firestore, { orgId: job.orgId, hostId: job.hostId })\n const style = aiSiteStyleFor({ kind, answer, seed: aiSiteSeed(origin), brand, avoid })\n const saved = await save(context.firestore, { hostId: job.hostId, jobId: origin, style })\n if (saved.write === 'missing') throw new Error(`site ${job.hostId} vanished while its look was chosen`)\n const output: AiJobOutput = {\n resource: 'theme',\n id: 'look',\n hostId: job.hostId,\n label:\n saved.write === 'kept'\n ? 'Kept the theme you chose for this site'\n : lookLabel(style, saved.baseName),\n proposal: JSON.parse(JSON.stringify({ style, write: saved.write })) as Record<string, unknown>,\n }\n return { ...spent, outputs: [output] }\n}\n"],"names":["DEFAULT_SITE_THEME","diffOverride","overrideWriteValue","themeArtifactContent","readThemeSelection","SITE_THEME_ENTRY_ID","dropPluginSiteCache","listServerThemePresets","runThemeLibraryAction","AI_SITE_FONT_PAIRINGS","aiSiteKindFor","aiSiteKindOfInputs","AI_SITE_LOOK_TOOL","AI_SITE_LOOK_TOOL_NAME","aiReadSiteLook","aiSiteSeed","aiSiteStyleFor","aiSiteTheme","aiCatalogEntry","aiDefaultModelFor","aiModelForStep","runValidatedGeneration","aiJobStepBudget","aiGenerationSpent","aiUnspentOutcome","AI_JOB_BRIEF_MAX_CHARS","AI_SITE_LOOK_MAX_TOKENS","AI_SITE_LOOK_BUDGET","tier","maxTokens","AI_SITE_LOOK_KIND","STARTER_WORDS","AI_SITE_LOOK_INSTRUCTIONS","text","join","cacheBreakpoint","shuffled","list","seed","out","state","index","length","Math","imul","other","aiSiteLookPrompt","input","job","kind","key","inputs","trim","pairings","filter","pairing","look","fonts","includes","id","$id","label","design","brief","slice","bases","map","entry","base","words","feel","corners","chroma","Boolean","aiSiteLookCheck","answer","value","violations","aiSiteLookModel","resolved","fallback","picked","model","provider","undefined","aiSiteBasePresetId","aiSiteLookBases","presets","flatMap","preset","find","description","name","stable","JSON","stringify","_key","inner","Array","isArray","Object","fromEntries","entries","sort","a","b","localeCompare","aiSiteThemeUntouched","host","themeOverride","selection","theme","aiSaveSiteTheme","firestore","hostRef","collection","doc","hostId","style","baseName","edited","override","siteStyle","jobId","write","runTransaction","tx","snapshot","get","exists","data","stored","extra","plan","action","target","ok","Error","error","update","hostIds","reason","lookLabel","heading","family","cards","AI_SITE_LOOK_SIBLINGS","aiWorkspaceSiteStyles","where","orgId","limit","docs","console","warn","aiRunSiteLook","context","deps","save","generate","modelFor","failure","origin","result","step","instructions","messages","role","content","tool","thinking","check","signal","spent","status","refused","brand","others","avoid","saved","output","resource","proposal","parse","outputs"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,sCAAqC;AACxE,SAASC,YAAY,EAAEC,kBAAkB,QAAQ,4CAA2C;AAC5F,SAASC,oBAAoB,QA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AAMnG,SAASuF,OAAOW,MAAM,KAAK,OAAOX,OAAOtF,KAAK,GAAG,CAAC;IACxD,MAAMmG,QAAQ,SAAO/H,eAAAA,IAAIG,MAAM,qBAAVH,YAAY,CAAC,QAAQ,MAAK,WAAYA,IAAIG,MAAM,CAAC,QAAQ,GAAc;IAC5F,MAAM6H,UAASpB,eAAAA,KAAKoB,MAAM,YAAXpB,eAAeT;IAC9B,MAAM8B,QAAQ,MAAMD,OAAOrB,QAAQ1C,SAAS,EAAE;QAAEoC,OAAOrG,IAAIqG,KAAK;QAAEhC,QAAQrE,IAAIqE,MAAM;IAAC;IACrF,MAAMC,QAAQtG,eAAe;QAAEiC;QAAM0B;QAAQrC,MAAMvB,WAAWkJ;QAASc;QAAOE;IAAM;IACpF,MAAMC,QAAQ,MAAMrB,KAAKF,QAAQ1C,SAAS,EAAE;QAAEI,QAAQrE,IAAIqE,MAAM;QAAEM,OAAOsC;QAAQ3C;IAAM;IACvF,IAAI4D,MAAMtD,KAAK,KAAK,WAAW,MAAM,IAAIa,MAAM,CAAC,KAAK,EAAEzF,IAAIqE,MAAM,CAAC,mCAAmC,CAAC;IACtG,MAAM8D,SAAsB;QAC1BC,UAAU;QACVzH,IAAI;QACJ0D,QAAQrE,IAAIqE,MAAM;QAClBxD,OACEqH,MAAMtD,KAAK,KAAK,SACZ,2CACAkB,UAAUxB,OAAO4D,MAAM3D,QAAQ;QACrC8D,UAAUvF,KAAKwF,KAAK,CAACxF,KAAKC,SAAS,CAAC;YAAEuB;YAAOM,OAAOsD,MAAMtD,KAAK;QAAC;IAClE;IACA,OAAO,aAAKgD;QAAOW,SAAS;YAACJ;SAAO;;AACtC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-site-look.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 { DEFAULT_SITE_THEME } from '@aglyn/aglyn/app-utils/default-site'\nimport { diffOverride, overrideWriteValue } from '@aglyn/aglyn/app-utils/artifact-overrides'\nimport { themeArtifactContent, type ThemeHostDocument } from '@aglyn/aglyn/app-utils/site-theme'\nimport { readThemeSelection, SITE_THEME_ENTRY_ID } from '@aglyn/aglyn/app-utils/theme-library'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport { listServerThemePresets } from '@aglyn/aglyn/plugin-manager/plugin-theme-presets'\nimport type { HostTheme } from '@aglyn/shared-data-types'\nimport { runThemeLibraryAction } from '@aglyn/tenant-data-admin/server/theme-library-write'\nimport type { AiJob, AiJobOutput } from '../model/ai-jobs.types'\nimport { AI_SITE_FONT_PAIRINGS, aiSiteKindFor, aiSiteKindOfInputs, type AiSiteBase, type AiSiteKind } from '../model/ai-site-kinds'\nimport {\n AI_SITE_LOOK_TOOL,\n AI_SITE_LOOK_TOOL_NAME,\n aiReadSiteLook,\n aiSiteSeed,\n aiSiteStyleFor,\n aiSiteTheme,\n type AiSiteLookAnswer,\n type AiSiteStyle,\n} from '../model/ai-site-look'\nimport { AI_SITE_MOTION_STYLE_RANGES, aiSiteMotionStylesFor } from '../layout-language/ai-layout-motion'\nimport { aiCatalogEntry, aiDefaultModelFor } from '../providers/catalog'\nimport { aiModelForStep } from '../providers/routing'\nimport { runValidatedGeneration, type AiGenerationCheck } from '../runtime/ai-doctrine'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiGenerationSpent, aiUnspentOutcome } from './ai-job-generation'\nimport { AI_JOB_BRIEF_MAX_CHARS, type AiJobStepContext, type AiJobStepOutcome } from './ai-job-text-step'\n\n/**\n * A site's look, designed first (AGL-3660): the scaffold's theme unit.\n *\n * One short answer from the fast tier — the base theme, two hues, a ground,\n * a font pairing, the building blocks' styles and how the pages move\n * (AGL-3941), chosen for this business\n * within its kind — then code builds the theme (`ai-site-look.ts`) and saves\n * it the way Setup → Theme saves a pick and its edits: the base theme\n * selected, the site's own look as the override over it, and the style\n * tokens on the site for later edits to keep. The header, the footer and\n * every page are built after it, so they render in it from their first draft.\n *\n * The look never fails a site. An answer that could not be read leaves the\n * kind and the seed to choose; a site whose owner already changed its theme\n * keeps it.\n */\n\n/** The answer is a dozen short values, about 150 tokens; the ceiling leaves room to spare. */\nexport const AI_SITE_LOOK_MAX_TOKENS = 600\n\n/** A look pass's time, on the fast tier the look is asked on. */\nexport const AI_SITE_LOOK_BUDGET = aiJobStepBudget({ tier: 'fast', maxTokens: AI_SITE_LOOK_MAX_TOKENS })\n\n/**\n * The generation kind a look is asked under: values code builds a theme\n * from, composing nothing, so the doctrine's short fields block leads it.\n */\nexport const AI_SITE_LOOK_KIND = 'site-look'\n\n/** The base themes as the model reads them; `starter` is the one a new site is born with. */\nconst STARTER_WORDS = 'the starter theme a new site is born with: a soft neutral ground, rounder corners and calm buttons'\n\n/** The look door's cached instructions. */\nexport const AI_SITE_LOOK_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n \"You choose the look of a new small-business website: the platform's base theme it starts from, and the choices that make it this business's own.\",\n `Answer by calling ${AI_SITE_LOOK_TOOL_NAME} exactly once, at once, and write nothing else: no reasoning, no prose.`,\n '- Choose for this business, its audience and its kind of site, never a default: a roofer and a florist should not share a color, a law firm and a yoga studio should not share a typeface.',\n '- Prefer a base theme, font pairing and corners from the lists the request gives for this kind of site; the lists are in no order, so weigh each for this business.',\n '- hue is the brand color and accent sits beside it; pick colors people would expect of this business, and let the design seed tip a close call.',\n '- A hex color written in the brief is the brand color: put it in brand. Otherwise brand is null.',\n '- Choose the building blocks to suit the kind: quiet, flat cards and small eyebrows for minimal sites; raised cards and capitals for bold ones; soft tinted cards for calm ones.',\n '- motion is how the pages arrive as a visitor scrolls: choose from the motion list the request gives, for this business, never by habit; a quiet practice suits little motion, a lively studio more.',\n ].join('\\n'),\n cacheBreakpoint: true,\n },\n]\n\n/** A list in a seed's order (Fisher–Yates over a small LCG). */\nfunction shuffled<T>(list: readonly T[], seed: number): T[] {\n const out = [...list]\n let state = seed >>> 0 || 1\n for (let index = out.length - 1; index > 0; index -= 1) {\n state = (Math.imul(state, 1664525) + 1013904223) >>> 0\n const other = state % (index + 1)\n ;[out[index], out[other]] = [out[other] as T, out[index] as T]\n }\n return out\n}\n\n/** The look's user turn: the site, its kind and what suits it, and the seed. */\nexport function aiSiteLookPrompt(input: {\n job: Pick<AiJob, 'brief' | '$id' | 'inputs'>\n kind: AiSiteKind\n bases: ReadonlyArray<{ base: AiSiteBase; words: string }>\n}): string {\n const { job, kind } = input\n const text = (key: string) => (typeof job.inputs?.[key] === 'string' ? (job.inputs[key] as string).trim() : '')\n const pairings = AI_SITE_FONT_PAIRINGS.filter((pairing) => kind.look.fonts.includes(pairing.id))\n // The lists in the job's own order: a model reads the first of a list as\n // the answer, and every site of a kind would get the same base and type.\n const seed = aiSiteSeed(job.$id)\n return [\n `Kind of site: ${kind.label}. ${kind.design}`,\n text('businessName') ? `Business name: ${text('businessName')}` : '',\n text('businessType') ? `Business: ${text('businessType')}` : '',\n text('audience') ? `For: ${text('audience')}` : '',\n text('brand') ? `Brand: ${text('brand')}` : '',\n `Brief: ${job.brief.slice(0, AI_JOB_BRIEF_MAX_CHARS)}`,\n `Base themes that suit it: ${shuffled(input.bases, seed).map((entry) => `${entry.base} (${entry.words})`).join('; ')}.`,\n `Font pairings that suit it: ${shuffled(pairings, seed + 1).map((pairing) => `${pairing.id} (${pairing.feel})`).join('; ')}.`,\n `Corners that suit it: ${kind.look.corners.join(', ')}. Its palette runs ${kind.look.chroma === 'neutral' ? 'neutral, ink and paper with one accent color' : kind.look.chroma}.`,\n `Motion that suits it: ${shuffled(aiSiteMotionStylesFor(kind.id), seed + 2).map((motion) => `${motion} (${AI_SITE_MOTION_STYLE_RANGES[motion].words})`).join('; ')}.`,\n `Design seed: ${job.$id.slice(-6)}.`,\n ]\n .filter(Boolean)\n .join('\\n')\n}\n\n/** The answer, read leniently; a call with nothing usable is still an answer, and the seed fills it. */\nexport const aiSiteLookCheck: AiGenerationCheck<AiSiteLookAnswer> = (answer) => ({\n value: aiReadSiteLook(answer),\n violations: [],\n})\n\n/** The model a look is asked on: the fast tier of the job's provider, unless the creator picked a model. */\nexport function aiSiteLookModel(job: Pick<AiJob, 'model'>, resolved: string | undefined): string {\n const fallback = resolved ?? aiModelForStep('job.theme')\n const picked = typeof job.model === 'string' ? job.model.trim() : ''\n if (picked && picked !== 'auto') return fallback\n const entry = aiCatalogEntry(fallback)\n return (entry ? aiDefaultModelFor(entry.provider, 'fast') : undefined) ?? fallback\n}\n\n/** The preset id a base names. */\nexport const aiSiteBasePresetId = (base: AiSiteBase) => `theme-presets.${base}`\n\n/** The bases a kind suits that this deployment has, best first, with what each looks like. */\nexport function aiSiteLookBases(kind: AiSiteKind): Array<{ base: AiSiteBase; words: string }> {\n const presets = listServerThemePresets()\n return kind.look.bases.flatMap((base): Array<{ base: AiSiteBase; words: string }> => {\n if (base === 'starter') return [{ base, words: STARTER_WORDS }]\n const preset = presets.find((entry) => entry.id === aiSiteBasePresetId(base))\n return preset ? [{ base, words: preset.description ?? preset.name }] : []\n })\n}\n\n/** Plain JSON, deep-sorted, for comparing two themes as stored. */\nfunction stable(value: unknown): string {\n return JSON.stringify(value, (_key, inner) =>\n inner && typeof inner === 'object' && !Array.isArray(inner)\n ? Object.fromEntries(Object.entries(inner as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b)))\n : inner,\n )\n}\n\n/**\n * Whether a site still has the theme it was born with (AGL-3497), or none:\n * the only theme a look may replace. A site whose owner picked a theme, edited\n * one, or installed one keeps it.\n */\nexport function aiSiteThemeUntouched(host: ThemeHostDocument & Record<string, unknown>): boolean {\n if (host.themeOverride) return false\n const selection = readThemeSelection(host)\n if (selection.kind === 'default') return true\n if (selection.kind !== 'custom' || selection.id !== SITE_THEME_ENTRY_ID) return false\n return stable(themeArtifactContent(host.theme)) === stable(themeArtifactContent(DEFAULT_SITE_THEME))\n}\n\nexport type AiSiteThemeWrite = 'applied' | 'kept' | 'missing'\n\n/**\n * Saves a look on its site in one transaction: the base theme picked through\n * the theme library (so the site's starter theme is filed in its library, as\n * a person's switch files it), the look as the override over the base, and\n * the style tokens. Again for the same job is a no-op.\n */\nexport async function aiSaveSiteTheme(\n firestore: FirebaseFirestore.Firestore,\n input: { hostId: string; jobId: string; style: AiSiteStyle },\n): Promise<{ write: AiSiteThemeWrite; baseName: string }> {\n const hostRef = firestore.collection('hosts').doc(input.hostId)\n const preset =\n input.style.base === 'starter'\n ? null\n : (listServerThemePresets().find((entry) => entry.id === aiSiteBasePresetId(input.style.base)) ?? null)\n const base: HostTheme = preset ? themeArtifactContent(preset.theme) : DEFAULT_SITE_THEME\n const baseName = preset?.name ?? 'Site theme'\n const edited = aiSiteTheme({ ...input.style, base: preset ? input.style.base : 'starter' }, base)\n const override = overrideWriteValue(diffOverride(base, edited), null)\n const siteStyle = { ...input.style, base: preset ? input.style.base : 'starter', jobId: input.jobId }\n const write = await firestore.runTransaction(async (tx): Promise<AiSiteThemeWrite> => {\n const snapshot = await tx.get(hostRef)\n if (!snapshot.exists) return 'missing'\n const host = snapshot.data() as ThemeHostDocument & Record<string, unknown>\n const stored = host['siteStyle'] as { jobId?: unknown } | undefined\n if (stored?.jobId === input.jobId) return 'applied'\n if (!aiSiteThemeUntouched(host)) return 'kept'\n const extra = { themeOverride: override, siteStyle }\n if (preset) {\n const plan = await runThemeLibraryAction(\n tx,\n hostRef,\n { action: 'select', target: { kind: 'preset', id: preset.id, name: preset.name, theme: base } },\n extra,\n )\n if (plan.ok === false) throw new Error(`the site's base theme could not be picked: ${plan.error}`)\n } else {\n tx.update(hostRef, { theme: DEFAULT_SITE_THEME, ...extra })\n }\n return 'applied'\n })\n if (write === 'applied') {\n // The theme is live the moment it is written; cached pages go now.\n await dropPluginSiteCache({ hostIds: [input.hostId], reason: 'ai site look' })\n }\n return { write, baseName }\n}\n\n/** The sentence a look's row and output carry. */\nfunction lookLabel(style: AiSiteStyle, baseName: string): string {\n const pairing = AI_SITE_FONT_PAIRINGS.find((entry) => entry.id === style.fonts)\n return `Your look: ${baseName} base, ${pairing ? `${pairing.heading.family} type` : 'its own type'}, ${style.cards} cards`\n}\n\nexport interface AiSiteLookDeps {\n save?: typeof aiSaveSiteTheme\n generate?: typeof runValidatedGeneration\n others?: typeof aiWorkspaceSiteStyles\n}\n\n/** The most of a workspace's sites a look is drawn apart from. */\nexport const AI_SITE_LOOK_SIBLINGS = 50\n\n/**\n * The looks of a workspace's other sites (AGL-3660), so a new one is drawn\n * apart from each: none shares their base, hue family, heading font and\n * buttons. A read that fails draws apart from nothing.\n */\nexport async function aiWorkspaceSiteStyles(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; hostId: string },\n): Promise<AiSiteStyle[]> {\n try {\n const snapshot = await firestore\n .collection('hosts')\n .where('orgId', '==', input.orgId)\n .limit(AI_SITE_LOOK_SIBLINGS)\n .get()\n return snapshot.docs.flatMap((doc) => {\n const style = doc.get('siteStyle') as AiSiteStyle | undefined\n return doc.id !== input.hostId && style && typeof style.base === 'string' ? [style] : []\n })\n } catch (error) {\n console.warn('ai site look: the workspace sites could not be read; drawing apart from none', { orgId: input.orgId, error })\n return []\n }\n}\n\n/**\n * The theme unit's pass: ask for the look, build it, save it. `job` is the\n * unit's derived job, carrying the scaffold's inputs and its origin job id,\n * which is what the seed is drawn from — so a resumed pass draws the same.\n */\nexport async function aiRunSiteLook(\n context: AiJobStepContext,\n job: AiJob,\n deps: AiSiteLookDeps = {},\n): Promise<AiJobStepOutcome> {\n const save = deps.save ?? aiSaveSiteTheme\n const generate = deps.generate ?? runValidatedGeneration\n const model = aiSiteLookModel(job, context.modelFor?.('job.theme'))\n if (!job.hostId) return { ...aiUnspentOutcome(model), failure: 'This site job names no site.' }\n const kind = aiSiteKindOfInputs(job.inputs) ?? aiSiteKindFor(job.brief)\n const origin = typeof job.inputs?.['originJobId'] === 'string' ? (job.inputs['originJobId'] as string) : job.$id\n const result = await generate<AiSiteLookAnswer>(AI_SITE_LOOK_KIND, {\n step: 'job.theme',\n model,\n instructions: AI_SITE_LOOK_INSTRUCTIONS as AiSystemBlock[],\n messages: [{ role: 'user', content: aiSiteLookPrompt({ job: { ...job, $id: origin }, kind, bases: aiSiteLookBases(kind) }) }],\n tool: AI_SITE_LOOK_TOOL,\n maxTokens: AI_SITE_LOOK_BUDGET.maxTokens(model),\n thinking: 'off',\n check: aiSiteLookCheck,\n ...(context.signal ? { signal: context.signal } : {}),\n })\n const spent = aiGenerationSpent(result)\n if (result.status === 'refused') return { ...spent, refused: true }\n // An answer that could not be used leaves the kind and the seed to choose.\n const answer = result.status === 'ok' ? result.value : {}\n const brand = typeof job.inputs?.['brand'] === 'string' ? (job.inputs['brand'] as string) : null\n const others = deps.others ?? aiWorkspaceSiteStyles\n const avoid = await others(context.firestore, { orgId: job.orgId, hostId: job.hostId })\n const style = aiSiteStyleFor({ kind, answer, seed: aiSiteSeed(origin), brand, avoid })\n const saved = await save(context.firestore, { hostId: job.hostId, jobId: origin, style })\n if (saved.write === 'missing') throw new Error(`site ${job.hostId} vanished while its look was chosen`)\n const output: AiJobOutput = {\n resource: 'theme',\n id: 'look',\n hostId: job.hostId,\n label:\n saved.write === 'kept'\n ? 'Kept the theme you chose for this site'\n : lookLabel(style, saved.baseName),\n proposal: JSON.parse(JSON.stringify({ style, write: saved.write })) as Record<string, unknown>,\n }\n return { ...spent, outputs: [output] }\n}\n"],"names":["DEFAULT_SITE_THEME","diffOverride","overrideWriteValue","themeArtifactContent","readThemeSelection","SITE_THEME_ENTRY_ID","dropPluginSiteCache","listServerThemePresets","runThemeLibraryAction","AI_SITE_FONT_PAIRINGS","aiSiteKindFor","aiSiteKindOfInputs","AI_SITE_LOOK_TOOL","AI_SITE_LOOK_TOOL_NAME","aiReadSiteLook","aiSiteSeed","aiSiteStyleFor","aiSiteTheme","AI_SITE_MOTION_STYLE_RANGES","aiSiteMotionStylesFor","aiCatalogEntry","aiDefaultModelFor","aiModelForStep","runValidatedGeneration","aiJobStepBudget","aiGenerationSpent","aiUnspentOutcome","AI_JOB_BRIEF_MAX_CHARS","AI_SITE_LOOK_MAX_TOKENS","AI_SITE_LOOK_BUDGET","tier","maxTokens","AI_SITE_LOOK_KIND","STARTER_WORDS","AI_SITE_LOOK_INSTRUCTIONS","text","join","cacheBreakpoint","shuffled","list","seed","out","state","index","length","Math","imul","other","aiSiteLookPrompt","input","job","kind","key","inputs","trim","pairings","filter","pairing","look","fonts","includes","id","$id","label","design","brief","slice","bases","map","entry","base","words","feel","corners","chroma","motion","Boolean","aiSiteLookCheck","answer","value","violations","aiSiteLookModel","resolved","fallback","picked","model","provider","undefined","aiSiteBasePresetId","aiSiteLookBases","presets","flatMap","preset","find","description","name","stable","JSON","stringify","_key","inner","Array","isArray","Object","fromEntries","entries","sort","a","b","localeCompare","aiSiteThemeUntouched","host","themeOverride","selection","theme","aiSaveSiteTheme","firestore","hostRef","collection","doc","hostId","style","baseName","edited","override","siteStyle","jobId","write","runTransaction","tx","snapshot","get","exists","data","stored","extra","plan","action","target","ok","Error","error","update","hostIds","reason","lookLabel","heading","family","cards","AI_SITE_LOOK_SIBLINGS","aiWorkspaceSiteStyles","where","orgId","limit","docs","console","warn","aiRunSiteLook","context","deps","save","generate","modelFor","failure","origin","result","step","instructions","messages","role","content","tool","thinking","check","signal","spent","status","refused","brand","others","avoid","saved","output","resource","proposal","parse","outputs"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,sCAAqC;AACxE,SAASC,YAAY,EAAEC,kBAAkB,QAAQ,4CAA2C;AAC5F,SAASC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B;YAAOM,OAAOsD,MAAMtD,KAAK;QAAC;IAClE;IACA,OAAO,aAAKgD;QAAOW,SAAS;YAACJ;SAAO;;AACtC"}
@@ -599,14 +599,19 @@ export const AI_SITE_NO_PLAN_COPY = 'This site job has no confirmed plan to buil
599
599
  if (unit.kind === 'layout' || unit.kind === 'page') {
600
600
  var _job_outputs7;
601
601
  var _look_proposal;
602
- // The look designed first (AGL-3660): its header arrangement and band rhythm.
602
+ // The look designed first (AGL-3660): its header arrangement, band rhythm
603
+ // and, where it chose one, how its pages move (AGL-3941).
603
604
  const look = ((_job_outputs7 = job.outputs) != null ? _job_outputs7 : []).find((output)=>output.resource === 'theme' && output.id === 'look');
604
605
  const style = look == null ? void 0 : (_look_proposal = look.proposal) == null ? void 0 : _look_proposal['style'];
605
- if (style) unitInputs['siteStyle'] = {
606
- headerAlign: style['headerAlign'],
607
- rhythm: style['rhythm'],
608
- seed: style['seed']
609
- };
606
+ if (style) {
607
+ unitInputs['siteStyle'] = _extends({
608
+ headerAlign: style['headerAlign'],
609
+ rhythm: style['rhythm'],
610
+ seed: style['seed']
611
+ }, typeof style['motion'] === 'string' ? {
612
+ motion: style['motion']
613
+ } : {});
614
+ }
610
615
  unitInputs[AI_LAYOUT_LANGUAGE_INPUT] = true;
611
616
  const formPage = aiLayoutFormPageOfPlan(plan);
612
617
  if (formPage) unitInputs[AI_LAYOUT_FORM_PAGE_INPUT] = formPage;