@aglyn/plugins-ai 1.0.0-beta.268 → 1.0.0-beta.270
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +17 -17
- package/src/lib/components/ai-credits-card.component.d.ts +4 -3
- package/src/lib/components/ai-credits-card.component.js +25 -8
- package/src/lib/components/ai-credits-card.component.js.map +1 -1
- package/src/lib/components/ai-job-links.d.ts +6 -0
- package/src/lib/components/ai-job-links.js +9 -0
- package/src/lib/components/ai-job-links.js.map +1 -1
- package/src/lib/components/ai-products-hub-card.component.d.ts +6 -0
- package/src/lib/components/ai-products-hub-card.component.js +21 -6
- package/src/lib/components/ai-products-hub-card.component.js.map +1 -1
- package/src/lib/components/ai-site-build-page.component.js +3 -2
- package/src/lib/components/ai-site-build-page.component.js.map +1 -1
- package/src/lib/components/ai-store-finish-card.component.d.ts +14 -3
- package/src/lib/components/ai-store-finish-card.component.js +67 -9
- package/src/lib/components/ai-store-finish-card.component.js.map +1 -1
- package/src/lib/components/assist-build-card.component.js +3 -2
- package/src/lib/components/assist-build-card.component.js.map +1 -1
- package/src/lib/jobs/ai-job-build-step.d.ts +3 -0
- package/src/lib/jobs/ai-job-build-step.js +8 -2
- package/src/lib/jobs/ai-job-build-step.js.map +1 -1
- package/src/lib/jobs/ai-job-form-step.d.ts +9 -0
- package/src/lib/jobs/ai-job-form-step.js +21 -2
- package/src/lib/jobs/ai-job-form-step.js.map +1 -1
- package/src/lib/jobs/ai-job-page-language.d.ts +26 -9
- package/src/lib/jobs/ai-job-page-language.js +46 -3
- package/src/lib/jobs/ai-job-page-language.js.map +1 -1
- package/src/lib/jobs/ai-job-page-step.js +4 -2
- package/src/lib/jobs/ai-job-page-step.js.map +1 -1
- package/src/lib/jobs/ai-job-site-look.d.ts +2 -1
- package/src/lib/jobs/ai-job-site-look.js +6 -2
- package/src/lib/jobs/ai-job-site-look.js.map +1 -1
- package/src/lib/jobs/ai-job-site-step.js +11 -6
- package/src/lib/jobs/ai-job-site-step.js.map +1 -1
- package/src/lib/jobs/ai-layout-owner-photos.d.ts +57 -0
- package/src/lib/jobs/ai-layout-owner-photos.js +110 -0
- package/src/lib/jobs/ai-layout-owner-photos.js.map +1 -0
- package/src/lib/jobs/ai-layout-stock-photos.d.ts +51 -10
- package/src/lib/jobs/ai-layout-stock-photos.js +812 -121
- package/src/lib/jobs/ai-layout-stock-photos.js.map +1 -1
- package/src/lib/jobs/fixtures/ai-stock-photo-agl3942-recordings.d.ts +29 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl3942-recordings.js +291 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl3942-recordings.js.map +1 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-brightvale-recordings.d.ts +4 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-brightvale-recordings.js +87 -1
- package/src/lib/jobs/fixtures/ai-stock-photo-brightvale-recordings.js.map +1 -1
- package/src/lib/jobs/fixtures/ai-stock-photo-mexicano-recordings.d.ts +31 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-mexicano-recordings.js +325 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-mexicano-recordings.js.map +1 -0
- package/src/lib/layout-language/ai-layout-motion.d.ts +60 -7
- package/src/lib/layout-language/ai-layout-motion.js +231 -4
- package/src/lib/layout-language/ai-layout-motion.js.map +1 -1
- package/src/lib/layout-language/ai-layout-pictures.d.ts +8 -0
- package/src/lib/layout-language/ai-layout-pictures.js +68 -4
- package/src/lib/layout-language/ai-layout-pictures.js.map +1 -1
- package/src/lib/model/ai-site-look.d.ts +10 -1
- package/src/lib/model/ai-site-look.js +14 -3
- package/src/lib/model/ai-site-look.js.map +1 -1
- package/src/lib/native-nav.d.ts +26 -0
- package/src/lib/native-nav.js +58 -0
- package/src/lib/native-nav.js.map +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-page-step.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { throwIfAiJobCanceled } from './ai-job-cancel'\nimport { buildPageMarkdown } from '@aglyn/aglyn/app-utils/page-markdown'\nimport { SCREEN_SEO_TEXT_GUIDANCE } from '@aglyn/aglyn/app-utils/screen-seo-fields'\nimport { SCREEN_ROOT_PATH, screenRoutePathToUrl } from '@aglyn/aglyn/app-utils/screen-route'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport { duplicateResource } from '@aglyn/tenant-data-admin/server/duplicate-resource'\nimport { AI_BUILD_PLAN_LIMITS, aiPlanEmbedsFor, type AiBuildPlanScreen } from '../model/ai-build-plan'\nimport {\n AI_PAGE_CREATE_KINDS,\n aiPageCreationRefusal,\n aiPagePlanRefusal,\n parseAiPageJobInputs,\n} from '../model/ai-page-job'\nimport { aiPlanCapabilitiesForJob, aiPlanUncreatable } from '../model/ai-plan-capabilities'\nimport { aiSiteWords } from '../model/ai-site-job'\nimport type { AiJob, AiJobOutput, AiJobPlan, AiJobReview } from '../model/ai-jobs.types'\nimport { aiModelForStep } from '../providers/routing'\nimport { aiDoctrineNeedsInputMessage, runValidatedGeneration } from '../runtime/ai-doctrine'\nimport {\n aiClipAtWord,\n aiSettleMechanicalRules,\n aiSettlePlaceholderItems,\n aiSettleUnrelatedScreenLinks,\n validateAiDoctrineTree,\n type AiDoctrineTree,\n} from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { aiHasPlaceholderToken } from '../runtime/ai-placeholder-tokens'\nimport { AI_SEO_FIELDS_MAX_TOKENS, generateSeoFields } from '../runtime/seo-fields'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport type { AiSiteInventory } from '../model/ai-site-inventory'\nimport { registerAiJobAdmission, type AiJobAdmission } from './ai-job-admission'\nimport { aiGenerationWorstCaseMs } from './ai-job-budget'\nimport { aiJobDraftId, aiOriginJobId } from './ai-job-draft-ids'\nimport {\n aiBuildsWithComponents,\n aiDraftAdmissionRefusal,\n aiDraftAllowanceRefusal,\n aiSiteSubdomain,\n readAiDraft,\n readAiDraftNodes,\n readAiPlanCapabilities,\n updateAiDraftNodes,\n writeAiDraft,\n writeAiDraftScreenSeo,\n type AiDraftRecord,\n} from './ai-job-drafts'\nimport {\n aiBracketedFactsNote,\n aiConfirmedPlan,\n aiDoctrineReview,\n aiGenerationSpent,\n aiLimitReview,\n aiModelNodeIds,\n aiUnspentOutcome,\n} from './ai-job-generation'\nimport {\n AI_JOB_PAGE_SECTION_MAX_TOKENS,\n AI_JOB_PAGE_SECTION_TOKENS,\n AI_JOB_PAGE_STEP_BUDGET,\n AI_JOB_PAGE_STEP_MINIMUM_MS,\n aiJobPageSectionMaxTokens,\n} from './ai-job-page-budget'\nimport {\n AI_JOB_PAGE_INSTRUCTIONS,\n AI_PAGE_SECTION_TOOL,\n aiEmptyPage,\n aiPageCheckContext,\n aiPageLinkablePages,\n aiPageRecordNote,\n aiPageRecordTemplate,\n aiPageRecordTokens,\n aiPageSectionCheck,\n aiPageSectionNodeId,\n aiPageSectionPrompt,\n aiPageSectionSmaller,\n aiPageSectionWithRecordImage,\n aiPageWithSection,\n type AiPageSection,\n} from './ai-job-page-sections'\nimport { aiLayoutSitePages } from './ai-job-layout-site-pages'\nimport { aiResolveLayoutPictures } from '../layout-language/ai-layout-pictures'\nimport {\n AI_STOCK_PHOTO_AVOID_INPUT,\n AI_STOCK_PHOTO_PAGES_INPUT,\n aiLayoutStockPhotoSource,\n aiStockPhotoWordsOf,\n aiStockPlacedSrcs,\n} from './ai-layout-stock-photos'\nimport { AI_PLAN_ITEMS_MIN, aiPlanCopiedPageViolations } from './ai-job-plan-conformance'\nimport {\n AI_JOB_PAGE_LANGUAGE_BUDGET,\n aiJobUsesLayoutLanguage,\n aiLayoutListingContext,\n aiLayoutPageTargets,\n aiLayoutLeftOutNote,\n aiLayoutMotionSiteOf,\n aiRunLayoutPage,\n type AiLayoutStartPage,\n} from './ai-job-page-language'\nimport { aiWithSiteMotion } from '../layout-language/ai-layout-motion'\nimport {\n aiCreationUnit,\n aiRunJobUnit,\n aiSiteBuiltRefs,\n aiSitePendingUnits,\n aiSiteUnitJob,\n type AiSiteUnit,\n} from './ai-job-site-step'\nimport type { AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\nimport {\n aiJobStepRunMinimumMs,\n aiJobStepRunnerFor,\n registerAiJobStep,\n registerAiJobStepPasses,\n} from './ai-jobs'\n\n/**\n * The page step (AGL-2907): the generation step of a `page` job, run once a\n * member confirmed the job's plan. It builds ONE screen, section by section,\n * from what the site already has, and leaves it an unpublished draft.\n *\n * ── Why a page is built in passes ────────────────────────────────────────\n *\n * A page is far larger than one answer the job beat can wait for: the beat\n * gives a step what is left of its budget, and a whole page, answered and re-asked,\n * takes several times that. The confirmed plan already names the page's\n * sections, so the step builds one section per pass and asks the machine to\n * continue. Every pass is one reservation and one generation — the section's\n * lookup rounds, its answer and, when it breaks a rule, its one re-ask — sized\n * so that worst case fits `AI_JOB_PAGE_STEP_MINIMUM_MS`, which the step\n * registers as the least time a section pass needs before it starts.\n *\n * - The first pass builds the top section, which holds the page's h1, and\n * writes the draft screen and its first version.\n * - Each later pass builds the next section and adds it to that version.\n * - The last pass generates no tree: it holds the whole page to the\n * doctrine, writes the search title and description, and reports the\n * draft with its measured weight and a navigation proposal.\n *\n * How a section is asked for and held to the rules as part of the page is\n * `ai-job-page-sections.ts`.\n *\n * ── What the plan creates comes first (AGL-3031) ─────────────────────────\n *\n * A plan that creates a layout, forms or components is built in the same job,\n * before its page, one creation a pass, through the site scaffold's unit\n * machinery: each creation is handed to the step that builds that kind, under\n * a job derived from this one, and lands as the draft that step writes. Where\n * the job stands is read from its outputs, so nothing is kept anywhere else.\n * Once every creation is built, the page's passes run on the plan with each\n * `new:<name>` resolved to the record that was built, which the site's\n * inventory now lists — so the page places the new component and binds the new\n * form by id, and renders inside the new layout, exactly as it would one the\n * site always had. A pass that builds a creation needs the time the step that\n * builds it registers, not a section's (`aiPageJobRunMinimumMs`, AGL-3035), so\n * neither the beat nor a door starts it with only a section's time left.\n *\n * ── Never published ──────────────────────────────────────────────────────\n *\n * The draft is written the way `/api/hosts/resources` and\n * `/api/hosts/versions` write a screen and its first version, and nothing\n * else is touched: not the host document, whose routing map is what the live\n * site serves, and no collection, store, layout or navigation pointer\n * (`ai-job-drafts.ts`). A screen the routing map does not name serves nothing\n * until a member publishes it.\n */\n\n/**\n * A section pass's time, and the ceiling each pass asks on each model, are\n * declared apart from the step (`ai-job-page-budget.ts`): the site scaffold\n * builds its pages through this step and reads them without loading it.\n */\nexport {\n AI_JOB_PAGE_SECTION_MAX_TOKENS,\n AI_JOB_PAGE_SECTION_TOKENS,\n AI_JOB_PAGE_STEP_BUDGET,\n AI_JOB_PAGE_STEP_MINIMUM_MS,\n aiJobPageSectionMaxTokens,\n}\n\n/**\n * Tokens one element takes in a section's answer, ESTIMATED: the tree as JSON\n * text inside the tool call, at four characters a token. Measured on the ten\n * golden pages at a median of 38 and a most of 43 over their 39 sections, and\n * `ai-job-page-evals.spec.ts` holds every golden section under it.\n */\nexport const AI_JOB_PAGE_TOKENS_PER_ELEMENT = 45\n\n/**\n * Real tokens to every token estimated at four characters (AGL-3042). A\n * section's ceiling is counted by the provider in its own tokens, which run\n * above that estimate. MEASURED on the first live document run on a Free\n * workspace (AGL-3024, test-org, 2026-09-16), as the cache read of a request\n * over the estimate of the same cached prefix: 4,059 over 2,825 for the page\n * plan and 6,649 over 4,310 for the layout, the higher of the two, 1.5427 —\n * the ratio `ai-job-free-page.spec.ts` prices a Free page at. It is measured on\n * prompt text; an answer's own is read off a recorded pass, whose output\n * tokens the step's record keeps (`lastRuns`), beside the section it stored.\n */\nexport const AI_JOB_PAGE_REAL_TOKENS_PER_ESTIMATED = Math.max(4_059 / 2_825, 6_649 / 4_310)\n\n/**\n * Real tokens one element takes in a section's answer: the estimate at its\n * golden most, in real tokens, rounded up — 45 × 1.5427 → 70 (AGL-3042).\n */\nexport const AI_JOB_PAGE_REAL_TOKENS_PER_ELEMENT = Math.ceil(\n AI_JOB_PAGE_TOKENS_PER_ELEMENT * AI_JOB_PAGE_REAL_TOKENS_PER_ESTIMATED,\n)\n\n/**\n * The most elements a section's request asks it to keep under at an answer\n * ceiling: 15 at the balanced tier's 1,050 (AGL-3042). Counted in real\n * tokens, because the ceiling is: counted in the estimate, the budget is 23\n * elements, which a section of the goldens' largest elements fills at 1,597\n * real tokens — half as much again as the ceiling that cuts it off.\n */\nexport function aiJobPageSectionMaxElements(maxTokens: number): number {\n return Math.max(1, Math.floor(maxTokens / AI_JOB_PAGE_REAL_TOKENS_PER_ELEMENT))\n}\n\n/** A page's name when the plan names none. */\nexport const AI_JOB_PAGE_DEFAULT_NAME = 'New page'\n\nexport const AI_JOB_PAGE_NO_PLAN_COPY = 'This page job has no confirmed plan to build.'\nexport const AI_JOB_PAGE_DELETED_COPY = 'The draft page was deleted while it was being built.'\n\n/** A creation the plan names that this deployment has no step to build. */\nexport const AI_JOB_PAGE_CREATION_UNAVAILABLE_COPY =\n 'This page needs something that cannot be built here yet. Describe the page again.'\n\n/** A creation that finished without reporting what it built; the page cannot place it. */\nexport const AI_JOB_PAGE_CREATION_EMPTY_COPY =\n 'Part of this page could not be built. Describe the page again.'\n\n/**\n * What a page refused on its last pass tells the member after the plain\n * refusal (AGL-3143, AGL-3596). The draft is reported with the review, and\n * mending its layout in the editor is what lets the next pass finish the job.\n */\nexport const AI_JOB_PAGE_REFUSED_DRAFT_COPY = 'The draft is yours to open: fix its layout in the editor, then try again.'\n\n/**\n * The most passes a page job may take (AGL-3031): every creation the plan\n * limits admit, every section they admit, and the last pass that reports the\n * draft. A creation's step builds it in one pass, and a page one section a\n * pass, so a runner that never finishes is still bounded while a real page is\n * not.\n */\nexport const AI_JOB_PAGE_MAX_PASSES = AI_BUILD_PLAN_LIMITS.create + AI_BUILD_PLAN_LIMITS.sections + 1\n\n/**\n * The units a plan's creations are built as, in the order a scaffold builds\n * them: the layout, then the forms, then the components. Each is addressed by\n * its place in the plan, so a unit run again finds its own draft.\n */\nexport function aiPageJobUnits(plan: Pick<AiJobPlan, 'create'>): AiSiteUnit[] {\n return AI_PAGE_CREATE_KINDS.flatMap((kind) =>\n plan.create.flatMap((creation, index) => {\n if (creation.kind !== kind) return []\n const unit = aiCreationUnit(creation, `c${index}`)\n return unit ? [unit] : []\n }),\n )\n}\n\n/**\n * The least time this page job's next pass needs (AGL-3035). A pass that\n * builds a creation hands it to the step registered for that kind, under the\n * job derived for it, so it needs what that step registers for that job — a\n * layout's time, not a section's. Every other pass — a section, the last one —\n * needs a section pass's.\n */\nexport function aiPageJobRunMinimumMs(job: AiJob): number {\n const confirmed = aiConfirmedPlan(job)\n // A page built in the layout language is one answer for the whole page (AGL-3660).\n const pagePass = aiJobUsesLayoutLanguage(job) ? AI_JOB_PAGE_LANGUAGE_BUDGET.minimumMs : AI_JOB_PAGE_STEP_MINIMUM_MS\n if (!confirmed) return pagePass\n const units = aiPageJobUnits(confirmed)\n const outputs = job.outputs ?? []\n const [unit] = aiSitePendingUnits(units, outputs)\n if (!unit) return pagePass\n return aiJobStepRunMinimumMs(aiSiteUnitJob(job, unit, aiSiteBuiltRefs(units, outputs)))\n}\n\n/**\n * The one-segment address a draft asks for, from the plan's slug; `/` for a\n * planned home page, which asks for the root rather than for an address made\n * from its name (AGL-3596).\n */\nexport function aiPageDraftSlug(screen: Pick<AiBuildPlanScreen, 'slug'>): string {\n const segments = screen.slug.split('/').map((part) => part.trim()).filter(Boolean)\n if (!segments.length && screen.slug.trim() === SCREEN_ROOT_PATH) return SCREEN_ROOT_PATH\n return segments[segments.length - 1] ?? ''\n}\n\n/**\n * The layout a site's pages render inside (AGL-3596): the one its home page\n * uses, else the one the most pages use, else the site's only layout. `null`\n * for a site with no layout, or several and no page to choose between them.\n */\nexport function aiSiteDefaultLayoutId(\n inventory: Pick<AiSiteInventory, 'layouts' | 'screens'>,\n): string | null {\n const layouts = new Set(inventory.layouts.map((row) => row.id))\n if (!layouts.size) return null\n const pages = inventory.screens.filter(\n (row) => !row.template && row.layoutId && layouts.has(row.layoutId),\n )\n const home = pages.find((row) => row.slug.trim() === SCREEN_ROOT_PATH)\n if (home?.layoutId) return home.layoutId\n const counts = new Map<string, number>()\n for (const row of pages) counts.set(row.layoutId as string, (counts.get(row.layoutId as string) ?? 0) + 1)\n const [mostUsed] = [...counts.entries()].sort((a, b) => b[1] - a[1])\n if (mostUsed) return mostUsed[0]\n return layouts.size === 1 ? [...layouts][0] : null\n}\n\n/**\n * The layout a page draft renders inside: the plan's, where the site has it,\n * else the site's own (AGL-3596). A page the plan named no layout for used to\n * be written with none, and so with no header and no footer, beside pages\n * that had them.\n */\nexport function aiPageDraftLayoutId(\n screen: Pick<AiBuildPlanScreen, 'layout'>,\n inventory: Pick<AiSiteInventory, 'layouts' | 'screens'>,\n): string | null {\n if (screen.layout && inventory.layouts.some((row) => row.id === screen.layout)) return screen.layout\n return aiSiteDefaultLayoutId(inventory)\n}\n\n/** The site's name as its visitors see it, read the way the SEO step reads it. */\nfunction siteNameOf(host: FirebaseFirestore.DocumentSnapshot): string {\n const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '')\n return text(host.get('seo.title')) || text(host.get('displayName')) || text(host.get('subdomain'))\n}\n\n/**\n * The counts the confirmed plan's sections promised, against the page a COPY\n * actually produced (AGL-3024); `null` when the copy keeps the plan, or when\n * the plan promised no count to keep.\n *\n * The same hole the layout copy had (`aiCopiedLayoutReview`), on the kind the\n * defect was measured on. This branch generates nothing, so no model ever\n * answers for the plan: a plan reading \"start from the Services page, one\n * card per practice area\" gets the Services page and whatever IT had, and\n * until now reported `Done` — the one report that tells a customer there is\n * no reason to re-read the page.\n *\n * A copy that cannot be read back settles nothing, and a promise this step\n * cannot settle is reviewed by a person rather than reported as kept.\n */\nexport async function aiCopiedPageReview(\n firestore: FirebaseFirestore.Firestore,\n input: { hostId: string; id: string; name: string; screen: Pick<AiBuildPlanScreen, 'sections'> },\n): Promise<AiJobReview | null> {\n if (!input.screen.sections.some((section) => section.items >= AI_PLAN_ITEMS_MIN)) return null\n const stored = await readAiDraftNodes(firestore, { kind: 'screen', hostId: input.hostId, id: input.id })\n const nodes = (stored?.nodes ?? {}) as unknown as AiDoctrineTree['nodes']\n if (!nodes[CANVAS_ROOT_ELEMENT_ID]) {\n return {\n reason: 'doctrine',\n message: `\"${input.name}\" was copied from the page the plan names, and this job could not read the copy back to check it shows what the plan says it shows. Open the page and check it before you put it in front of anyone.`,\n findings: [],\n }\n }\n const violations = aiPlanCopiedPageViolations(input.screen, { rootId: CANVAS_ROOT_ELEMENT_ID, nodes })\n if (!violations.length) return null\n return aiDoctrineReview({\n message: `\"${input.name}\" is a copy of the page the plan names, and a copy is all it is: ${violations[0].message}`,\n violations,\n })\n}\n\n/**\n * A page job is admitted with inputs that read, for a site of the job's own\n * org with a screen to spare; and confirmed only for a plan it can build —\n * one screen, whose creations are ones a page job builds, this deployment has\n * a step for, and this workspace may still make on this site (AGL-3031).\n */\nexport const aiPageJobAdmission: AiJobAdmission = async (context) => {\n const inputs = parseAiPageJobInputs(context.inputs)\n if (typeof inputs === 'string') return { status: 400, error: inputs }\n const plan = context.plan\n if (plan) {\n const refusal = aiPagePlanRefusal(plan)\n if (refusal) return { status: 400, error: refusal }\n if (aiPageJobUnits(plan).some((unit) => !aiJobStepRunnerFor(unit.jobKind))) {\n return { status: 400, error: AI_JOB_PAGE_CREATION_UNAVAILABLE_COPY }\n }\n }\n const org = context.org as Partial<AglynOrgBilling> | null\n return aiDraftAdmissionRefusal(context.firestore, {\n orgId: context.orgId,\n hostId: context.hostId,\n kind: 'screen',\n noun: 'page',\n org,\n // What the workspace may still make here, read once the site is known to\n // be the org's: the site may have changed since the plan was told.\n ...(plan?.create.length\n ? {\n ownCheck: async (hostId: string) => {\n const capabilities = aiPlanCapabilitiesForJob(\n await readAiPlanCapabilities(context.firestore, { hostId, org }),\n { noun: 'a page job', creates: AI_PAGE_CREATE_KINDS },\n )\n const refusal = aiPageCreationRefusal(aiPlanUncreatable(plan, capabilities))\n return refusal ? { status: 403 as const, error: refusal } : null\n },\n }\n : {}),\n })\n}\n\n/**\n * The site's page a page of a build or a site starts from (AGL-3832): the\n * plan's `duplicateOf`, by its name and its words, for the page's prompt.\n * Only a page the site has, and never its starter home page, which is a\n * placeholder rather than words of the owner's (AGL-3596) — nor an entry\n * template, whose words are its records'. `null` when there is no such page\n * or its words cannot be read: the page is then built from its plan alone.\n */\nexport async function aiPageStartPage(\n firestore: Parameters<typeof readAiDraftNodes>[0],\n input: { hostId: string; screen: Pick<AiBuildPlanScreen, 'duplicateOf'>; inventory: Pick<AiSiteInventory, 'screens'> },\n readNodes: typeof readAiDraftNodes = readAiDraftNodes,\n): Promise<AiLayoutStartPage | null> {\n const id = input.screen.duplicateOf\n const row = id ? input.inventory.screens.find((one) => one.id === id && !one.template && !one.replaceable) : undefined\n if (!row) return null\n const stored = await readNodes(firestore, { kind: 'screen', hostId: input.hostId, id: row.id }).catch(() => null)\n const text = stored ? buildPageMarkdown({ nodes: stored.nodes as never, rootId: CANVAS_ROOT_ELEMENT_ID }).trim() : ''\n return text ? { label: row.name, text } : null\n}\n\n/**\n * The library photos the job's other pages already show (AGL-3660): read\n * from the screen drafts a site job names for its page unit\n * (`AI_STOCK_PHOTO_PAGES_INPUT`), never this page's own, so a pass repeated\n * over it keeps its photos, and those its datasets' records show\n * (`AI_STOCK_PHOTO_AVOID_INPUT`, AGL-3616). Empty on any failure: a repeat is better than a\n * page that fails over decoration.\n */\nexport async function aiJobPagesPlacedPhotos(\n firestore: Parameters<typeof readAiDraftNodes>[0],\n input: { hostId: string; job: Pick<AiJob, 'inputs'>; draftId: string },\n readNodes: typeof readAiDraftNodes = readAiDraftNodes,\n): Promise<string[]> {\n const listed = input.job.inputs?.[AI_STOCK_PHOTO_PAGES_INPUT]\n const ids = Array.isArray(listed)\n ? [...new Set(listed.filter((id): id is string => typeof id === 'string' && !!id && id !== input.draftId))]\n : []\n // What the site's datasets' records show (AGL-3616), named by the job.\n const elsewhere = input.job.inputs?.[AI_STOCK_PHOTO_AVOID_INPUT]\n const shown = Array.isArray(elsewhere)\n ? elsewhere.filter((src): src is string => typeof src === 'string' && src.startsWith('media:'))\n : []\n if (!ids.length) return [...new Set(shown)]\n const read = await Promise.all(\n ids.map((id) => readNodes(firestore, { kind: 'screen', hostId: input.hostId, id }).catch(() => null)),\n )\n return [...new Set([...shown, ...read.flatMap((stored) => aiStockPlacedSrcs(stored?.nodes))])]\n}\n\nexport interface AiJobPageStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** The platform's duplicate module, for a plan that starts from a copy. */\n duplicate?: typeof duplicateResource\n /** The listing generator (AGL-2910). */\n seoFields?: typeof generateSeoFields\n /** The runners a plan's creations are built by (AGL-3031); the registry's otherwise. */\n runnerFor?: typeof aiJobStepRunnerFor\n /** The stock photo source of a language page's pictures (AGL-3660); core's provider otherwise. */\n stockPhotos?: typeof aiLayoutStockPhotoSource\n}\n\nexport function createAiJobPageStep(deps: AiJobPageStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const duplicate = deps.duplicate ?? duplicateResource\n const seoFields = deps.seoFields ?? generateSeoFields\n const runnerFor = deps.runnerFor ?? aiJobStepRunnerFor\n return async (stepContext): Promise<AiJobStepOutcome> => {\n const { job, now, signal, firestore, modelFor } = stepContext\n const hostId = job.hostId\n if (!hostId) throw new Error('a page job names no site, and its admission refuses one')\n // The switch's answer for this job, else the routing table's (AGL-2942).\n const model = modelFor?.('job.page') ?? aiModelForStep('job.page')\n const confirmed = aiConfirmedPlan(job)\n if (!confirmed) return { ...aiUnspentOutcome(model), failure: AI_JOB_PAGE_NO_PLAN_COPY }\n // The resume door refuses such a plan at confirmation; one confirmed\n // before a site changed still stops here, before any spend.\n const refusal = aiPagePlanRefusal(confirmed)\n if (refusal) return { ...aiUnspentOutcome(model), failure: refusal }\n\n // ── The creations first (AGL-3031): one a pass, by the steps that own them ──\n const units = aiPageJobUnits(confirmed)\n const outputs = job.outputs ?? []\n const [unit] = aiSitePendingUnits(units, outputs)\n if (unit) {\n const runner = runnerFor(unit.jobKind)\n if (!runner) return { ...aiUnspentOutcome(model), failure: AI_JOB_PAGE_CREATION_UNAVAILABLE_COPY }\n const pass = await aiRunJobUnit(stepContext, {\n unit,\n units,\n runner,\n emptyCopy: AI_JOB_PAGE_CREATION_EMPTY_COPY,\n })\n // A built creation is followed by the next, or by the page's first section.\n return pass.built ? { ...pass.outcome, continue: true } : pass.outcome\n }\n // The page's plan with every creation resolved to the record it built, as\n // a scaffold's page is planned against what the scaffold built.\n const plan: AiJobPlan = units.length\n ? (aiSiteUnitJob(\n job,\n {\n kind: 'page',\n jobKind: 'page',\n resource: 'screen',\n slot: 'page',\n screen: confirmed.screens[0],\n label: confirmed.screens[0].title,\n },\n aiSiteBuiltRefs(units, outputs),\n ).plan as AiJobPlan)\n : confirmed\n const screen = plan.screens[0] as AiBuildPlanScreen\n const name = screen.title || AI_JOB_PAGE_DEFAULT_NAME\n const slug = aiPageDraftSlug(screen)\n const sectionIds = screen.sections.map((_, index) => aiPageSectionNodeId(job.$id, index))\n // The draft screen, by the id the job recorded for it: every pass writes and finds the same one.\n const draftId = aiJobDraftId(job, 'screen')\n\n const output = (\n draft: Pick<AiDraftRecord, 'id' | 'versionId' | 'name' | 'hostSubdomain'>,\n load?: AiLoadEstimate | null,\n note?: string | null,\n ): AiJobOutput => ({\n resource: 'screen',\n id: draft.id,\n versionId: draft.versionId,\n hostId,\n hostSubdomain: draft.hostSubdomain,\n label: draft.name,\n ...(load ? { load } : {}),\n ...(note ? { note } : {}),\n // Rule 10: a navigation entry travels with the page as a proposal, for\n // the member to add once the page is live; no menu is written.\n ...(screen.nav ? { proposal: { navigation: { label: name, slug } } } : {}),\n })\n\n const [inventory, orgSnapshot, written] = await Promise.all([\n readInventory(job.orgId, hostId, { firestore }),\n firestore.collection('orgs').doc(job.orgId).get(),\n readAiDraft(firestore, { kind: 'screen', hostId, id: draftId }),\n ])\n const org = (orgSnapshot.data() ?? null) as Partial<AglynOrgBilling> | null\n if (written?.deleted) return { ...aiUnspentOutcome(model), failure: AI_JOB_PAGE_DELETED_COPY }\n // A record template's copy binds its dataset's fields, and its draft says\n // where the member saves the binding (AGL-3475).\n const record = aiPageRecordTemplate(screen.record, inventory, plan)\n const recordNote = record ? aiPageRecordNote(record) : null\n\n // A page job's plan starts from a copy of a screen the site has (rule\n // 15): the copy is the draft — unrouted, as every copy is — and nothing\n // is generated.\n // Only a page is a page's start: a collection entry template's copy stays\n // a template, so a plan naming one builds the page instead.\n // A copy shows what its SOURCE shows, and this branch generates nothing.\n // So if the source cannot already show what the plan promised, copying it\n // can only produce a page that breaks the promise — the refusal below\n // would be certain before the copy was ever minted. Read the source and\n // build instead, rather than leave the member a page they must throw away\n // and a Try again that can only copy the same thing (AGL-3024).\n // Only a source we could READ and found short diverts: one we cannot read\n // is one we cannot judge, and the review after the copy still answers for\n // that. A short source carries findings; an unreadable one carries none.\n // A copy of the starter home page is never a page the job built\n // (AGL-3596): the site's own placeholder is replaced by a page generated\n // from the plan, so a plan that names it as a start builds instead.\n const copiesStarter = Boolean(\n screen.duplicateOf &&\n inventory.screens.some((row) => row.id === screen.duplicateOf && row.replaceable),\n )\n // A page a build or a site makes (every one designed in the layout\n // language) counts as built only once its plan's sections are in it,\n // under the ids this step writes them by (AGL-3596). A copy holds its\n // source's sections under the source's ids, so it never counts: a build\n // that copied \"Our Story\" for its About page failed the page and left the\n // copy behind (AGL-3832). Such a page is generated from its plan, its\n // prompt shown the words of the page it starts from (`aiPageStartPage`).\n const generatedWhole = aiJobUsesLayoutLanguage(job)\n const sourceReview =\n !written && screen.duplicateOf && !copiesStarter && !generatedWhole\n ? await aiCopiedPageReview(firestore, { hostId, id: screen.duplicateOf, name, screen })\n : null\n const sourceShort = Boolean(sourceReview?.findings.length)\n if (\n !written &&\n !sourceShort &&\n !copiesStarter &&\n !generatedWhole &&\n screen.duplicateOf &&\n inventory.screens.some((row) => row.id === screen.duplicateOf && !row.template)\n ) {\n const copy = await duplicate('screen', {\n orgId: job.orgId,\n hostId,\n sourceId: screen.duplicateOf,\n name,\n uid: job.createdBy,\n org: org as Record<string, unknown> | null,\n // A copy core mints is written under core's id, never `draftId`, so\n // `written` above cannot find it and this branch would fire on every\n // pass — and the pass after a refused copy is the common one, since\n // the review below offers to try again. The job's recorded id is the\n // claim, so a second pass replays the one copy instead of leaving\n // another orphan screen behind it (AGL-3024).\n attemptKey: draftId,\n })\n if (copy.ok) {\n // A copy is not a build (AGL-3024). Nothing is generated here, so\n // whatever the plan promised BEYOND the source is in the draft only\n // if the source already had it, and no model is left to answer for\n // the difference — the copy itself has to.\n const review = await aiCopiedPageReview(firestore, { hostId, id: copy.id, name, screen })\n if (review) return aiUnspentOutcome(model, { review })\n const hostSubdomain = await aiSiteSubdomain(firestore, hostId)\n return aiUnspentOutcome(model, {\n outputs: [output({ id: copy.id, versionId: copy.versionId, name: copy.name, hostSubdomain }, null, recordNote)],\n })\n }\n if (copy.ok === false && copy.status === 403) {\n return aiUnspentOutcome(model, { review: aiLimitReview(copy.error) })\n }\n }\n\n const stored = written ? await readAiDraftNodes(firestore, { kind: 'screen', hostId, id: draftId }) : null\n if (written && !stored) return { ...aiUnspentOutcome(model), failure: AI_JOB_PAGE_DELETED_COPY }\n let page = stored?.nodes ?? aiEmptyPage()\n const index = sectionIds.findIndex((id) => !(id in page))\n // A workspace whose component allowance is finite — Free's one — draws\n // its repeats inline, and every pass is held to the rules that way\n // (AGL-3030, AGL-3615). A form is a saved one placed by id on every plan,\n // or none (AGL-3596).\n const reusableComponents = aiBuildsWithComponents(org)\n // A link may take a visitor to a section of this page, by its name in the plan (AGL-3097).\n const sections = screen.sections.map((section) => section.name)\n // A third-party player the confirmed plan lists for this page is the only one it may embed (AGL-3433).\n const embeds = aiPlanEmbedsFor(plan, { slug: screen.slug })\n // The site's other pages a link may go to, built or minted on a guided\n // start's plan, and the one a link that names none can only mean (AGL-3596).\n const { linkablePages, linkTarget } = aiPageLinkablePages(inventory, aiLayoutSitePages(job.inputs), [screen.id, draftId])\n // A page unit of a guided start or a build is designed in the layout\n // language and compiled (AGL-3660); a record template keeps the raw tree,\n // since its copy binds fields the language does not name.\n const language = aiJobUsesLayoutLanguage(job) && !record\n const checked = {\n ...aiPageCheckContext(inventory, {\n reusableComponents,\n sections,\n embeds,\n recordTokens: aiPageRecordTokens(record),\n linkablePages,\n }),\n // The last pass holds a compiled page to what its own check did: the\n // design's picture cards are the compiler's, not a block rule 1 asks a\n // component of (AGL-3660). Without it, a Pro store's Shop page passed\n // its check and was refused at the last pass (live run, 2026-10-09).\n ...(language ? { codeBuilt: true, repeatsCompiled: true } : {}),\n }\n // And a post's card in a section listing the blog links its post and shows\n // its cover by the tokens the page fills per post (AGL-3676), as its check admitted.\n const context = language\n ? aiLayoutListingContext(checked, aiLayoutPageTargets({ job, inventory, own: [screen.id, draftId] }))\n : checked\n\n // ── The last pass: the whole page, its listing, and the draft reported ──\n // A page in the layout language is written whole by one pass (AGL-3660),\n // so once written it is complete: a planned section missing from it was\n // taken out by its last answer, never one still to build (AGL-3771).\n if ((index === -1 || language) && written) {\n // An attribute a rule has one answer for is settled on the stored page\n // and stored (AGL-3660): this pass asks no model, so a page refused\n // here for one would be refused the same way on every Try again. A\n // Portfolio page whose opening photos all loaded eagerly was (2026-10-10).\n // And a link sent home for nothing is sent to the site's form, or left out (AGL-3729),\n // and an item of a list that shows only placeholders is taken out where the list keeps a real one (AGL-3827).\n // And the site's entrance motion is written on a page built a section at\n // a time, as on one built whole (AGL-3838); a page that already moves —\n // by this pass or by its author — comes back as it is, and is not written.\n const motion = aiLayoutMotionSiteOf(job, screen.slug)\n const settle = <T extends AiDoctrineTree>(tree: T): T => {\n const settled = aiSettleUnrelatedScreenLinks(\n aiSettlePlaceholderItems(aiSettleMechanicalRules(tree, 'page'), 'page', context),\n 'page',\n {\n ...context,\n ownScreenIds: [screen.id, draftId],\n },\n )\n const moved = aiWithSiteMotion(settled.nodes, motion, { sectionIds })\n return moved === settled.nodes ? settled : { ...settled, nodes: moved }\n }\n const settled = settle({ rootId: CANVAS_ROOT_ELEMENT_ID, nodes: page as unknown as AiDoctrineTree['nodes'] })\n if (settled.nodes !== (page as unknown as AiDoctrineTree['nodes'])) {\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const update = await updateAiDraftNodes(firestore, {\n kind: 'screen',\n hostId,\n id: draftId,\n now,\n update: (nodes) => {\n const tree = { rootId: CANVAS_ROOT_ELEMENT_ID, nodes: nodes as unknown as AiDoctrineTree['nodes'] }\n const next = settle(tree)\n return next === tree ? null : (next.nodes as unknown as typeof nodes)\n },\n })\n if (update.ok === false) return { ...aiUnspentOutcome(model), failure: AI_JOB_PAGE_DELETED_COPY }\n page = settled.nodes as unknown as typeof page\n }\n // A link the page carries to one of its sections goes there, now every section is built.\n const report = validateAiDoctrineTree({ rootId: CANVAS_ROOT_ELEMENT_ID, nodes: page }, 'page', {\n ...context,\n scrollTargetIds: sectionIds,\n })\n // The facts the brief did not give, on the page or in the defaults its components show (AGL-3056).\n const note =\n [\n aiBracketedFactsNote({\n tree: { rootId: CANVAS_ROOT_ELEMENT_ID, nodes: page as unknown as AiDoctrineTree['nodes'] },\n inventory,\n }),\n recordNote,\n // A section the last answer could not fill was left out, and the page says which (AGL-3771).\n language ? aiLayoutLeftOutNote(screen, sectionIds, page as unknown as Record<string, unknown>) : null,\n ]\n .filter(Boolean)\n .join(' ') || null\n // The page's own draft, reported once however many times the last pass\n // runs (AGL-3143): a refused pass reports it and a later one that\n // passes does not report it twice.\n const reported = outputs.some((entry) => entry.resource === 'screen' && entry.id === draftId)\n const reports = reported ? [] : [output(written, report.load, note)]\n if (report.violations.length) {\n // The check mints its own ids; the review names the nodes by the ids the draft stores them under.\n const storedIds = report.tree?.sourceIds ?? {}\n const violations = report.violations.map((violation) =>\n violation.nodeIds ? { ...violation, nodeIds: aiModelNodeIds(violation.nodeIds, storedIds) } : violation,\n )\n // THE DRAFT TRAVELS WITH THE REFUSAL (AGL-3143). Every other review\n // parks on a model's answer, so trying again asks the model again and\n // can come back different. This one reads the STORED page and spends\n // nothing, so trying again refuses the same page for the same reasons\n // forever — and a job parked here having reported no output names no\n // draft at all, which leaves the member nowhere to mend the nodes the\n // findings name and no way to finish the job from the console. The\n // draft is reported now instead, and the job still parks: what the\n // review names is mended in the draft, and the next pass then passes.\n return aiUnspentOutcome(model, {\n outputs: reports,\n review: aiDoctrineReview(\n {\n message: aiDoctrineNeedsInputMessage(violations),\n violations,\n answer: { tree: { rootId: CANVAS_ROOT_ELEMENT_ID, nodes: page } },\n },\n { page: true, then: AI_JOB_PAGE_REFUSED_DRAFT_COPY },\n ),\n })\n }\n let spent: AiJobStepOutcome = aiUnspentOutcome(model)\n if (!written.seo?.title?.trim() || !written.seo?.description?.trim()) {\n const seoModel = modelFor?.('job.seo') ?? aiModelForStep('job.seo')\n // The plan's own listing, held to the editor's guidance, when the\n // listing cannot be written inside this pass's time on the model the\n // job runs.\n let values = {\n title: aiClipAtWord(screen.seoTitle, SCREEN_SEO_TEXT_GUIDANCE.title, plan.language),\n description: aiClipAtWord(screen.seoDescription, SCREEN_SEO_TEXT_GUIDANCE.description, plan.language),\n }\n if (\n // A listing is written from the page's own text, with no inventory\n // and so no lookup round.\n aiGenerationWorstCaseMs({ maxTokens: AI_SEO_FIELDS_MAX_TOKENS, model: seoModel, lookups: 0 }) <=\n AI_JOB_PAGE_STEP_MINIMUM_MS\n ) {\n const host = await firestore.collection('hosts').doc(hostId).get()\n const result = await seoFields({\n subject: { kind: 'screen', name, path: screenRoutePathToUrl(slug || SCREEN_ROOT_PATH) },\n brand: siteNameOf(host),\n // What the site is and who it is for (AGL-2918). The page's own\n // Markdown says what the page is about and cannot say who it was\n // written for, so the listing borrows the two answers the job was\n // started from — the scaffold's derived page job carries them,\n // and a page job started from the Screens page carries neither.\n site: aiSiteWords(job.inputs),\n text: buildPageMarkdown({ nodes: page as never, rootId: CANVAS_ROOT_ELEMENT_ID }),\n fields: ['title', 'description'],\n // Other screens by name only: their own listings are their content.\n otherTitles: inventory.screens.map((row) => row.name),\n model: seoModel,\n ...(signal ? { signal } : {}),\n })\n spent = { ...spent, ...aiGenerationSpent(result) }\n if (result.status === 'ok') {\n // A written field that shows a placeholder keeps the plan's, which\n // the plan's own check already held to rule 14 (AGL-3827).\n const usable = (text: string | null | undefined): string =>\n text?.trim() && !aiHasPlaceholderToken(text) ? text.trim() : ''\n values = {\n title: usable(result.value.title) || values.title,\n description: usable(result.value.description) || values.description,\n }\n }\n }\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n await writeAiDraftScreenSeo(firestore, { hostId, id: draftId, seo: values, now })\n }\n return { ...spent, outputs: reports }\n }\n\n // ── A section pass ──\n if (!written) {\n const allowance = await aiDraftAllowanceRefusal(firestore, { kind: 'screen', hostId, org })\n if (allowance) return aiUnspentOutcome(model, { review: aiLimitReview(allowance) })\n }\n if (language) {\n // ── The whole page in one answer, in the layout language ──\n const targets = aiLayoutPageTargets({ job, inventory, own: [screen.id, draftId] })\n const startsFrom = await aiPageStartPage(firestore, { hostId, screen, inventory })\n const result = await aiRunLayoutPage({\n job,\n plan,\n screen,\n sectionIds,\n targets,\n context,\n reusableComponents,\n inventory,\n model,\n startsFrom,\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(result)\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') return { ...spent, review: aiDoctrineReview(result) }\n // The compiler leaves each picture slot empty; a photo the site serves\n // itself fills it here, after the page is checked (AGL-3660): a stock\n // photo copied into the site's library where the deployment has a\n // library, else a starter photo. No AI credits; never fails the job.\n const sectionNames = screen.sections.map((section) => section.name)\n const seed = `${aiOriginJobId(job)}:${screen.id ?? screen.slug}`\n // A photo another page of the job already shows is not placed here.\n const avoid = await aiJobPagesPlacedPhotos(firestore, { hostId, job, draftId })\n const photoWords = aiStockPhotoWordsOf(job)\n const pictured = await aiResolveLayoutPictures(result.value.nodes, {\n rootId: CANVAS_ROOT_ELEMENT_ID,\n sectionIds,\n sectionNames,\n seed,\n ...(photoWords.language ? { language: photoWords.language } : {}),\n source: (deps.stockPhotos ?? aiLayoutStockPhotoSource)({\n hostId,\n uid: job.createdBy,\n seed,\n business: aiSiteWords(job.inputs).about,\n ...photoWords,\n sectionNames,\n jobId: aiOriginJobId(job),\n ...(avoid.length ? { avoid } : {}),\n ...(signal ? { signal } : {}),\n }),\n })\n if (!written) {\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const draft = await writeAiDraft(firestore, {\n kind: 'screen',\n hostId,\n id: draftId,\n uid: job.createdBy,\n org,\n name,\n nodes: pictured,\n slug,\n layoutId: aiPageDraftLayoutId(screen, inventory),\n aiJobId: aiOriginJobId(job),\n now,\n })\n if (draft.ok === false) {\n if (draft.status === 404) throw new Error(`site ${hostId} vanished while its page was generated`)\n return { ...spent, review: aiLimitReview(draft.error) }\n }\n } else {\n // A draft written by an earlier, interrupted pass is replaced whole.\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const update = await updateAiDraftNodes(firestore, {\n kind: 'screen',\n hostId,\n id: draftId,\n now,\n update: () => pictured,\n })\n if (update.ok === false) return { ...spent, failure: AI_JOB_PAGE_DELETED_COPY }\n }\n return { ...spent, continue: true }\n }\n const maxTokens = aiJobPageSectionMaxTokens(model)\n const maxElements = aiJobPageSectionMaxElements(maxTokens)\n const result = await runValidatedGeneration<AiPageSection>('page-section', {\n step: 'job.page',\n model,\n instructions: AI_JOB_PAGE_INSTRUCTIONS,\n inventory,\n messages: [\n {\n role: 'user',\n content: aiPageSectionPrompt({ job, plan, screen, index, maxElements, reusableComponents, record, linkablePages }),\n },\n ],\n tool: AI_PAGE_SECTION_TOOL,\n maxTokens,\n // A section cut off at its ceiling is asked for smaller, and a member\n // whose section still does not fit reads that it was too large (AGL-3042).\n cutOff: { noun: 'section', smaller: aiPageSectionSmaller({ maxElements, reusableComponents }) },\n thinking: 'off',\n check: aiPageSectionCheck({\n page,\n sectionIds,\n index,\n context,\n section: screen.sections[index],\n inventory,\n linkTarget,\n }),\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(result)\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') return { ...spent, review: aiDoctrineReview(result, { page: true }) }\n // A record template's page leads with each record's own photo (AGL-3616).\n const section = aiPageSectionWithRecordImage(result.value, page, record)\n\n if (!written) {\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const draft = await writeAiDraft(firestore, {\n kind: 'screen',\n hostId,\n id: draftId,\n uid: job.createdBy,\n org,\n name,\n nodes: aiPageWithSection(aiEmptyPage(), section, sectionIds),\n slug,\n layoutId: aiPageDraftLayoutId(screen, inventory),\n aiJobId: aiOriginJobId(job),\n now,\n })\n if (draft.ok === false) {\n if (draft.status === 404) throw new Error(`site ${hostId} vanished while its page was generated`)\n return { ...spent, review: aiLimitReview(draft.error) }\n }\n } else {\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const update = await updateAiDraftNodes(firestore, {\n kind: 'screen',\n hostId,\n id: draftId,\n now,\n // A pass run again after its write finds its section and changes nothing.\n update: (nodes) =>\n section.rootId in nodes ? null : aiPageWithSection(nodes, section, sectionIds),\n })\n if (update.ok === false) return { ...spent, failure: AI_JOB_PAGE_DELETED_COPY }\n }\n return { ...spent, continue: true }\n }\n}\n\nexport const runAiJobPageStep = createAiJobPageStep()\n\n/**\n * Registers the page step with the least time a section pass needs and the\n * time its next pass needs, the passes a page with its creations may take, and\n * the check a page job passes when it is created or its plan is confirmed.\n */\nexport function registerAiPageJob(): void {\n registerAiJobStep('page', runAiJobPageStep, {\n minimumMs: AI_JOB_PAGE_STEP_MINIMUM_MS,\n minimumMsFor: aiPageJobRunMinimumMs,\n })\n registerAiJobStepPasses('page', AI_JOB_PAGE_MAX_PASSES)\n registerAiJobAdmission('page', aiPageJobAdmission)\n}\n"],"names":["throwIfAiJobCanceled","buildPageMarkdown","SCREEN_SEO_TEXT_GUIDANCE","SCREEN_ROOT_PATH","screenRoutePathToUrl","CANVAS_ROOT_ELEMENT_ID","duplicateResource","AI_BUILD_PLAN_LIMITS","aiPlanEmbedsFor","AI_PAGE_CREATE_KINDS","aiPageCreationRefusal","aiPagePlanRefusal","parseAiPageJobInputs","aiPlanCapabilitiesForJob","aiPlanUncreatable","aiSiteWords","aiModelForStep","aiDoctrineNeedsInputMessage","runValidatedGeneration","aiClipAtWord","aiSettleMechanicalRules","aiSettlePlaceholderItems","aiSettleUnrelatedScreenLinks","validateAiDoctrineTree","aiHasPlaceholderToken","AI_SEO_FIELDS_MAX_TOKENS","generateSeoFields","readSiteInventory","registerAiJobAdmission","aiGenerationWorstCaseMs","aiJobDraftId","aiOriginJobId","aiBuildsWithComponents","aiDraftAdmissionRefusal","aiDraftAllowanceRefusal","aiSiteSubdomain","readAiDraft","readAiDraftNodes","readAiPlanCapabilities","updateAiDraftNodes","writeAiDraft","writeAiDraftScreenSeo","aiBracketedFactsNote","aiConfirmedPlan","aiDoctrineReview","aiGenerationSpent","aiLimitReview","aiModelNodeIds","aiUnspentOutcome","AI_JOB_PAGE_SECTION_MAX_TOKENS","AI_JOB_PAGE_SECTION_TOKENS","AI_JOB_PAGE_STEP_BUDGET","AI_JOB_PAGE_STEP_MINIMUM_MS","aiJobPageSectionMaxTokens","AI_JOB_PAGE_INSTRUCTIONS","AI_PAGE_SECTION_TOOL","aiEmptyPage","aiPageCheckContext","aiPageLinkablePages","aiPageRecordNote","aiPageRecordTemplate","aiPageRecordTokens","aiPageSectionCheck","aiPageSectionNodeId","aiPageSectionPrompt","aiPageSectionSmaller","aiPageSectionWithRecordImage","aiPageWithSection","aiLayoutSitePages","aiResolveLayoutPictures","AI_STOCK_PHOTO_AVOID_INPUT","AI_STOCK_PHOTO_PAGES_INPUT","aiLayoutStockPhotoSource","aiStockPhotoWordsOf","aiStockPlacedSrcs","AI_PLAN_ITEMS_MIN","aiPlanCopiedPageViolations","AI_JOB_PAGE_LANGUAGE_BUDGET","aiJobUsesLayoutLanguage","aiLayoutListingContext","aiLayoutPageTargets","aiLayoutLeftOutNote","aiLayoutMotionSiteOf","aiRunLayoutPage","aiWithSiteMotion","aiCreationUnit","aiRunJobUnit","aiSiteBuiltRefs","aiSitePendingUnits","aiSiteUnitJob","aiJobStepRunMinimumMs","aiJobStepRunnerFor","registerAiJobStep","registerAiJobStepPasses","AI_JOB_PAGE_TOKENS_PER_ELEMENT","AI_JOB_PAGE_REAL_TOKENS_PER_ESTIMATED","Math","max","AI_JOB_PAGE_REAL_TOKENS_PER_ELEMENT","ceil","aiJobPageSectionMaxElements","maxTokens","floor","AI_JOB_PAGE_DEFAULT_NAME","AI_JOB_PAGE_NO_PLAN_COPY","AI_JOB_PAGE_DELETED_COPY","AI_JOB_PAGE_CREATION_UNAVAILABLE_COPY","AI_JOB_PAGE_CREATION_EMPTY_COPY","AI_JOB_PAGE_REFUSED_DRAFT_COPY","AI_JOB_PAGE_MAX_PASSES","create","sections","aiPageJobUnits","plan","flatMap","kind","creation","index","unit","aiPageJobRunMinimumMs","job","confirmed","pagePass","minimumMs","units","outputs","aiPageDraftSlug","screen","segments","slug","split","map","part","trim","filter","Boolean","length","aiSiteDefaultLayoutId","inventory","counts","layouts","Set","row","id","size","pages","screens","template","layoutId","has","home","find","Map","set","get","mostUsed","entries","sort","a","b","aiPageDraftLayoutId","layout","some","siteNameOf","host","text","value","aiCopiedPageReview","firestore","input","section","items","stored","hostId","nodes","reason","message","name","findings","violations","rootId","aiPageJobAdmission","context","inputs","status","error","refusal","jobKind","org","orgId","noun","ownCheck","capabilities","creates","aiPageStartPage","readNodes","duplicateOf","one","replaceable","undefined","catch","label","aiJobPagesPlacedPhotos","listed","ids","Array","isArray","draftId","elsewhere","shown","src","startsWith","read","Promise","all","createAiJobPageStep","deps","readInventory","duplicate","seoFields","runnerFor","stepContext","orgSnapshot","now","signal","modelFor","Error","model","failure","runner","pass","emptyCopy","built","outcome","continue","resource","slot","title","sectionIds","_","$id","output","draft","load","note","versionId","hostSubdomain","nav","proposal","navigation","written","collection","doc","data","deleted","record","recordNote","copiesStarter","generatedWhole","sourceReview","sourceShort","copy","sourceId","uid","createdBy","attemptKey","ok","review","page","findIndex","reusableComponents","embeds","linkablePages","linkTarget","language","checked","recordTokens","codeBuilt","repeatsCompiled","own","motion","settle","tree","settled","ownScreenIds","moved","update","next","report","scrollTargetIds","join","reported","entry","reports","storedIds","sourceIds","violation","nodeIds","answer","then","spent","seo","description","seoModel","values","seoTitle","seoDescription","lookups","result","subject","path","brand","site","fields","otherTitles","usable","allowance","targets","startsFrom","refused","sectionNames","seed","avoid","photoWords","pictured","source","stockPhotos","business","about","jobId","aiJobId","maxElements","step","instructions","messages","role","content","tool","cutOff","smaller","thinking","check","runAiJobPageStep","registerAiPageJob","minimumMsFor"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,qBAAiB;AACtD,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,wBAAwB,QAAQ,2CAA0C;AACnF,SAASC,gBAAgB,EAAEC,oBAAoB,QAAQ,sCAAqC;AAC5F,SAASC,sBAAsB,QAAQ,2CAA0C;AAEjF,SAASC,iBAAiB,QAAQ,qDAAoD;AACtF,SAASC,oBAAoB,EA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BAAqBgO;YACrB,MAAM8D,SAAS,MAAMvP,mBAAmBiI,WAAW;gBACjDrD,MAAM;gBACN0D;gBACA9B,IAAIgE;gBACJgB;gBACA,0EAA0E;gBAC1E+D,QAAQ,CAAChH,QACPJ,QAAQU,MAAM,IAAIN,QAAQ,OAAO3G,kBAAkB2G,OAAOJ,SAASoE;YACvE;YACA,IAAIgD,OAAOpB,EAAE,KAAK,OAAO,OAAO,aAAKkC;gBAAOxE,SAAS3H;;QACvD;QACA,OAAO,aAAKmM;YAAOlE,UAAU;;IAC/B;AACF;AAEA,OAAO,MAAM4G,mBAAmB/H,sBAAqB;AAErD;;;;CAIC,GACD,OAAO,SAASgI;IACd3P,kBAAkB,QAAQ0P,kBAAkB;QAC1C3N,WAAWvE;QACXoS,cAAcjO;IAChB;IACA1B,wBAAwB,QAAQgB;IAChCjF,uBAAuB,QAAQyJ;AACjC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-page-step.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { throwIfAiJobCanceled } from './ai-job-cancel'\nimport { buildPageMarkdown } from '@aglyn/aglyn/app-utils/page-markdown'\nimport { SCREEN_SEO_TEXT_GUIDANCE } from '@aglyn/aglyn/app-utils/screen-seo-fields'\nimport { SCREEN_ROOT_PATH, screenRoutePathToUrl } from '@aglyn/aglyn/app-utils/screen-route'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport { duplicateResource } from '@aglyn/tenant-data-admin/server/duplicate-resource'\nimport { AI_BUILD_PLAN_LIMITS, aiPlanEmbedsFor, type AiBuildPlanScreen } from '../model/ai-build-plan'\nimport {\n AI_PAGE_CREATE_KINDS,\n aiPageCreationRefusal,\n aiPagePlanRefusal,\n parseAiPageJobInputs,\n} from '../model/ai-page-job'\nimport { aiPlanCapabilitiesForJob, aiPlanUncreatable } from '../model/ai-plan-capabilities'\nimport { aiSiteWords } from '../model/ai-site-job'\nimport type { AiJob, AiJobOutput, AiJobPlan, AiJobReview } from '../model/ai-jobs.types'\nimport { aiModelForStep } from '../providers/routing'\nimport { aiDoctrineNeedsInputMessage, runValidatedGeneration } from '../runtime/ai-doctrine'\nimport {\n aiClipAtWord,\n aiSettleMechanicalRules,\n aiSettlePlaceholderItems,\n aiSettleUnrelatedScreenLinks,\n validateAiDoctrineTree,\n type AiDoctrineTree,\n} from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { aiHasPlaceholderToken } from '../runtime/ai-placeholder-tokens'\nimport { AI_SEO_FIELDS_MAX_TOKENS, generateSeoFields } from '../runtime/seo-fields'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport type { AiSiteInventory } from '../model/ai-site-inventory'\nimport { registerAiJobAdmission, type AiJobAdmission } from './ai-job-admission'\nimport { aiGenerationWorstCaseMs } from './ai-job-budget'\nimport { aiJobDraftId, aiOriginJobId } from './ai-job-draft-ids'\nimport {\n aiBuildsWithComponents,\n aiDraftAdmissionRefusal,\n aiDraftAllowanceRefusal,\n aiSiteSubdomain,\n readAiDraft,\n readAiDraftNodes,\n readAiPlanCapabilities,\n updateAiDraftNodes,\n writeAiDraft,\n writeAiDraftScreenSeo,\n type AiDraftRecord,\n} from './ai-job-drafts'\nimport {\n aiBracketedFactsNote,\n aiConfirmedPlan,\n aiDoctrineReview,\n aiGenerationSpent,\n aiLimitReview,\n aiModelNodeIds,\n aiUnspentOutcome,\n} from './ai-job-generation'\nimport {\n AI_JOB_PAGE_SECTION_MAX_TOKENS,\n AI_JOB_PAGE_SECTION_TOKENS,\n AI_JOB_PAGE_STEP_BUDGET,\n AI_JOB_PAGE_STEP_MINIMUM_MS,\n aiJobPageSectionMaxTokens,\n} from './ai-job-page-budget'\nimport {\n AI_JOB_PAGE_INSTRUCTIONS,\n AI_PAGE_SECTION_TOOL,\n aiEmptyPage,\n aiPageCheckContext,\n aiPageLinkablePages,\n aiPageRecordNote,\n aiPageRecordTemplate,\n aiPageRecordTokens,\n aiPageSectionCheck,\n aiPageSectionNodeId,\n aiPageSectionPrompt,\n aiPageSectionSmaller,\n aiPageSectionWithRecordImage,\n aiPageWithSection,\n type AiPageSection,\n} from './ai-job-page-sections'\nimport { aiLayoutSitePages } from './ai-job-layout-site-pages'\nimport { aiResolveLayoutPictures } from '../layout-language/ai-layout-pictures'\nimport { aiLayoutSitePhotoSource } from './ai-layout-owner-photos'\nimport {\n AI_STOCK_PHOTO_AVOID_INPUT,\n AI_STOCK_PHOTO_PAGES_INPUT,\n aiLayoutStockPhotoSource,\n aiStockPhotoWordsOf,\n aiStockPlacedSrcs,\n} from './ai-layout-stock-photos'\nimport { AI_PLAN_ITEMS_MIN, aiPlanCopiedPageViolations } from './ai-job-plan-conformance'\nimport {\n AI_JOB_PAGE_LANGUAGE_BUDGET,\n aiJobUsesLayoutLanguage,\n aiLayoutListingContext,\n aiLayoutPageTargets,\n aiLayoutLeftOutNote,\n aiLayoutMotionSiteOf,\n aiRunLayoutPage,\n type AiLayoutStartPage,\n} from './ai-job-page-language'\nimport { aiWithSiteMotion } from '../layout-language/ai-layout-motion'\nimport {\n aiCreationUnit,\n aiRunJobUnit,\n aiSiteBuiltRefs,\n aiSitePendingUnits,\n aiSiteUnitJob,\n type AiSiteUnit,\n} from './ai-job-site-step'\nimport type { AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\nimport {\n aiJobStepRunMinimumMs,\n aiJobStepRunnerFor,\n registerAiJobStep,\n registerAiJobStepPasses,\n} from './ai-jobs'\n\n/**\n * The page step (AGL-2907): the generation step of a `page` job, run once a\n * member confirmed the job's plan. It builds ONE screen, section by section,\n * from what the site already has, and leaves it an unpublished draft.\n *\n * ── Why a page is built in passes ────────────────────────────────────────\n *\n * A page is far larger than one answer the job beat can wait for: the beat\n * gives a step what is left of its budget, and a whole page, answered and re-asked,\n * takes several times that. The confirmed plan already names the page's\n * sections, so the step builds one section per pass and asks the machine to\n * continue. Every pass is one reservation and one generation — the section's\n * lookup rounds, its answer and, when it breaks a rule, its one re-ask — sized\n * so that worst case fits `AI_JOB_PAGE_STEP_MINIMUM_MS`, which the step\n * registers as the least time a section pass needs before it starts.\n *\n * - The first pass builds the top section, which holds the page's h1, and\n * writes the draft screen and its first version.\n * - Each later pass builds the next section and adds it to that version.\n * - The last pass generates no tree: it holds the whole page to the\n * doctrine, writes the search title and description, and reports the\n * draft with its measured weight and a navigation proposal.\n *\n * How a section is asked for and held to the rules as part of the page is\n * `ai-job-page-sections.ts`.\n *\n * ── What the plan creates comes first (AGL-3031) ─────────────────────────\n *\n * A plan that creates a layout, forms or components is built in the same job,\n * before its page, one creation a pass, through the site scaffold's unit\n * machinery: each creation is handed to the step that builds that kind, under\n * a job derived from this one, and lands as the draft that step writes. Where\n * the job stands is read from its outputs, so nothing is kept anywhere else.\n * Once every creation is built, the page's passes run on the plan with each\n * `new:<name>` resolved to the record that was built, which the site's\n * inventory now lists — so the page places the new component and binds the new\n * form by id, and renders inside the new layout, exactly as it would one the\n * site always had. A pass that builds a creation needs the time the step that\n * builds it registers, not a section's (`aiPageJobRunMinimumMs`, AGL-3035), so\n * neither the beat nor a door starts it with only a section's time left.\n *\n * ── Never published ──────────────────────────────────────────────────────\n *\n * The draft is written the way `/api/hosts/resources` and\n * `/api/hosts/versions` write a screen and its first version, and nothing\n * else is touched: not the host document, whose routing map is what the live\n * site serves, and no collection, store, layout or navigation pointer\n * (`ai-job-drafts.ts`). A screen the routing map does not name serves nothing\n * until a member publishes it.\n */\n\n/**\n * A section pass's time, and the ceiling each pass asks on each model, are\n * declared apart from the step (`ai-job-page-budget.ts`): the site scaffold\n * builds its pages through this step and reads them without loading it.\n */\nexport {\n AI_JOB_PAGE_SECTION_MAX_TOKENS,\n AI_JOB_PAGE_SECTION_TOKENS,\n AI_JOB_PAGE_STEP_BUDGET,\n AI_JOB_PAGE_STEP_MINIMUM_MS,\n aiJobPageSectionMaxTokens,\n}\n\n/**\n * Tokens one element takes in a section's answer, ESTIMATED: the tree as JSON\n * text inside the tool call, at four characters a token. Measured on the ten\n * golden pages at a median of 38 and a most of 43 over their 39 sections, and\n * `ai-job-page-evals.spec.ts` holds every golden section under it.\n */\nexport const AI_JOB_PAGE_TOKENS_PER_ELEMENT = 45\n\n/**\n * Real tokens to every token estimated at four characters (AGL-3042). A\n * section's ceiling is counted by the provider in its own tokens, which run\n * above that estimate. MEASURED on the first live document run on a Free\n * workspace (AGL-3024, test-org, 2026-09-16), as the cache read of a request\n * over the estimate of the same cached prefix: 4,059 over 2,825 for the page\n * plan and 6,649 over 4,310 for the layout, the higher of the two, 1.5427 —\n * the ratio `ai-job-free-page.spec.ts` prices a Free page at. It is measured on\n * prompt text; an answer's own is read off a recorded pass, whose output\n * tokens the step's record keeps (`lastRuns`), beside the section it stored.\n */\nexport const AI_JOB_PAGE_REAL_TOKENS_PER_ESTIMATED = Math.max(4_059 / 2_825, 6_649 / 4_310)\n\n/**\n * Real tokens one element takes in a section's answer: the estimate at its\n * golden most, in real tokens, rounded up — 45 × 1.5427 → 70 (AGL-3042).\n */\nexport const AI_JOB_PAGE_REAL_TOKENS_PER_ELEMENT = Math.ceil(\n AI_JOB_PAGE_TOKENS_PER_ELEMENT * AI_JOB_PAGE_REAL_TOKENS_PER_ESTIMATED,\n)\n\n/**\n * The most elements a section's request asks it to keep under at an answer\n * ceiling: 15 at the balanced tier's 1,050 (AGL-3042). Counted in real\n * tokens, because the ceiling is: counted in the estimate, the budget is 23\n * elements, which a section of the goldens' largest elements fills at 1,597\n * real tokens — half as much again as the ceiling that cuts it off.\n */\nexport function aiJobPageSectionMaxElements(maxTokens: number): number {\n return Math.max(1, Math.floor(maxTokens / AI_JOB_PAGE_REAL_TOKENS_PER_ELEMENT))\n}\n\n/** A page's name when the plan names none. */\nexport const AI_JOB_PAGE_DEFAULT_NAME = 'New page'\n\nexport const AI_JOB_PAGE_NO_PLAN_COPY = 'This page job has no confirmed plan to build.'\nexport const AI_JOB_PAGE_DELETED_COPY = 'The draft page was deleted while it was being built.'\n\n/** A creation the plan names that this deployment has no step to build. */\nexport const AI_JOB_PAGE_CREATION_UNAVAILABLE_COPY =\n 'This page needs something that cannot be built here yet. Describe the page again.'\n\n/** A creation that finished without reporting what it built; the page cannot place it. */\nexport const AI_JOB_PAGE_CREATION_EMPTY_COPY =\n 'Part of this page could not be built. Describe the page again.'\n\n/**\n * What a page refused on its last pass tells the member after the plain\n * refusal (AGL-3143, AGL-3596). The draft is reported with the review, and\n * mending its layout in the editor is what lets the next pass finish the job.\n */\nexport const AI_JOB_PAGE_REFUSED_DRAFT_COPY = 'The draft is yours to open: fix its layout in the editor, then try again.'\n\n/**\n * The most passes a page job may take (AGL-3031): every creation the plan\n * limits admit, every section they admit, and the last pass that reports the\n * draft. A creation's step builds it in one pass, and a page one section a\n * pass, so a runner that never finishes is still bounded while a real page is\n * not.\n */\nexport const AI_JOB_PAGE_MAX_PASSES = AI_BUILD_PLAN_LIMITS.create + AI_BUILD_PLAN_LIMITS.sections + 1\n\n/**\n * The units a plan's creations are built as, in the order a scaffold builds\n * them: the layout, then the forms, then the components. Each is addressed by\n * its place in the plan, so a unit run again finds its own draft.\n */\nexport function aiPageJobUnits(plan: Pick<AiJobPlan, 'create'>): AiSiteUnit[] {\n return AI_PAGE_CREATE_KINDS.flatMap((kind) =>\n plan.create.flatMap((creation, index) => {\n if (creation.kind !== kind) return []\n const unit = aiCreationUnit(creation, `c${index}`)\n return unit ? [unit] : []\n }),\n )\n}\n\n/**\n * The least time this page job's next pass needs (AGL-3035). A pass that\n * builds a creation hands it to the step registered for that kind, under the\n * job derived for it, so it needs what that step registers for that job — a\n * layout's time, not a section's. Every other pass — a section, the last one —\n * needs a section pass's.\n */\nexport function aiPageJobRunMinimumMs(job: AiJob): number {\n const confirmed = aiConfirmedPlan(job)\n // A page built in the layout language is one answer for the whole page (AGL-3660).\n const pagePass = aiJobUsesLayoutLanguage(job) ? AI_JOB_PAGE_LANGUAGE_BUDGET.minimumMs : AI_JOB_PAGE_STEP_MINIMUM_MS\n if (!confirmed) return pagePass\n const units = aiPageJobUnits(confirmed)\n const outputs = job.outputs ?? []\n const [unit] = aiSitePendingUnits(units, outputs)\n if (!unit) return pagePass\n return aiJobStepRunMinimumMs(aiSiteUnitJob(job, unit, aiSiteBuiltRefs(units, outputs)))\n}\n\n/**\n * The one-segment address a draft asks for, from the plan's slug; `/` for a\n * planned home page, which asks for the root rather than for an address made\n * from its name (AGL-3596).\n */\nexport function aiPageDraftSlug(screen: Pick<AiBuildPlanScreen, 'slug'>): string {\n const segments = screen.slug.split('/').map((part) => part.trim()).filter(Boolean)\n if (!segments.length && screen.slug.trim() === SCREEN_ROOT_PATH) return SCREEN_ROOT_PATH\n return segments[segments.length - 1] ?? ''\n}\n\n/**\n * The layout a site's pages render inside (AGL-3596): the one its home page\n * uses, else the one the most pages use, else the site's only layout. `null`\n * for a site with no layout, or several and no page to choose between them.\n */\nexport function aiSiteDefaultLayoutId(\n inventory: Pick<AiSiteInventory, 'layouts' | 'screens'>,\n): string | null {\n const layouts = new Set(inventory.layouts.map((row) => row.id))\n if (!layouts.size) return null\n const pages = inventory.screens.filter(\n (row) => !row.template && row.layoutId && layouts.has(row.layoutId),\n )\n const home = pages.find((row) => row.slug.trim() === SCREEN_ROOT_PATH)\n if (home?.layoutId) return home.layoutId\n const counts = new Map<string, number>()\n for (const row of pages) counts.set(row.layoutId as string, (counts.get(row.layoutId as string) ?? 0) + 1)\n const [mostUsed] = [...counts.entries()].sort((a, b) => b[1] - a[1])\n if (mostUsed) return mostUsed[0]\n return layouts.size === 1 ? [...layouts][0] : null\n}\n\n/**\n * The layout a page draft renders inside: the plan's, where the site has it,\n * else the site's own (AGL-3596). A page the plan named no layout for used to\n * be written with none, and so with no header and no footer, beside pages\n * that had them.\n */\nexport function aiPageDraftLayoutId(\n screen: Pick<AiBuildPlanScreen, 'layout'>,\n inventory: Pick<AiSiteInventory, 'layouts' | 'screens'>,\n): string | null {\n if (screen.layout && inventory.layouts.some((row) => row.id === screen.layout)) return screen.layout\n return aiSiteDefaultLayoutId(inventory)\n}\n\n/** The site's name as its visitors see it, read the way the SEO step reads it. */\nfunction siteNameOf(host: FirebaseFirestore.DocumentSnapshot): string {\n const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '')\n return text(host.get('seo.title')) || text(host.get('displayName')) || text(host.get('subdomain'))\n}\n\n/**\n * The counts the confirmed plan's sections promised, against the page a COPY\n * actually produced (AGL-3024); `null` when the copy keeps the plan, or when\n * the plan promised no count to keep.\n *\n * The same hole the layout copy had (`aiCopiedLayoutReview`), on the kind the\n * defect was measured on. This branch generates nothing, so no model ever\n * answers for the plan: a plan reading \"start from the Services page, one\n * card per practice area\" gets the Services page and whatever IT had, and\n * until now reported `Done` — the one report that tells a customer there is\n * no reason to re-read the page.\n *\n * A copy that cannot be read back settles nothing, and a promise this step\n * cannot settle is reviewed by a person rather than reported as kept.\n */\nexport async function aiCopiedPageReview(\n firestore: FirebaseFirestore.Firestore,\n input: { hostId: string; id: string; name: string; screen: Pick<AiBuildPlanScreen, 'sections'> },\n): Promise<AiJobReview | null> {\n if (!input.screen.sections.some((section) => section.items >= AI_PLAN_ITEMS_MIN)) return null\n const stored = await readAiDraftNodes(firestore, { kind: 'screen', hostId: input.hostId, id: input.id })\n const nodes = (stored?.nodes ?? {}) as unknown as AiDoctrineTree['nodes']\n if (!nodes[CANVAS_ROOT_ELEMENT_ID]) {\n return {\n reason: 'doctrine',\n message: `\"${input.name}\" was copied from the page the plan names, and this job could not read the copy back to check it shows what the plan says it shows. Open the page and check it before you put it in front of anyone.`,\n findings: [],\n }\n }\n const violations = aiPlanCopiedPageViolations(input.screen, { rootId: CANVAS_ROOT_ELEMENT_ID, nodes })\n if (!violations.length) return null\n return aiDoctrineReview({\n message: `\"${input.name}\" is a copy of the page the plan names, and a copy is all it is: ${violations[0].message}`,\n violations,\n })\n}\n\n/**\n * A page job is admitted with inputs that read, for a site of the job's own\n * org with a screen to spare; and confirmed only for a plan it can build —\n * one screen, whose creations are ones a page job builds, this deployment has\n * a step for, and this workspace may still make on this site (AGL-3031).\n */\nexport const aiPageJobAdmission: AiJobAdmission = async (context) => {\n const inputs = parseAiPageJobInputs(context.inputs)\n if (typeof inputs === 'string') return { status: 400, error: inputs }\n const plan = context.plan\n if (plan) {\n const refusal = aiPagePlanRefusal(plan)\n if (refusal) return { status: 400, error: refusal }\n if (aiPageJobUnits(plan).some((unit) => !aiJobStepRunnerFor(unit.jobKind))) {\n return { status: 400, error: AI_JOB_PAGE_CREATION_UNAVAILABLE_COPY }\n }\n }\n const org = context.org as Partial<AglynOrgBilling> | null\n return aiDraftAdmissionRefusal(context.firestore, {\n orgId: context.orgId,\n hostId: context.hostId,\n kind: 'screen',\n noun: 'page',\n org,\n // What the workspace may still make here, read once the site is known to\n // be the org's: the site may have changed since the plan was told.\n ...(plan?.create.length\n ? {\n ownCheck: async (hostId: string) => {\n const capabilities = aiPlanCapabilitiesForJob(\n await readAiPlanCapabilities(context.firestore, { hostId, org }),\n { noun: 'a page job', creates: AI_PAGE_CREATE_KINDS },\n )\n const refusal = aiPageCreationRefusal(aiPlanUncreatable(plan, capabilities))\n return refusal ? { status: 403 as const, error: refusal } : null\n },\n }\n : {}),\n })\n}\n\n/**\n * The site's page a page of a build or a site starts from (AGL-3832): the\n * plan's `duplicateOf`, by its name and its words, for the page's prompt.\n * Only a page the site has, and never its starter home page, which is a\n * placeholder rather than words of the owner's (AGL-3596) — nor an entry\n * template, whose words are its records'. `null` when there is no such page\n * or its words cannot be read: the page is then built from its plan alone.\n */\nexport async function aiPageStartPage(\n firestore: Parameters<typeof readAiDraftNodes>[0],\n input: { hostId: string; screen: Pick<AiBuildPlanScreen, 'duplicateOf'>; inventory: Pick<AiSiteInventory, 'screens'> },\n readNodes: typeof readAiDraftNodes = readAiDraftNodes,\n): Promise<AiLayoutStartPage | null> {\n const id = input.screen.duplicateOf\n const row = id ? input.inventory.screens.find((one) => one.id === id && !one.template && !one.replaceable) : undefined\n if (!row) return null\n const stored = await readNodes(firestore, { kind: 'screen', hostId: input.hostId, id: row.id }).catch(() => null)\n const text = stored ? buildPageMarkdown({ nodes: stored.nodes as never, rootId: CANVAS_ROOT_ELEMENT_ID }).trim() : ''\n return text ? { label: row.name, text } : null\n}\n\n/**\n * The library photos the job's other pages already show (AGL-3660): read\n * from the screen drafts a site job names for its page unit\n * (`AI_STOCK_PHOTO_PAGES_INPUT`), never this page's own, so a pass repeated\n * over it keeps its photos, and those its datasets' records show\n * (`AI_STOCK_PHOTO_AVOID_INPUT`, AGL-3616). Empty on any failure: a repeat is better than a\n * page that fails over decoration.\n */\nexport async function aiJobPagesPlacedPhotos(\n firestore: Parameters<typeof readAiDraftNodes>[0],\n input: { hostId: string; job: Pick<AiJob, 'inputs'>; draftId: string },\n readNodes: typeof readAiDraftNodes = readAiDraftNodes,\n): Promise<string[]> {\n const listed = input.job.inputs?.[AI_STOCK_PHOTO_PAGES_INPUT]\n const ids = Array.isArray(listed)\n ? [...new Set(listed.filter((id): id is string => typeof id === 'string' && !!id && id !== input.draftId))]\n : []\n // What the site's datasets' records show (AGL-3616), named by the job.\n const elsewhere = input.job.inputs?.[AI_STOCK_PHOTO_AVOID_INPUT]\n const shown = Array.isArray(elsewhere)\n ? elsewhere.filter((src): src is string => typeof src === 'string' && src.startsWith('media:'))\n : []\n if (!ids.length) return [...new Set(shown)]\n const read = await Promise.all(\n ids.map((id) => readNodes(firestore, { kind: 'screen', hostId: input.hostId, id }).catch(() => null)),\n )\n return [...new Set([...shown, ...read.flatMap((stored) => aiStockPlacedSrcs(stored?.nodes))])]\n}\n\nexport interface AiJobPageStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** The platform's duplicate module, for a plan that starts from a copy. */\n duplicate?: typeof duplicateResource\n /** The listing generator (AGL-2910). */\n seoFields?: typeof generateSeoFields\n /** The runners a plan's creations are built by (AGL-3031); the registry's otherwise. */\n runnerFor?: typeof aiJobStepRunnerFor\n /** The stock photo source of a language page's pictures (AGL-3660); core's provider otherwise. */\n stockPhotos?: typeof aiLayoutStockPhotoSource\n}\n\nexport function createAiJobPageStep(deps: AiJobPageStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const duplicate = deps.duplicate ?? duplicateResource\n const seoFields = deps.seoFields ?? generateSeoFields\n const runnerFor = deps.runnerFor ?? aiJobStepRunnerFor\n return async (stepContext): Promise<AiJobStepOutcome> => {\n const { job, now, signal, firestore, modelFor } = stepContext\n const hostId = job.hostId\n if (!hostId) throw new Error('a page job names no site, and its admission refuses one')\n // The switch's answer for this job, else the routing table's (AGL-2942).\n const model = modelFor?.('job.page') ?? aiModelForStep('job.page')\n const confirmed = aiConfirmedPlan(job)\n if (!confirmed) return { ...aiUnspentOutcome(model), failure: AI_JOB_PAGE_NO_PLAN_COPY }\n // The resume door refuses such a plan at confirmation; one confirmed\n // before a site changed still stops here, before any spend.\n const refusal = aiPagePlanRefusal(confirmed)\n if (refusal) return { ...aiUnspentOutcome(model), failure: refusal }\n\n // ── The creations first (AGL-3031): one a pass, by the steps that own them ──\n const units = aiPageJobUnits(confirmed)\n const outputs = job.outputs ?? []\n const [unit] = aiSitePendingUnits(units, outputs)\n if (unit) {\n const runner = runnerFor(unit.jobKind)\n if (!runner) return { ...aiUnspentOutcome(model), failure: AI_JOB_PAGE_CREATION_UNAVAILABLE_COPY }\n const pass = await aiRunJobUnit(stepContext, {\n unit,\n units,\n runner,\n emptyCopy: AI_JOB_PAGE_CREATION_EMPTY_COPY,\n })\n // A built creation is followed by the next, or by the page's first section.\n return pass.built ? { ...pass.outcome, continue: true } : pass.outcome\n }\n // The page's plan with every creation resolved to the record it built, as\n // a scaffold's page is planned against what the scaffold built.\n const plan: AiJobPlan = units.length\n ? (aiSiteUnitJob(\n job,\n {\n kind: 'page',\n jobKind: 'page',\n resource: 'screen',\n slot: 'page',\n screen: confirmed.screens[0],\n label: confirmed.screens[0].title,\n },\n aiSiteBuiltRefs(units, outputs),\n ).plan as AiJobPlan)\n : confirmed\n const screen = plan.screens[0] as AiBuildPlanScreen\n const name = screen.title || AI_JOB_PAGE_DEFAULT_NAME\n const slug = aiPageDraftSlug(screen)\n const sectionIds = screen.sections.map((_, index) => aiPageSectionNodeId(job.$id, index))\n // The draft screen, by the id the job recorded for it: every pass writes and finds the same one.\n const draftId = aiJobDraftId(job, 'screen')\n\n const output = (\n draft: Pick<AiDraftRecord, 'id' | 'versionId' | 'name' | 'hostSubdomain'>,\n load?: AiLoadEstimate | null,\n note?: string | null,\n ): AiJobOutput => ({\n resource: 'screen',\n id: draft.id,\n versionId: draft.versionId,\n hostId,\n hostSubdomain: draft.hostSubdomain,\n label: draft.name,\n ...(load ? { load } : {}),\n ...(note ? { note } : {}),\n // Rule 10: a navigation entry travels with the page as a proposal, for\n // the member to add once the page is live; no menu is written.\n ...(screen.nav ? { proposal: { navigation: { label: name, slug } } } : {}),\n })\n\n const [inventory, orgSnapshot, written] = await Promise.all([\n readInventory(job.orgId, hostId, { firestore }),\n firestore.collection('orgs').doc(job.orgId).get(),\n readAiDraft(firestore, { kind: 'screen', hostId, id: draftId }),\n ])\n const org = (orgSnapshot.data() ?? null) as Partial<AglynOrgBilling> | null\n if (written?.deleted) return { ...aiUnspentOutcome(model), failure: AI_JOB_PAGE_DELETED_COPY }\n // A record template's copy binds its dataset's fields, and its draft says\n // where the member saves the binding (AGL-3475).\n const record = aiPageRecordTemplate(screen.record, inventory, plan)\n const recordNote = record ? aiPageRecordNote(record) : null\n\n // A page job's plan starts from a copy of a screen the site has (rule\n // 15): the copy is the draft — unrouted, as every copy is — and nothing\n // is generated.\n // Only a page is a page's start: a collection entry template's copy stays\n // a template, so a plan naming one builds the page instead.\n // A copy shows what its SOURCE shows, and this branch generates nothing.\n // So if the source cannot already show what the plan promised, copying it\n // can only produce a page that breaks the promise — the refusal below\n // would be certain before the copy was ever minted. Read the source and\n // build instead, rather than leave the member a page they must throw away\n // and a Try again that can only copy the same thing (AGL-3024).\n // Only a source we could READ and found short diverts: one we cannot read\n // is one we cannot judge, and the review after the copy still answers for\n // that. A short source carries findings; an unreadable one carries none.\n // A copy of the starter home page is never a page the job built\n // (AGL-3596): the site's own placeholder is replaced by a page generated\n // from the plan, so a plan that names it as a start builds instead.\n const copiesStarter = Boolean(\n screen.duplicateOf &&\n inventory.screens.some((row) => row.id === screen.duplicateOf && row.replaceable),\n )\n // A page a build or a site makes (every one designed in the layout\n // language) counts as built only once its plan's sections are in it,\n // under the ids this step writes them by (AGL-3596). A copy holds its\n // source's sections under the source's ids, so it never counts: a build\n // that copied \"Our Story\" for its About page failed the page and left the\n // copy behind (AGL-3832). Such a page is generated from its plan, its\n // prompt shown the words of the page it starts from (`aiPageStartPage`).\n const generatedWhole = aiJobUsesLayoutLanguage(job)\n const sourceReview =\n !written && screen.duplicateOf && !copiesStarter && !generatedWhole\n ? await aiCopiedPageReview(firestore, { hostId, id: screen.duplicateOf, name, screen })\n : null\n const sourceShort = Boolean(sourceReview?.findings.length)\n if (\n !written &&\n !sourceShort &&\n !copiesStarter &&\n !generatedWhole &&\n screen.duplicateOf &&\n inventory.screens.some((row) => row.id === screen.duplicateOf && !row.template)\n ) {\n const copy = await duplicate('screen', {\n orgId: job.orgId,\n hostId,\n sourceId: screen.duplicateOf,\n name,\n uid: job.createdBy,\n org: org as Record<string, unknown> | null,\n // A copy core mints is written under core's id, never `draftId`, so\n // `written` above cannot find it and this branch would fire on every\n // pass — and the pass after a refused copy is the common one, since\n // the review below offers to try again. The job's recorded id is the\n // claim, so a second pass replays the one copy instead of leaving\n // another orphan screen behind it (AGL-3024).\n attemptKey: draftId,\n })\n if (copy.ok) {\n // A copy is not a build (AGL-3024). Nothing is generated here, so\n // whatever the plan promised BEYOND the source is in the draft only\n // if the source already had it, and no model is left to answer for\n // the difference — the copy itself has to.\n const review = await aiCopiedPageReview(firestore, { hostId, id: copy.id, name, screen })\n if (review) return aiUnspentOutcome(model, { review })\n const hostSubdomain = await aiSiteSubdomain(firestore, hostId)\n return aiUnspentOutcome(model, {\n outputs: [output({ id: copy.id, versionId: copy.versionId, name: copy.name, hostSubdomain }, null, recordNote)],\n })\n }\n if (copy.ok === false && copy.status === 403) {\n return aiUnspentOutcome(model, { review: aiLimitReview(copy.error) })\n }\n }\n\n const stored = written ? await readAiDraftNodes(firestore, { kind: 'screen', hostId, id: draftId }) : null\n if (written && !stored) return { ...aiUnspentOutcome(model), failure: AI_JOB_PAGE_DELETED_COPY }\n let page = stored?.nodes ?? aiEmptyPage()\n const index = sectionIds.findIndex((id) => !(id in page))\n // A workspace whose component allowance is finite — Free's one — draws\n // its repeats inline, and every pass is held to the rules that way\n // (AGL-3030, AGL-3615). A form is a saved one placed by id on every plan,\n // or none (AGL-3596).\n const reusableComponents = aiBuildsWithComponents(org)\n // A link may take a visitor to a section of this page, by its name in the plan (AGL-3097).\n const sections = screen.sections.map((section) => section.name)\n // A third-party player the confirmed plan lists for this page is the only one it may embed (AGL-3433).\n const embeds = aiPlanEmbedsFor(plan, { slug: screen.slug })\n // The site's other pages a link may go to, built or minted on a guided\n // start's plan, and the one a link that names none can only mean (AGL-3596).\n const { linkablePages, linkTarget } = aiPageLinkablePages(inventory, aiLayoutSitePages(job.inputs), [screen.id, draftId])\n // A page unit of a guided start or a build is designed in the layout\n // language and compiled (AGL-3660); a record template keeps the raw tree,\n // since its copy binds fields the language does not name.\n const language = aiJobUsesLayoutLanguage(job) && !record\n const checked = {\n ...aiPageCheckContext(inventory, {\n reusableComponents,\n sections,\n embeds,\n recordTokens: aiPageRecordTokens(record),\n linkablePages,\n }),\n // The last pass holds a compiled page to what its own check did: the\n // design's picture cards are the compiler's, not a block rule 1 asks a\n // component of (AGL-3660). Without it, a Pro store's Shop page passed\n // its check and was refused at the last pass (live run, 2026-10-09).\n ...(language ? { codeBuilt: true, repeatsCompiled: true } : {}),\n }\n // And a post's card in a section listing the blog links its post and shows\n // its cover by the tokens the page fills per post (AGL-3676), as its check admitted.\n const context = language\n ? aiLayoutListingContext(checked, aiLayoutPageTargets({ job, inventory, own: [screen.id, draftId] }))\n : checked\n\n // ── The last pass: the whole page, its listing, and the draft reported ──\n // A page in the layout language is written whole by one pass (AGL-3660),\n // so once written it is complete: a planned section missing from it was\n // taken out by its last answer, never one still to build (AGL-3771).\n if ((index === -1 || language) && written) {\n // An attribute a rule has one answer for is settled on the stored page\n // and stored (AGL-3660): this pass asks no model, so a page refused\n // here for one would be refused the same way on every Try again. A\n // Portfolio page whose opening photos all loaded eagerly was (2026-10-10).\n // And a link sent home for nothing is sent to the site's form, or left out (AGL-3729),\n // and an item of a list that shows only placeholders is taken out where the list keeps a real one (AGL-3827).\n // And the site's entrance motion is written on a page built a section at\n // a time, as on one built whole (AGL-3838); a page that already moves —\n // by this pass or by its author — comes back as it is, and is not written.\n const motion = aiLayoutMotionSiteOf(job, screen.slug)\n const settle = <T extends AiDoctrineTree>(tree: T): T => {\n const settled = aiSettleUnrelatedScreenLinks(\n aiSettlePlaceholderItems(aiSettleMechanicalRules(tree, 'page'), 'page', context),\n 'page',\n {\n ...context,\n ownScreenIds: [screen.id, draftId],\n },\n )\n const moved = aiWithSiteMotion(settled.nodes, motion, { sectionIds })\n return moved === settled.nodes ? settled : { ...settled, nodes: moved }\n }\n const settled = settle({ rootId: CANVAS_ROOT_ELEMENT_ID, nodes: page as unknown as AiDoctrineTree['nodes'] })\n if (settled.nodes !== (page as unknown as AiDoctrineTree['nodes'])) {\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const update = await updateAiDraftNodes(firestore, {\n kind: 'screen',\n hostId,\n id: draftId,\n now,\n update: (nodes) => {\n const tree = { rootId: CANVAS_ROOT_ELEMENT_ID, nodes: nodes as unknown as AiDoctrineTree['nodes'] }\n const next = settle(tree)\n return next === tree ? null : (next.nodes as unknown as typeof nodes)\n },\n })\n if (update.ok === false) return { ...aiUnspentOutcome(model), failure: AI_JOB_PAGE_DELETED_COPY }\n page = settled.nodes as unknown as typeof page\n }\n // A link the page carries to one of its sections goes there, now every section is built.\n const report = validateAiDoctrineTree({ rootId: CANVAS_ROOT_ELEMENT_ID, nodes: page }, 'page', {\n ...context,\n scrollTargetIds: sectionIds,\n })\n // The facts the brief did not give, on the page or in the defaults its components show (AGL-3056).\n const note =\n [\n aiBracketedFactsNote({\n tree: { rootId: CANVAS_ROOT_ELEMENT_ID, nodes: page as unknown as AiDoctrineTree['nodes'] },\n inventory,\n }),\n recordNote,\n // A section the last answer could not fill was left out, and the page says which (AGL-3771).\n language ? aiLayoutLeftOutNote(screen, sectionIds, page as unknown as Record<string, unknown>) : null,\n ]\n .filter(Boolean)\n .join(' ') || null\n // The page's own draft, reported once however many times the last pass\n // runs (AGL-3143): a refused pass reports it and a later one that\n // passes does not report it twice.\n const reported = outputs.some((entry) => entry.resource === 'screen' && entry.id === draftId)\n const reports = reported ? [] : [output(written, report.load, note)]\n if (report.violations.length) {\n // The check mints its own ids; the review names the nodes by the ids the draft stores them under.\n const storedIds = report.tree?.sourceIds ?? {}\n const violations = report.violations.map((violation) =>\n violation.nodeIds ? { ...violation, nodeIds: aiModelNodeIds(violation.nodeIds, storedIds) } : violation,\n )\n // THE DRAFT TRAVELS WITH THE REFUSAL (AGL-3143). Every other review\n // parks on a model's answer, so trying again asks the model again and\n // can come back different. This one reads the STORED page and spends\n // nothing, so trying again refuses the same page for the same reasons\n // forever — and a job parked here having reported no output names no\n // draft at all, which leaves the member nowhere to mend the nodes the\n // findings name and no way to finish the job from the console. The\n // draft is reported now instead, and the job still parks: what the\n // review names is mended in the draft, and the next pass then passes.\n return aiUnspentOutcome(model, {\n outputs: reports,\n review: aiDoctrineReview(\n {\n message: aiDoctrineNeedsInputMessage(violations),\n violations,\n answer: { tree: { rootId: CANVAS_ROOT_ELEMENT_ID, nodes: page } },\n },\n { page: true, then: AI_JOB_PAGE_REFUSED_DRAFT_COPY },\n ),\n })\n }\n let spent: AiJobStepOutcome = aiUnspentOutcome(model)\n if (!written.seo?.title?.trim() || !written.seo?.description?.trim()) {\n const seoModel = modelFor?.('job.seo') ?? aiModelForStep('job.seo')\n // The plan's own listing, held to the editor's guidance, when the\n // listing cannot be written inside this pass's time on the model the\n // job runs.\n let values = {\n title: aiClipAtWord(screen.seoTitle, SCREEN_SEO_TEXT_GUIDANCE.title, plan.language),\n description: aiClipAtWord(screen.seoDescription, SCREEN_SEO_TEXT_GUIDANCE.description, plan.language),\n }\n if (\n // A listing is written from the page's own text, with no inventory\n // and so no lookup round.\n aiGenerationWorstCaseMs({ maxTokens: AI_SEO_FIELDS_MAX_TOKENS, model: seoModel, lookups: 0 }) <=\n AI_JOB_PAGE_STEP_MINIMUM_MS\n ) {\n const host = await firestore.collection('hosts').doc(hostId).get()\n const result = await seoFields({\n subject: { kind: 'screen', name, path: screenRoutePathToUrl(slug || SCREEN_ROOT_PATH) },\n brand: siteNameOf(host),\n // What the site is and who it is for (AGL-2918). The page's own\n // Markdown says what the page is about and cannot say who it was\n // written for, so the listing borrows the two answers the job was\n // started from — the scaffold's derived page job carries them,\n // and a page job started from the Screens page carries neither.\n site: aiSiteWords(job.inputs),\n text: buildPageMarkdown({ nodes: page as never, rootId: CANVAS_ROOT_ELEMENT_ID }),\n fields: ['title', 'description'],\n // Other screens by name only: their own listings are their content.\n otherTitles: inventory.screens.map((row) => row.name),\n model: seoModel,\n ...(signal ? { signal } : {}),\n })\n spent = { ...spent, ...aiGenerationSpent(result) }\n if (result.status === 'ok') {\n // A written field that shows a placeholder keeps the plan's, which\n // the plan's own check already held to rule 14 (AGL-3827).\n const usable = (text: string | null | undefined): string =>\n text?.trim() && !aiHasPlaceholderToken(text) ? text.trim() : ''\n values = {\n title: usable(result.value.title) || values.title,\n description: usable(result.value.description) || values.description,\n }\n }\n }\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n await writeAiDraftScreenSeo(firestore, { hostId, id: draftId, seo: values, now })\n }\n return { ...spent, outputs: reports }\n }\n\n // ── A section pass ──\n if (!written) {\n const allowance = await aiDraftAllowanceRefusal(firestore, { kind: 'screen', hostId, org })\n if (allowance) return aiUnspentOutcome(model, { review: aiLimitReview(allowance) })\n }\n if (language) {\n // ── The whole page in one answer, in the layout language ──\n const targets = aiLayoutPageTargets({ job, inventory, own: [screen.id, draftId] })\n const startsFrom = await aiPageStartPage(firestore, { hostId, screen, inventory })\n const result = await aiRunLayoutPage({\n job,\n plan,\n screen,\n sectionIds,\n targets,\n context,\n reusableComponents,\n inventory,\n model,\n startsFrom,\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(result)\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') return { ...spent, review: aiDoctrineReview(result) }\n // The compiler leaves each picture slot empty; a photo the site serves\n // itself fills it here, after the page is checked (AGL-3660): a stock\n // photo copied into the site's library where the deployment has a\n // library, else a starter photo. No AI credits; never fails the job.\n const sectionNames = screen.sections.map((section) => section.name)\n const seed = `${aiOriginJobId(job)}:${screen.id ?? screen.slug}`\n // A photo another page of the job already shows is not placed here.\n const avoid = await aiJobPagesPlacedPhotos(firestore, { hostId, job, draftId })\n const photoWords = aiStockPhotoWordsOf(job)\n const pictured = await aiResolveLayoutPictures(result.value.nodes, {\n rootId: CANVAS_ROOT_ELEMENT_ID,\n sectionIds,\n sectionNames,\n seed,\n ...(photoWords.language ? { language: photoWords.language } : {}),\n // The owner's own photos first (AGL-3957), the stock library for the rest.\n source: (deps.stockPhotos ?? aiLayoutSitePhotoSource)({\n hostId,\n uid: job.createdBy,\n seed,\n business: aiSiteWords(job.inputs).about,\n ...photoWords,\n sectionNames,\n jobId: aiOriginJobId(job),\n ...(avoid.length ? { avoid } : {}),\n ...(signal ? { signal } : {}),\n }),\n })\n if (!written) {\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const draft = await writeAiDraft(firestore, {\n kind: 'screen',\n hostId,\n id: draftId,\n uid: job.createdBy,\n org,\n name,\n nodes: pictured,\n slug,\n layoutId: aiPageDraftLayoutId(screen, inventory),\n aiJobId: aiOriginJobId(job),\n now,\n })\n if (draft.ok === false) {\n if (draft.status === 404) throw new Error(`site ${hostId} vanished while its page was generated`)\n return { ...spent, review: aiLimitReview(draft.error) }\n }\n } else {\n // A draft written by an earlier, interrupted pass is replaced whole.\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const update = await updateAiDraftNodes(firestore, {\n kind: 'screen',\n hostId,\n id: draftId,\n now,\n update: () => pictured,\n })\n if (update.ok === false) return { ...spent, failure: AI_JOB_PAGE_DELETED_COPY }\n }\n return { ...spent, continue: true }\n }\n const maxTokens = aiJobPageSectionMaxTokens(model)\n const maxElements = aiJobPageSectionMaxElements(maxTokens)\n const result = await runValidatedGeneration<AiPageSection>('page-section', {\n step: 'job.page',\n model,\n instructions: AI_JOB_PAGE_INSTRUCTIONS,\n inventory,\n messages: [\n {\n role: 'user',\n content: aiPageSectionPrompt({ job, plan, screen, index, maxElements, reusableComponents, record, linkablePages }),\n },\n ],\n tool: AI_PAGE_SECTION_TOOL,\n maxTokens,\n // A section cut off at its ceiling is asked for smaller, and a member\n // whose section still does not fit reads that it was too large (AGL-3042).\n cutOff: { noun: 'section', smaller: aiPageSectionSmaller({ maxElements, reusableComponents }) },\n thinking: 'off',\n check: aiPageSectionCheck({\n page,\n sectionIds,\n index,\n context,\n section: screen.sections[index],\n inventory,\n linkTarget,\n }),\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(result)\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') return { ...spent, review: aiDoctrineReview(result, { page: true }) }\n // A record template's page leads with each record's own photo (AGL-3616).\n const section = aiPageSectionWithRecordImage(result.value, page, record)\n\n if (!written) {\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const draft = await writeAiDraft(firestore, {\n kind: 'screen',\n hostId,\n id: draftId,\n uid: job.createdBy,\n org,\n name,\n nodes: aiPageWithSection(aiEmptyPage(), section, sectionIds),\n slug,\n layoutId: aiPageDraftLayoutId(screen, inventory),\n aiJobId: aiOriginJobId(job),\n now,\n })\n if (draft.ok === false) {\n if (draft.status === 404) throw new Error(`site ${hostId} vanished while its page was generated`)\n return { ...spent, review: aiLimitReview(draft.error) }\n }\n } else {\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const update = await updateAiDraftNodes(firestore, {\n kind: 'screen',\n hostId,\n id: draftId,\n now,\n // A pass run again after its write finds its section and changes nothing.\n update: (nodes) =>\n section.rootId in nodes ? null : aiPageWithSection(nodes, section, sectionIds),\n })\n if (update.ok === false) return { ...spent, failure: AI_JOB_PAGE_DELETED_COPY }\n }\n return { ...spent, continue: true }\n }\n}\n\nexport const runAiJobPageStep = createAiJobPageStep()\n\n/**\n * Registers the page step with the least time a section pass needs and the\n * time its next pass needs, the passes a page with its creations may take, and\n * the check a page job passes when it is created or its plan is confirmed.\n */\nexport function registerAiPageJob(): void {\n registerAiJobStep('page', runAiJobPageStep, {\n minimumMs: AI_JOB_PAGE_STEP_MINIMUM_MS,\n minimumMsFor: aiPageJobRunMinimumMs,\n })\n registerAiJobStepPasses('page', AI_JOB_PAGE_MAX_PASSES)\n registerAiJobAdmission('page', aiPageJobAdmission)\n}\n"],"names":["throwIfAiJobCanceled","buildPageMarkdown","SCREEN_SEO_TEXT_GUIDANCE","SCREEN_ROOT_PATH","screenRoutePathToUrl","CANVAS_ROOT_ELEMENT_ID","duplicateResource","AI_BUILD_PLAN_LIMITS","aiPlanEmbedsFor","AI_PAGE_CREATE_KINDS","aiPageCreationRefusal","aiPagePlanRefusal","parseAiPageJobInputs","aiPlanCapabilitiesForJob","aiPlanUncreatable","aiSiteWords","aiModelForStep","aiDoctrineNeedsInputMessage","runValidatedGeneration","aiClipAtWord","aiSettleMechanicalRules","aiSettlePlaceholderItems","aiSettleUnrelatedScreenLinks","validateAiDoctrineTree","aiHasPlaceholderToken","AI_SEO_FIELDS_MAX_TOKENS","generateSeoFields","readSiteInventory","registerAiJobAdmission","aiGenerationWorstCaseMs","aiJobDraftId","aiOriginJobId","aiBuildsWithComponents","aiDraftAdmissionRefusal","aiDraftAllowanceRefusal","aiSiteSubdomain","readAiDraft","readAiDraftNodes","readAiPlanCapabilities","updateAiDraftNodes","writeAiDraft","writeAiDraftScreenSeo","aiBracketedFactsNote","aiConfirmedPlan","aiDoctrineReview","aiGenerationSpent","aiLimitReview","aiModelNodeIds","aiUnspentOutcome","AI_JOB_PAGE_SECTION_MAX_TOKENS","AI_JOB_PAGE_SECTION_TOKENS","AI_JOB_PAGE_STEP_BUDGET","AI_JOB_PAGE_STEP_MINIMUM_MS","aiJobPageSectionMaxTokens","AI_JOB_PAGE_INSTRUCTIONS","AI_PAGE_SECTION_TOOL","aiEmptyPage","aiPageCheckContext","aiPageLinkablePages","aiPageRecordNote","aiPageRecordTemplate","aiPageRecordTokens","aiPageSectionCheck","aiPageSectionNodeId","aiPageSectionPrompt","aiPageSectionSmaller","aiPageSectionWithRecordImage","aiPageWithSection","aiLayoutSitePages","aiResolveLayoutPictures","aiLayoutSitePhotoSource","AI_STOCK_PHOTO_AVOID_INPUT","AI_STOCK_PHOTO_PAGES_INPUT","aiStockPhotoWordsOf","aiStockPlacedSrcs","AI_PLAN_ITEMS_MIN","aiPlanCopiedPageViolations","AI_JOB_PAGE_LANGUAGE_BUDGET","aiJobUsesLayoutLanguage","aiLayoutListingContext","aiLayoutPageTargets","aiLayoutLeftOutNote","aiLayoutMotionSiteOf","aiRunLayoutPage","aiWithSiteMotion","aiCreationUnit","aiRunJobUnit","aiSiteBuiltRefs","aiSitePendingUnits","aiSiteUnitJob","aiJobStepRunMinimumMs","aiJobStepRunnerFor","registerAiJobStep","registerAiJobStepPasses","AI_JOB_PAGE_TOKENS_PER_ELEMENT","AI_JOB_PAGE_REAL_TOKENS_PER_ESTIMATED","Math","max","AI_JOB_PAGE_REAL_TOKENS_PER_ELEMENT","ceil","aiJobPageSectionMaxElements","maxTokens","floor","AI_JOB_PAGE_DEFAULT_NAME","AI_JOB_PAGE_NO_PLAN_COPY","AI_JOB_PAGE_DELETED_COPY","AI_JOB_PAGE_CREATION_UNAVAILABLE_COPY","AI_JOB_PAGE_CREATION_EMPTY_COPY","AI_JOB_PAGE_REFUSED_DRAFT_COPY","AI_JOB_PAGE_MAX_PASSES","create","sections","aiPageJobUnits","plan","flatMap","kind","creation","index","unit","aiPageJobRunMinimumMs","job","confirmed","pagePass","minimumMs","units","outputs","aiPageDraftSlug","screen","segments","slug","split","map","part","trim","filter","Boolean","length","aiSiteDefaultLayoutId","inventory","counts","layouts","Set","row","id","size","pages","screens","template","layoutId","has","home","find","Map","set","get","mostUsed","entries","sort","a","b","aiPageDraftLayoutId","layout","some","siteNameOf","host","text","value","aiCopiedPageReview","firestore","input","section","items","stored","hostId","nodes","reason","message","name","findings","violations","rootId","aiPageJobAdmission","context","inputs","status","error","refusal","jobKind","org","orgId","noun","ownCheck","capabilities","creates","aiPageStartPage","readNodes","duplicateOf","one","replaceable","undefined","catch","label","aiJobPagesPlacedPhotos","listed","ids","Array","isArray","draftId","elsewhere","shown","src","startsWith","read","Promise","all","createAiJobPageStep","deps","readInventory","duplicate","seoFields","runnerFor","stepContext","orgSnapshot","now","signal","modelFor","Error","model","failure","runner","pass","emptyCopy","built","outcome","continue","resource","slot","title","sectionIds","_","$id","output","draft","load","note","versionId","hostSubdomain","nav","proposal","navigation","written","collection","doc","data","deleted","record","recordNote","copiesStarter","generatedWhole","sourceReview","sourceShort","copy","sourceId","uid","createdBy","attemptKey","ok","review","page","findIndex","reusableComponents","embeds","linkablePages","linkTarget","language","checked","recordTokens","codeBuilt","repeatsCompiled","own","motion","settle","tree","settled","ownScreenIds","moved","update","next","report","scrollTargetIds","join","reported","entry","reports","storedIds","sourceIds","violation","nodeIds","answer","then","spent","seo","description","seoModel","values","seoTitle","seoDescription","lookups","result","subject","path","brand","site","fields","otherTitles","usable","allowance","targets","startsFrom","refused","sectionNames","seed","avoid","photoWords","pictured","source","stockPhotos","business","about","jobId","aiJobId","maxElements","step","instructions","messages","role","content","tool","cutOff","smaller","thinking","check","runAiJobPageStep","registerAiPageJob","minimumMsFor"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,qBAAiB;AACtD,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,wBAAwB,QAAQ,2CAA0C;AACnF,SAASC,gBAAgB,EAAEC,oBAAoB,QAAQ,sCAAqC;AAC5F,SAASC,sBAAsB,QAAQ,2CAA0C;AAEjF,SAASC,iBAAiB,QAAQ,qDAAoD;AACtF,SAASC,oBAAoB,EAAEC,eAAe,QAAgC,4BAAwB;AACtG,SACEC,oBAAoB,EACpBC,qBAAqB,EACrBC,iBAAiB,EACjBC,oBAAoB,QACf,0BAAsB;AAC7B,SAASC,wBAAwB,EAAEC,iBAAiB,QAAQ,mCAA+B;AAC3F,SAASC,WAAW,QAAQ,0BAAsB;AAElD,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SAASC,2BAA2B,EAAEC,sBAAsB,QAAQ,4BAAwB;AAC5F,SACEC,YAAY,EACZC,uBAAuB,EACvBC,wBAAwB,EACxBC,4BAA4B,EAC5BC,sBAAsB,QAEjB,uCAAmC;AAE1C,SAASC,qBAAqB,QAAQ,sCAAkC;AACxE,SAASC,wBAAwB,EAAEC,iBAAiB,QAAQ,2BAAuB;AACnF,SAASC,iBAAiB,QAAQ,+BAA2B;AAE7D,SAASC,sBAAsB,QA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ChB;IACA1B,wBAAwB,QAAQgB;IAChCjF,uBAAuB,QAAQyJ;AACjC"}
|
|
@@ -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
|
|
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
|
|
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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OE,SAAS;;IAC7D,2EAA2E;IAC3E,MAAMnG,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,E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