@aglyn/plugins-ai 1.0.0-beta.249 → 1.0.0-beta.250

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-ai",
3
- "version": "1.0.0-beta.249",
3
+ "version": "1.0.0-beta.250",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,22 +25,22 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.249",
29
- "@aglyn/shared-data-enums": "1.0.0-beta.249",
30
- "@aglyn/shared-data-mdi": "1.0.0-beta.249",
31
- "@aglyn/shared-data-types": "1.0.0-beta.249",
32
- "@aglyn/shared-ui-email-campaigns": "1.0.0-beta.249",
33
- "@aglyn/shared-ui-jsx": "1.0.0-beta.249",
34
- "@aglyn/shared-ui-snackstack": "1.0.0-beta.249",
35
- "@aglyn/shared-ui-theme": "1.0.0-beta.249",
36
- "@aglyn/shared-util-email": "1.0.0-beta.249",
37
- "@aglyn/shared-util-errors": "1.0.0-beta.249",
38
- "@aglyn/shared-util-http": "1.0.0-beta.249",
39
- "@aglyn/shared-util-timestamp": "1.0.0-beta.249",
40
- "@aglyn/shared-util-tools": "1.0.0-beta.249",
41
- "@aglyn/tenant-data-admin": "1.0.0-beta.249",
42
- "@aglyn/tenant-feature-instance": "1.0.0-beta.249",
43
- "@aglyn/tenant-runtime": "1.0.0-beta.249",
28
+ "@aglyn/aglyn": "1.0.0-beta.250",
29
+ "@aglyn/shared-data-enums": "1.0.0-beta.250",
30
+ "@aglyn/shared-data-mdi": "1.0.0-beta.250",
31
+ "@aglyn/shared-data-types": "1.0.0-beta.250",
32
+ "@aglyn/shared-ui-email-campaigns": "1.0.0-beta.250",
33
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.250",
34
+ "@aglyn/shared-ui-snackstack": "1.0.0-beta.250",
35
+ "@aglyn/shared-ui-theme": "1.0.0-beta.250",
36
+ "@aglyn/shared-util-email": "1.0.0-beta.250",
37
+ "@aglyn/shared-util-errors": "1.0.0-beta.250",
38
+ "@aglyn/shared-util-http": "1.0.0-beta.250",
39
+ "@aglyn/shared-util-timestamp": "1.0.0-beta.250",
40
+ "@aglyn/shared-util-tools": "1.0.0-beta.250",
41
+ "@aglyn/tenant-data-admin": "1.0.0-beta.250",
42
+ "@aglyn/tenant-feature-instance": "1.0.0-beta.250",
43
+ "@aglyn/tenant-runtime": "1.0.0-beta.250",
44
44
  "@swc/helpers": "0.5.23"
45
45
  },
46
46
  "peerDependencies": {
@@ -34,7 +34,7 @@ import { AI_JOB_PAGE_STEP_MINIMUM_MS } from "./ai-job-page-budget.js";
34
34
  import { aiPluginDraftAdmissionRefusal, aiPluginDraftWriter } from "./ai-job-plugin-drafts.js";
35
35
  import { aiSitePageWritten, aiSiteResolvedRef } from "./ai-job-site-step.js";
36
36
  import { AI_LAYOUT_SITE_PAGES_INPUT, aiLayoutSitePagesOfPlan } from "./ai-job-layout-site-pages.js";
37
- import { AI_LAYOUT_FORM_PAGE_INPUT, AI_LAYOUT_LANGUAGE_INPUT, aiLayoutFormPageOfPlan } from "./ai-job-page-language.js";
37
+ import { AI_LAYOUT_FORM_PAGE_INPUT, AI_LAYOUT_LANGUAGE_INPUT, aiJobUsesLayoutLanguage, aiLayoutFormPageOfPlan } from "./ai-job-page-language.js";
38
38
  import { aiDatasetListingsOf } from "./ai-job-site-datasets.js";
39
39
  import { AI_SITE_EVENT_OP, aiEventsListings } from "./ai-job-site-events.js";
40
40
  import { AI_FORM_DATASET_MADE_INPUT } from "./ai-job-form-dataset.js";
@@ -911,7 +911,8 @@ export function createAiJobBuildStep(deps = {}) {
911
911
  hostId: job.hostId,
912
912
  unitJobId: derived.$id,
913
913
  screen: unit.screen,
914
- draftId: page.id
914
+ draftId: page.id,
915
+ layoutLanguage: aiJobUsesLayoutLanguage(derived)
915
916
  }, readNodes);
916
917
  if (!written) {
917
918
  return settle(failed(unit.slot, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-build-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 { aiJobCancelAsked } from './ai-job-cancel'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport type { PluginAiCapability } from '@aglyn/aglyn/plugin-manager/plugin-ai-capabilities'\nimport { resolveEffectivePlan } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { resolveOrgIdForHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport {\n AI_BUILD_LIMITS,\n AI_BUILD_MADE_INPUT,\n AI_BUILD_PUBLISH_INPUT,\n aiArticle,\n aiBuildCreditRange,\n aiBuildDegradation,\n aiBuildInitialLedger,\n aiBuildItemDelivered,\n aiBuildItemOpen,\n aiBuildNextUnit,\n aiBuildOrder,\n aiBuildItemOutputNote,\n aiBuildPlacedItemLines,\n aiBuildPlanMissingInput,\n aiBuildPlanShapeRefusal,\n aiBuildSmaller,\n aiBuildUnits,\n type AiBuildMade,\n type AiBuildOps,\n type AiBuildUnit,\n} from '../model/ai-build-job'\nimport { isAiPlanNewRef, type AiBuildPlanCreateKind } from '../model/ai-build-plan'\nimport type {\n AiJob,\n AiJobItemFailure,\n AiJobItemLedger,\n AiJobKind,\n AiJobOutput,\n AiJobPlan,\n} from '../model/ai-jobs.types'\nimport { AI_SITE_MAX_SECTIONS } from '../model/ai-site-job'\nimport {\n AI_CREDITS_CONFIRM_CODE,\n aiCreditsPromptFor,\n aiCreditsPromptText,\n type AiCreditRange,\n type AiCreditsPrompt,\n type AiCreditsSmaller,\n} from '../model/ai-credit-estimate'\nimport { aiFreeCreditsNoneLeftText, aiSiteWords } from '../model/ai-site-job'\nimport { readFreeAiCreditsLeft } from '../usage/free-ai-credits-left'\nimport { aiModelForStep } from '../providers/routing'\nimport {\n AI_BUILD_UNIT_EMPTY_COPY,\n aiBuildBuiltRefs,\n aiUnitErrorRetryable,\n aiUnitFailure,\n aiUnitSpend,\n} from './ai-build-unit-outcome'\nimport { aiBuildOps, type AiBuildOpsContext } from './ai-build-capabilities'\nimport {\n aiJobAdmissionRefusal,\n registerAiJobAdmission,\n type AiJobAdmission,\n type AiJobAdmissionContext,\n type AiJobAdmissionRefusal,\n} from './ai-job-admission'\nimport { aiOriginJobId } from './ai-job-draft-ids'\nimport { readAiDraftNodes } from './ai-job-drafts'\nimport { aiConfirmedPlan, aiUnspentOutcome } from './ai-job-generation'\nimport { AI_JOB_PAGE_STEP_MINIMUM_MS } from './ai-job-page-budget'\nimport {\n aiPluginDraftAdmissionRefusal,\n aiPluginDraftWriter,\n type AiPluginDraftWriterLookup,\n} from './ai-job-plugin-drafts'\nimport { aiSitePageWritten, aiSiteResolvedRef } from './ai-job-site-step'\nimport { AI_LAYOUT_SITE_PAGES_INPUT, aiLayoutSitePagesOfPlan } from './ai-job-layout-site-pages'\nimport { AI_LAYOUT_FORM_PAGE_INPUT, AI_LAYOUT_LANGUAGE_INPUT, aiLayoutFormPageOfPlan } from './ai-job-page-language'\nimport { aiDatasetListingsOf } from './ai-job-site-datasets'\nimport { AI_SITE_EVENT_OP, aiEventsListings } from './ai-job-site-events'\nimport { AI_FORM_DATASET_MADE_INPUT } from './ai-job-form-dataset'\nimport { AI_LAYOUT_LISTINGS_INPUT } from '../layout-language/ai-layout-listings'\nimport {\n AI_BUILD_STORE_OP,\n AI_BUILD_STORE_PAGES_PRESENT_NOTE,\n aiBuildStoreLayoutLinks,\n aiBuildStoreLayoutOf,\n aiBuildStorePagesOf,\n aiBuildStorePagesStillMissing,\n type AiBuildStoreLinksState,\n type AiStoreSitePage,\n} from '../model/ai-build-store-pages'\nimport type { AiStoreLayoutLinks } from '../model/ai-layout-store-links'\nimport { writeAiStoreLinksLayoutDraft } from './ai-job-store-links-layout'\nimport type { AiSitePublishStoreLinks } from './ai-site-publish'\nimport {\n AI_SITE_STORE_LINKS_INPUT,\n AI_SITE_STORE_PAGES_NOTE,\n aiStoreFrameLinks,\n aiStorePagesToWrite,\n} from '../model/ai-site-store-pages'\nimport {\n AI_SITE_STORE_PAGES_INPUT,\n aiSiteStorePageId,\n aiSiteStorePagesRefusal,\n runAiSiteStorePagesUnit,\n type AiSiteStorePagesInput,\n} from './ai-job-site-store-pages'\nimport {\n AI_JOB_BRIEF_MAX_CHARS,\n type AiJobItemOutcome,\n type AiJobStepOutcome,\n type AiJobStepRunner,\n} from './ai-job-text-step'\nimport { aiJobPublishesBuild, aiMergeSitePublish, aiPublishGuidedSite } from './ai-site-publish'\nimport {\n AI_PLANNED_JOB_KINDS,\n aiJobStepRunMinimumMs,\n aiJobStepRunnerFor,\n registerAiJobStep,\n registerAiJobStepPasses,\n} from './ai-jobs'\n\n/**\n * The build step (AGL-3616): the generation step of a `build` job, run once\n * the member confirmed the plan their request produced.\n *\n * Like the site scaffold it generalizes, it builds nothing itself and asks no\n * model of its own. Each pass takes the next unit in dependency order and\n * hands it to what builds that kind of thing — a page, layout, form,\n * component, email design or template to this plugin's own step, under a job\n * derived for the unit; another plugin's resource to that plugin's writer on\n * the resource-draft seam, with the content the owner's capability derives\n * from the item's arguments. One unit, one pass, one recorded spend.\n *\n * ── Settled item by item ────────────────────────────────────────────────\n *\n * Where a unit stands is read from the job's ITEM LEDGER, never from counting\n * outputs: the machine writes each pass's row in the transaction that\n * records its spend (`recordStep`). A unit that fails is a FAILED ROW, not a\n * failed job: the pass reports it, the machine gives back that item's spend\n * where the failure was ours, and the next pass builds the next unit. What\n * depended on it is built without it, or skipped where it cannot stand\n * without it (`aiBuildDegradation`). The machine ends the job when nothing is\n * left: `done` when anything was delivered, `failed` — its planning given\n * back too — when nothing was.\n *\n * ── Drafts, unless asked and confirmed ───────────────────────────────────\n *\n * Every unit writes the draft its own kind writes, which nothing publishes.\n * Only a build whose request asked to publish AND whose member ticked the\n * plan card's box puts its built pages live, once, on its last pass, through\n * the guided start's publish.\n */\n\n/** What a build answers with no confirmed plan to build. */\nexport const AI_BUILD_NO_PLAN_COPY = 'This build has no confirmed plan to build.'\n\n/** What a unit says when nothing on this site builds its operation any more. */\nexport const aiBuildUnavailableCopy = (noun: string): string =>\n `Not built: ${aiArticle(noun)} cannot be made on this site right now.`\n\n\n/** What a page that was reported built but holds none of its plan says. */\nexport const AI_BUILD_PAGE_NOT_WRITTEN_COPY = 'The page was not written from its plan.'\n\n\n/**\n * The most passes a build's step may take: every unit at a page's worst — its\n * sections and its listing — so a runner that never finishes is still\n * bounded while the largest plan is not. Try again starts the count over.\n */\nexport const AI_BUILD_MAX_PASSES = AI_BUILD_LIMITS.units * (AI_SITE_MAX_SECTIONS + 1) + 1\n\n/** The job kind a creation of the build is built by. */\nconst CREATION_JOB_KINDS: Partial<Record<AiBuildPlanCreateKind, AiJobKind>> = {\n layout: 'layout',\n form: 'form',\n component: 'component',\n email: 'email',\n}\n\n/** The job kind a unit is built by, where an AI runner builds it. */\nexport function aiBuildUnitJobKind(unit: AiBuildUnit, ops: AiBuildOps): AiJobKind | null {\n if (unit.screen) return 'page'\n if (unit.creation) return CREATION_JOB_KINDS[unit.creation.kind] ?? null\n const runnerKind = ops.get(unit.op)?.runnerKind\n return runnerKind ? (runnerKind as AiJobKind) : null\n}\n\n/** What the job drawer says under an item another plugin's writer made (`model/ai-build-job.ts`). */\nexport { aiBuildItemOutputNote }\n\n/** The id a unit's job, and so its draft, is named by. */\nexport function aiBuildUnitJobId(job: Pick<AiJob, '$id'>, unit: AiBuildUnit): string {\n return unit.creation?.id ?? unit.screen?.id ?? unit.item?.id ?? `${job.$id}-${unit.slot}`\n}\n\n/**\n * The job a unit is built under (generalizing `aiSiteUnitJob`): this job's\n * org, site, creator and model; the kind that builds the unit; a plan\n * narrowed to the unit, its `new:` references resolved to what was built and\n * the failed ones left out; and a brief that says what the unit is, what it\n * is built without, and which blocks its sections place.\n */\nexport function aiBuildUnitJob(\n job: AiJob,\n unit: AiBuildUnit,\n context: {\n kind: AiJobKind\n units: readonly AiBuildUnit[]\n ledger: readonly AiJobItemLedger[]\n ops: AiBuildOps\n briefLines?: readonly string[]\n },\n): AiJob {\n const plan = job.plan as AiJobPlan\n const built = aiBuildBuiltRefs(context.units, context.ledger, job.outputs ?? [])\n const labels = { ...(plan.labels ?? {}) }\n for (const entry of built.values()) labels[entry.id] = entry.label\n const brief = [job.brief.trim()]\n const unitPlan: AiJobPlan = { ...plan, labels, reuse: [...plan.reuse], create: [], screens: [] }\n delete unitPlan.items\n const placedByScreens = new Set(plan.screens.flatMap((screen) => screen.sections.flatMap((section) => section.uses)))\n if (unit.creation) {\n unitPlan.reuse = plan.reuse.filter((entry) => !placedByScreens.has(entry.id))\n unitPlan.create = [\n {\n ...unit.creation,\n duplicateOf: aiSiteResolvedRef(unit.creation.duplicateOf, built),\n // The dataset a form writes to, new or the site's own (AGL-3616); one\n // this build failed to make leaves the form as it always was.\n ...(unit.creation.writesTo ? { writesTo: aiSiteResolvedRef(unit.creation.writesTo, built) } : {}),\n },\n ]\n brief.push(`Build the ${unit.creation.kind} “${unit.creation.name}”: ${unit.creation.why}`)\n }\n if (unit.screen) {\n const screen = unit.screen\n for (const entry of built.values()) {\n unitPlan.reuse.push({ kind: entry.kind, id: entry.id, purpose: `the ${entry.kind} this request built` })\n }\n let builtLayout: string | null = null\n for (const entry of built.values()) if (entry.kind === 'layout') builtLayout = builtLayout ?? entry.id\n unitPlan.screens = [\n {\n ...screen,\n // A page whose layout failed renders inside the site's own: the page\n // step falls back to it when the plan names none.\n layout: aiSiteResolvedRef(screen.layout, built) ?? (isAiPlanNewRef(screen.layout) ? builtLayout : null),\n template: aiSiteResolvedRef(screen.template, built),\n duplicateOf: aiSiteResolvedRef(screen.duplicateOf, built),\n record: screen.record\n ? { ...screen.record, dataset: aiSiteResolvedRef(screen.record.dataset, built) ?? screen.record.dataset }\n : null,\n sections: screen.sections.map((section) => ({\n ...section,\n uses: section.uses\n .map((ref) => aiSiteResolvedRef(ref, built))\n .filter((ref): ref is string => !!ref),\n })),\n },\n ]\n brief.push(`Build the page “${screen.title}”, at ${screen.slug}.`)\n // A build's events are listed by the platform (AGL-3755), never written by the page.\n brief.push(\n ...aiBuildPlacedItemLines(unit, { units: context.units, ledger: context.ledger, ops: context.ops, placedByCode: [AI_SITE_EVENT_OP] }),\n )\n }\n const item = unit.item\n if (item) {\n const noun = context.ops.get(item.op)?.noun ?? item.op\n brief.push(`Build the ${noun} “${item.name}”${item.why ? `: ${item.why}` : '.'}`)\n // A planned kind's step builds the plan's first creation of its kind.\n unitPlan.create = AI_PLANNED_JOB_KINDS.includes(context.kind)\n ? [{ kind: context.kind as AiBuildPlanCreateKind, name: item.name, why: item.why, duplicateOf: null, fields: [], ...(item.id ? { id: item.id } : {}) }]\n : []\n }\n brief.push(...(context.briefLines ?? []))\n const inputs: Record<string, unknown> = {\n ...job.inputs,\n ...(item?.args ?? {}),\n originJobId: aiOriginJobId(job),\n }\n delete inputs[AI_BUILD_PUBLISH_INPUT]\n // An item is told the pages and layouts this build made before it, which\n // its arguments may link as `new:<name>` (a menu item, AGL-3728).\n if (item) {\n const rows = new Map(context.ledger.map((row) => [row.slot, row]))\n const made: AiBuildMade = {\n pages: context.units.flatMap((one) => {\n const row = rows.get(one.slot)\n return one.screen?.id && row && aiBuildItemDelivered(row) ? [{ title: one.screen.title, id: one.screen.id }] : []\n }),\n layouts: [...built.entries()].filter(([, entry]) => entry.kind === 'layout').map(([name, entry]) => ({ name, id: entry.id })),\n }\n if (made.pages.length || made.layouts.length) inputs[AI_BUILD_MADE_INPUT] = made\n }\n // A dataset this build made for its form, which the form may bind (AGL-3616).\n const madeFor = unit.creation?.kind === 'form' && isAiPlanNewRef(unit.creation.writesTo) ? unitPlan.create[0]?.writesTo : null\n if (madeFor) inputs[AI_FORM_DATASET_MADE_INPUT] = madeFor\n // A build's pages and layouts are designed in the layout language and\n // compiled (AGL-3660), told the pages the build plans and where its form is.\n if (context.kind === 'page' || context.kind === 'layout') {\n inputs[AI_LAYOUT_LANGUAGE_INPUT] = true\n const pages = aiLayoutSitePagesOfPlan(plan.screens)\n if (pages.length) inputs[AI_LAYOUT_SITE_PAGES_INPUT] = pages\n const formPage = aiLayoutFormPageOfPlan(plan)\n if (formPage) inputs[AI_LAYOUT_FORM_PAGE_INPUT] = formPage\n // The datasets this build made, repeated in the sections that name them (AGL-3616),\n // and the site's own the plan reuses (AGL-3747): the page reads their fields,\n // and the record pages the site already serves for them, off its inventory.\n const datasets = [...built.entries()]\n .filter(([, entry]) => entry.kind === 'dataset')\n .map(([name, entry]) => ({ id: entry.id, name: context.units.find((one) => one.item?.name.toLowerCase() === name)?.label ?? entry.label }))\n for (const entry of plan.reuse) {\n if (entry.kind !== 'dataset' || datasets.some((one) => one.id === entry.id)) continue\n datasets.push({ id: entry.id, name: plan.labels?.[entry.id] ?? entry.id })\n }\n const listings = aiDatasetListingsOf(datasets, plan.screens)\n // The events this build wrote, in the sections that name them (AGL-3755).\n const eventUnits = context.units.filter((one) => one.item?.op === AI_SITE_EVENT_OP)\n const ledgerRows = new Map(context.ledger.map((row) => [row.slot, row]))\n listings.push(\n ...aiEventsListings({\n written: eventUnits\n .filter((one) => {\n const row = ledgerRows.get(one.slot)\n return Boolean(row && aiBuildItemDelivered(row) && row.outputs.length)\n })\n .map((one) => one.item?.name ?? one.label),\n planned: eventUnits.map((one) => one.item?.name ?? one.label),\n screens: plan.screens,\n }),\n )\n if (listings.length) inputs[AI_LAYOUT_LISTINGS_INPUT] = listings\n }\n // A build that makes the site a store links its account and policies from\n // the layout it makes (AGL-3676), by path: they are written after it.\n const storePages = aiBuildStorePagesOf(plan)\n if (context.kind === 'layout' && storePages) inputs[AI_SITE_STORE_LINKS_INPUT] = aiStoreFrameLinks(storePages.pages)\n return {\n ...job,\n $id: aiBuildUnitJobId(job, unit),\n kind: context.kind,\n steps: [],\n outputs: [],\n items: null,\n plan: item && !AI_PLANNED_JOB_KINDS.includes(context.kind) ? null : unitPlan,\n inputs,\n brief: brief.join('\\n').slice(0, AI_JOB_BRIEF_MAX_CHARS),\n }\n}\n\n/** The unit's failure, for its row: ours or not, why, in customer-safe words. */\nfunction failed(\n slot: string,\n failure: AiJobItemFailure,\n extra: Partial<AiJobItemOutcome> = {},\n): AiJobItemOutcome {\n return { slot, status: 'failed', failure, ...extra }\n}\n\nexport interface AiJobBuildStepDeps {\n /** The runner registry; specs hand in fakes. */\n runnerFor?: typeof aiJobStepRunnerFor\n /** The draft writer registry; specs hand in fakes. */\n writerFor?: AiPluginDraftWriterLookup\n /** The operations this site may use; the registry and its gates otherwise. */\n opsFor?: (context: AiBuildOpsContext) => Promise<AiBuildOps>\n /** A runner kind's own admission, asked before its item runs; the registry's otherwise. */\n admissionFor?: typeof aiJobAdmissionRefusal\n /** Another plugin's admission for its writer; the seam's otherwise. */\n pluginAdmission?: typeof aiPluginDraftAdmissionRefusal\n /** The draft reader a built page is checked through. */\n readNodes?: typeof readAiDraftNodes\n /** The publish a build asked for and confirmed. */\n publish?: typeof aiPublishGuidedSite\n /** A store's own pages' pass and whether they may be added here (AGL-3676); specs hand in fakes. */\n storePages?: AiJobStepRunner\n storePagesRefusal?: typeof aiSiteStorePagesRefusal\n /** The site's pages as they are now, which a store's own pages are checked against before they are written. */\n readSitePages?: typeof readAiStoreSitePages\n /** The draft version of the site's layout a store's links are written into. */\n writeStoreLinks?: typeof writeAiStoreLinksLayoutDraft\n}\n\n/** The site's pages as a store's own pages are checked against them (AGL-3676): every page that is not deleted. */\nexport async function readAiStoreSitePages(firestore: FirebaseFirestore.Firestore, hostId: string): Promise<AiStoreSitePage[]> {\n const snapshot = await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('screens')\n .select('displayName', 'slug', 'kind', 'deletedAt', 'layoutId')\n .get()\n return snapshot.docs.flatMap((doc) => {\n const kind = doc.get('kind')\n if (doc.get('deletedAt') || (kind && kind !== 'template')) return []\n const slug = String(doc.get('slug') ?? '')\n const layoutId = doc.get('layoutId')\n return slug\n ? [{ id: doc.id, slug, title: String(doc.get('displayName') ?? ''), template: kind === 'template', layoutId: typeof layoutId === 'string' && layoutId ? layoutId : null }]\n : []\n })\n}\n\n/**\n * What a build's store pages unit is told (AGL-3676): the pages its plan kept,\n * less any the site has gained since — never counting the pages this unit\n * wrote itself on an earlier pass, which it finds again by their ids — what\n * their words link, and the layout they render inside: the plan's Shop\n * page's, else the site's own (`aiBuildStoreLayoutOf`).\n */\nexport function aiBuildStorePagesInput(\n job: AiJob,\n context: { unitJobId: string; sitePages: readonly AiStoreSitePage[]; units: readonly AiBuildUnit[]; ledger: readonly AiJobItemLedger[] },\n): AiSiteStorePagesInput | null {\n const plan = job.plan as AiJobPlan\n const kept = aiBuildStorePagesOf(plan)\n if (!kept) return null\n const own = new Set(kept.pages.map((page) => aiSiteStorePageId(context.unitJobId, page.key)))\n const pages = aiBuildStorePagesStillMissing(\n kept.pages,\n context.sitePages.filter((page) => !page.id || !own.has(page.id)),\n )\n const built = aiBuildBuiltRefs(context.units, context.ledger, job.outputs ?? [])\n const shop = plan.screens.find((screen) => !screen.record && screen.slug.replace(/^\\/+/, '').split('/')[0].toLowerCase() === kept.facts.shopPath.slice(1))\n const layout = shop ? aiSiteResolvedRef(shop.layout, built) : null\n return {\n pages,\n facts: kept.facts,\n layoutId: aiBuildStoreLayoutOf(layout && !isAiPlanNewRef(layout) ? layout : null, context.sitePages),\n }\n}\n\n/**\n * Adds a store's links to the site's own layout (AGL-3676), as a draft\n * version, where the build made no layout of its own for its store pages: the\n * outputs that record it — the layout version written (`storeLinks: draft`),\n * and on the first page `storeLinks: missing` where the layout had no header\n * or footer list to add them to, or there is no layout at all.\n */\nexport async function aiBuildStoreLinksOutputs(\n firestore: FirebaseFirestore.Firestore,\n input: {\n job: AiJob\n unitJobId: string\n store: AiSiteStorePagesInput\n outputs: readonly AiJobOutput[]\n sitePages: readonly AiStoreSitePage[]\n builtLayouts: ReadonlySet<string>\n now: Date\n },\n write: typeof writeAiStoreLinksLayoutDraft = writeAiStoreLinksLayoutDraft,\n): Promise<AiJobOutput[]> {\n const outputs = input.outputs.map((output) => ({ ...output }))\n const layoutId = input.store.layoutId\n // A layout this build made was told the store's links as it was compiled.\n if (layoutId && input.builtLayouts.has(layoutId)) return outputs\n const written = new Set(outputs.map((output) => output.proposal?.['storePage']).filter((key): key is string => typeof key === 'string'))\n const links = aiBuildStoreLayoutLinks(input.store.pages, written)\n const missing = (): AiJobOutput[] => {\n const [first, ...rest] = outputs\n const state: AiBuildStoreLinksState = 'missing'\n return first ? [{ ...first, proposal: { ...(first.proposal ?? {}), storeLinks: state } }, ...rest] : outputs\n }\n if (!layoutId || !input.job.hostId) return missing()\n const hrefs = new Set([...links.header, ...(links.cart ? [links.cart] : []), ...links.footer].map((link) => link.href.slice(1)))\n const screenPaths: Record<string, string> = {}\n for (const page of input.sitePages) {\n const slug = page.slug.replace(/^\\/+/, '').split('/')[0].toLowerCase()\n if (page.id && hrefs.has(slug)) screenPaths[page.id] = slug\n }\n const draft = await write(firestore, {\n hostId: input.job.hostId,\n layoutId,\n versionId: `${input.unitJobId}-links`.slice(0, 64),\n links,\n screenPaths,\n uid: input.job.createdBy,\n aiJobId: aiOriginJobId(input.job),\n now: input.now,\n })\n if (draft.status === 'present') return outputs\n if (draft.status === 'gone') return missing()\n const versionId = draft.versionId\n const layout: AiJobOutput[] = versionId\n ? [\n {\n resource: 'layout',\n id: draft.layoutId,\n versionId,\n hostId: input.job.hostId,\n hostSubdomain: outputs.find((output) => output.hostSubdomain)?.hostSubdomain,\n label: draft.name,\n note: 'A new draft version with Account and policy links. Visitors see it once it is published.',\n proposal: { storeLinks: 'draft' satisfies AiBuildStoreLinksState, links, screenPaths },\n },\n ]\n : []\n return [...(draft.status === 'unrecognized' ? missing() : outputs), ...layout]\n}\n\n/** The store's links a build drafted into the site's layout (AGL-3676), as its publish puts them live; `null` where it drafted none. */\nexport function aiBuildStoreLinksToPublish(outputs: readonly AiJobOutput[]): AiSitePublishStoreLinks | null {\n // The newest: a retried store drafts its links again after the first attempt's (AGL-3739).\n const draft = [...outputs]\n .reverse()\n .find((output) => output.resource === 'layout' && output.proposal?.['storeLinks'] === 'draft' && output.versionId)\n if (!draft?.versionId) return null\n return {\n layoutId: draft.id,\n versionId: draft.versionId,\n links: draft.proposal?.['links'] as AiStoreLayoutLinks,\n screenPaths: (draft.proposal?.['screenPaths'] ?? {}) as Record<string, string>,\n }\n}\n\n/** Whether a build's workspace spends the Free taste. */\nexport function aiBuildFreeTaste(org: object | null | undefined): boolean {\n return Boolean(org) && resolveEffectivePlan(org as never) === 'free'\n}\n\n/** The site document a gate reads, or `null`. */\nasync function readHost(firestore: FirebaseFirestore.Firestore, hostId: string | null) {\n if (!hostId) return null\n return ((await firestore.collection('hosts').doc(hostId).get()).data() ?? null) as Record<string, unknown> | null\n}\n\nexport function createAiJobBuildStep(deps: AiJobBuildStepDeps = {}): AiJobStepRunner {\n const runnerFor = deps.runnerFor ?? aiJobStepRunnerFor\n const writerFor = deps.writerFor ?? aiPluginDraftWriter\n const opsFor = deps.opsFor ?? ((context) => aiBuildOps(context))\n const admissionFor = deps.admissionFor ?? aiJobAdmissionRefusal\n const pluginAdmission = deps.pluginAdmission ?? aiPluginDraftAdmissionRefusal\n const readNodes = deps.readNodes ?? readAiDraftNodes\n const publish = deps.publish ?? aiPublishGuidedSite\n const storePagesRunner = deps.storePages ?? runAiSiteStorePagesUnit\n const storePagesRefusal = deps.storePagesRefusal ?? aiSiteStorePagesRefusal\n const readSitePages = deps.readSitePages ?? readAiStoreSitePages\n const writeStoreLinks = deps.writeStoreLinks ?? writeAiStoreLinksLayoutDraft\n\n return async (context): Promise<AiJobStepOutcome> => {\n const { job, firestore } = context\n const model = context.modelFor?.('job.plan') ?? aiModelForStep('job.plan')\n const plan = aiConfirmedPlan(job)\n if (!plan) return { ...aiUnspentOutcome(model), failure: AI_BUILD_NO_PLAN_COPY }\n const org = (context.org ?? null) as Partial<AglynOrgBilling> | null\n const units = aiBuildUnits(plan)\n const ordered = aiBuildOrder(units) ?? units\n const starting = !job.items?.length\n const ledger = starting ? aiBuildInitialLedger(units) : (job.items as AiJobItemLedger[])\n const init = starting ? { items: ledger } : {}\n const unit = aiBuildNextUnit(ordered, ledger)\n const rows = new Map(ledger.map((row) => [row.slot, row]))\n const host = await readHost(firestore, job.hostId ?? null)\n const ops = await opsFor({\n orgId: job.orgId,\n hostId: job.hostId ?? null,\n org,\n host,\n freeTaste: aiBuildFreeTaste(org),\n })\n\n /** Whether units other than this one are still to build. */\n const othersOpen = (slot: string) =>\n ordered.some((one) => one.slot !== slot && aiBuildItemOpen(rows.get(one.slot) ?? { status: 'pending' }))\n\n /**\n * The build's last pass puts its pages live, where it was asked and\n * confirmed. Once it has, Try again's last pass puts only the pages the\n * retry built live (AGL-3739, AGL-3730's fix for a site start),\n * merged into the record of the first.\n */\n const finish = async (\n outcome: AiJobStepOutcome,\n extraPages: readonly AiJobOutput[] = [],\n extraOutputs: readonly AiJobOutput[] = [],\n ): Promise<AiJobStepOutcome> => {\n if (!aiJobPublishesBuild(job) || !job.hostId) return outcome\n const previous = job.sitePublish ?? null\n const retry = Boolean(previous?.published.length)\n const already = new Set((previous?.published ?? []).map((page) => page.id))\n // A record template renders once per record only once its binding is\n // saved, so it is never published at its own address (AGL-3616).\n // A store's own pages (AGL-3676) go live with the pages the build planned.\n const pageIds = new Set(\n units\n .filter(\n (one) =>\n ((one.screen && !one.screen.record) || one.op === AI_BUILD_STORE_OP) &&\n aiBuildItemDelivered(rows.get(one.slot) ?? { status: 'pending' }),\n )\n .flatMap((one) => rows.get(one.slot)?.outputs ?? []),\n )\n const built = [\n ...(job.outputs ?? []).filter((output) => output.resource === 'screen' && pageIds.has(output.id)),\n ...extraPages,\n ]\n const pages = built.filter((page) => !already.has(page.id))\n if (!pages.length) return outcome\n // A canceled build never puts anything live (AGL-3616): its pages stay drafts.\n if (await aiJobCancelAsked(firestore, job, context.signal)) return outcome\n // The store pages a layout this build made links and that were not written come out of it.\n const storePages = aiBuildStorePagesOf(plan)\n const live = new Set(built.map((page) => page.proposal?.['storePage']).filter(Boolean))\n const unwrittenHrefs = storePages\n ? aiStorePagesToWrite(storePages.pages).filter((page) => !live.has(page.key)).map((page) => page.href)\n : []\n // A retry puts the store's links live only with store pages it built:\n // the first publish's links draft is live already, and a person may have edited it since.\n const storeLinks =\n !retry || pages.some((page) => page.proposal?.['storePage'])\n ? aiBuildStoreLinksToPublish([...(job.outputs ?? []), ...extraOutputs])\n : null\n const sitePublish = await publish(firestore, {\n job,\n outputs: pages,\n now: context.now,\n ...(unwrittenHrefs.length ? { unwrittenHrefs } : {}),\n ...(storeLinks ? { storeLinks } : {}),\n ...(retry ? { retry: true } : {}),\n }).catch((error: unknown) => {\n console.error('ai build publish threw', { orgId: job.orgId, jobId: job.$id, error })\n return null\n })\n if (!sitePublish) return outcome\n return { ...outcome, sitePublish: previous ? aiMergeSitePublish(previous, sitePublish) : sitePublish }\n }\n\n if (!unit) return finish({ ...aiUnspentOutcome(model), ...init })\n\n const settle = (item: AiJobItemOutcome, spent: AiJobStepOutcome = aiUnspentOutcome(model)): AiJobStepOutcome => ({\n ...spent,\n ...init,\n item,\n ...(item.status === 'running' || othersOpen(unit.slot) ? { continue: true } : {}),\n })\n\n // What its dependencies came to.\n const degradation = aiBuildDegradation(unit, { units, ledger, ops })\n if (degradation.skip) {\n return settle({ slot: unit.slot, status: 'skipped', note: degradation.skip, degradedBy: degradation.degradedBy })\n }\n // A store's own pages (AGL-3676): written by code, behind the site start's gate.\n if (unit.op === AI_BUILD_STORE_OP) {\n if (!job.hostId) return settle({ slot: unit.slot, status: 'skipped', note: 'Not built: open the site first.' })\n if (rows.get(unit.slot)?.status !== 'running') {\n const refusal = await storePagesRefusal({ ...context, job }).catch((error: unknown) => {\n console.error('ai build store pages admission failed', { orgId: job.orgId, jobId: job.$id, error })\n return AI_BUILD_UNIT_EMPTY_COPY\n })\n if (refusal) return settle({ slot: unit.slot, status: 'skipped', note: `Not built: ${refusal}` })\n }\n const unitJobId = aiBuildUnitJobId(job, unit)\n const sitePages = await readSitePages(firestore, job.hostId)\n const input = aiBuildStorePagesInput(job, { unitJobId, sitePages, units, ledger })\n if (!input) return settle({ slot: unit.slot, status: 'skipped', note: aiBuildUnavailableCopy('store page') })\n if (!aiStorePagesToWrite(input.pages).length) {\n return settle({ slot: unit.slot, status: 'skipped', note: AI_BUILD_STORE_PAGES_PRESENT_NOTE })\n }\n const derived: AiJob = {\n ...job,\n $id: unitJobId,\n kind: 'text',\n steps: [],\n outputs: [],\n items: null,\n plan: null,\n inputs: { ...job.inputs, originJobId: aiOriginJobId(job), [AI_SITE_STORE_PAGES_INPUT]: input },\n }\n let outcome: AiJobStepOutcome\n try {\n outcome = await storePagesRunner({ ...context, job: derived })\n } catch (error) {\n if (aiUnitErrorRetryable(error)) throw error\n console.error('ai build store pages threw', { orgId: job.orgId, jobId: job.$id, error })\n return settle(failed(unit.slot, { ours: true, reason: 'step-failure', message: AI_BUILD_UNIT_EMPTY_COPY }))\n }\n const stopped = aiUnitFailure(unit.slot, outcome)\n if (stopped) return settle(stopped, aiUnitSpend(outcome))\n // The site's own header and footer link them (AGL-3676), in a draft\n // version of its layout; a layout this build made already does.\n const builtLayouts = new Set(\n [...aiBuildBuiltRefs(units, ledger, job.outputs ?? []).values()].filter((entry) => entry.kind === 'layout').map((entry) => entry.id),\n )\n const outputs = await aiBuildStoreLinksOutputs(\n firestore,\n { job, unitJobId, store: input, outputs: outcome.outputs, sitePages, builtLayouts, now: context.now },\n writeStoreLinks,\n ).catch((error: unknown) => {\n console.error('ai build store links not written', { orgId: job.orgId, jobId: job.$id, error })\n return outcome.outputs\n })\n const ids = outputs.map((output) => output.id)\n const done = settle({ slot: unit.slot, status: 'succeeded', outputs: ids, note: AI_SITE_STORE_PAGES_NOTE }, { ...aiUnitSpend(outcome), outputs })\n if (done.continue) return done\n rows.set(unit.slot, { ...(rows.get(unit.slot) as AiJobItemLedger), status: 'succeeded', outputs: ids })\n return finish(\n done,\n outputs.filter((output) => output.resource === 'screen'),\n outputs,\n )\n }\n\n const capability = ops.get(unit.op)\n const noun = capability?.noun ?? unit.op\n if (!capability) return settle({ slot: unit.slot, status: 'skipped', note: aiBuildUnavailableCopy(noun) })\n const degraded = degradation.degradedBy.length > 0\n const note = degradation.notes.length ? degradation.notes.join(' ') : null\n\n // Another plugin's resource: its writer, with the content its capability derives.\n if (capability.draftResource) {\n const item = unit.item\n const writer = writerFor(capability.draftResource)\n if (!item || !writer || !job.hostId) {\n return settle({ slot: unit.slot, status: 'skipped', note: aiBuildUnavailableCopy(noun) })\n }\n const admission: AiJobAdmissionContext = {\n firestore,\n orgId: job.orgId,\n hostId: job.hostId,\n inputs: {},\n org,\n uid: job.createdBy,\n }\n const refusal = await pluginAdmission(admission, {\n kind: 'build',\n drafts: [{ resource: capability.draftResource, label: capability.noun }],\n writerFor,\n })\n if (refusal) return settle({ slot: unit.slot, status: 'skipped', note: `Not built: ${refusal.error}` })\n const dependencies: Record<string, { op: string; id: string }> = {}\n for (const slot of unit.deps) {\n const dep = units.find((one) => one.slot === slot)\n const row = rows.get(slot)\n if (!dep || !row || !aiBuildItemDelivered(row) || !row.outputs.length) continue\n dependencies[`new:${dep.label}`] = { op: dep.op, id: row.outputs[0] }\n }\n const content = capability.draftContent?.({ name: item.name, args: item.args }, { hostId: job.hostId, dependencies }) ?? item.args\n const checked = writer.check(content, { hostId: job.hostId })\n if (checked.ok === false) {\n return settle(\n failed(unit.slot, { ours: true, reason: 'step-failure', message: checked.problems[0] ?? AI_BUILD_UNIT_EMPTY_COPY }),\n )\n }\n const id = aiBuildUnitJobId(job, unit)\n const written = await writer.write({\n orgId: job.orgId,\n hostId: job.hostId,\n uid: job.createdBy,\n org,\n now: context.now,\n // Drafts of one build share what must not repeat (a cover photo) and read its business (AGL-3755).\n act: { id: aiOriginJobId(job), business: aiSiteWords(job.inputs).about || job.brief || '' },\n id,\n name: item.name,\n content,\n })\n if (written.ok === false) {\n return settle(failed(unit.slot, { ours: false, reason: 'review', message: written.error }))\n }\n const output: AiJobOutput = {\n resource: 'draft',\n id: written.id,\n versionId: written.versionId,\n hostId: job.hostId,\n label: written.name,\n draftResource: capability.draftResource,\n // A resource with no draft state is live once written (AGL-3745, AGL-3746).\n note: aiBuildItemOutputNote(capability, written),\n }\n return settle(\n {\n slot: unit.slot,\n status: degraded ? 'degraded' : 'succeeded',\n outputs: [written.id],\n note,\n ...(degraded ? { degradedBy: degradation.degradedBy } : {}),\n },\n { ...aiUnspentOutcome(model), outputs: [output] },\n )\n }\n\n // This plugin's own runner, under a job derived for the unit.\n const kind = aiBuildUnitJobKind(unit, ops)\n const runner = kind ? runnerFor(kind) : null\n if (!kind || !runner) return settle({ slot: unit.slot, status: 'skipped', note: aiBuildUnavailableCopy(noun) })\n const derived = aiBuildUnitJob(job, unit, { kind, units, ledger, ops, briefLines: degradation.briefLines })\n // An item's kind is asked its own admission first (a campaign's plan,\n // a template's subject), once, before its first pass.\n if (unit.item && rows.get(unit.slot)?.status !== 'running') {\n const refusal = await admissionFor(kind, {\n firestore,\n orgId: job.orgId,\n hostId: job.hostId ?? null,\n inputs: derived.inputs,\n org,\n uid: job.createdBy,\n }).catch((error: unknown) => {\n console.error('ai build item admission failed', { orgId: job.orgId, jobId: job.$id, slot: unit.slot, error })\n return { status: 403 as const, error: AI_BUILD_UNIT_EMPTY_COPY }\n })\n if (refusal) return settle({ slot: unit.slot, status: 'skipped', note: `Not built: ${refusal.error}` })\n }\n\n let outcome: AiJobStepOutcome\n try {\n outcome = await runner({ ...context, job: derived })\n } catch (error) {\n // A provider that will answer later is the machine's to retry; anything\n // else is this item's failure, and the build goes on.\n if (aiUnitErrorRetryable(error)) throw error\n console.error('ai build unit threw', { orgId: job.orgId, jobId: job.$id, slot: unit.slot, error })\n return settle(failed(unit.slot, { ours: true, reason: 'provider', message: AI_BUILD_UNIT_EMPTY_COPY }))\n }\n const spent = aiUnitSpend(outcome)\n const ids = outcome.outputs.map((output) => output.id)\n const stopped = aiUnitFailure(unit.slot, outcome)\n if (stopped) return settle(stopped, spent)\n // A page counts as built only when its plan's sections are in it (AGL-3596).\n if (unit.screen && job.hostId) {\n const page = outcome.outputs.find((output) => output.resource === 'screen')\n const written =\n page !== undefined &&\n (await aiSitePageWritten(\n firestore,\n { hostId: job.hostId, unitJobId: derived.$id, screen: unit.screen, draftId: page.id },\n readNodes,\n ))\n if (!written) {\n return settle(\n failed(unit.slot, { ours: true, reason: 'step-failure', message: AI_BUILD_PAGE_NOT_WRITTEN_COPY }),\n { ...spent, outputs: outcome.outputs.filter((output) => output.resource !== 'screen') },\n )\n }\n }\n const done = settle(\n {\n slot: unit.slot,\n status: degraded ? 'degraded' : 'succeeded',\n outputs: ids,\n note,\n ...(degraded ? { degradedBy: degradation.degradedBy } : {}),\n },\n spent,\n )\n if (done.continue) return done\n // The last unit: what was built goes live where it was asked and confirmed.\n rows.set(unit.slot, { ...(rows.get(unit.slot) as AiJobItemLedger), status: degraded ? 'degraded' : 'succeeded', outputs: ids })\n return finish(done, unit.screen ? outcome.outputs.filter((output) => output.resource === 'screen') : [])\n }\n}\n\nexport const runAiJobBuildStep = createAiJobBuildStep()\n\n/**\n * The least time a build's next pass needs: what the step that builds its\n * next unit registers for the job derived for it; a page pass's when the\n * next unit is another plugin's draft, which asks no model.\n */\nexport function aiBuildJobRunMinimumMs(job: AiJob): number {\n const plan = aiConfirmedPlan(job)\n if (!plan) return AI_JOB_PAGE_STEP_MINIMUM_MS\n const units = aiBuildUnits(plan)\n const ordered = aiBuildOrder(units) ?? units\n const ledger = job.items?.length ? job.items : aiBuildInitialLedger(units)\n const unit = aiBuildNextUnit(ordered, ledger)\n if (!unit) return AI_JOB_PAGE_STEP_MINIMUM_MS\n const kind: AiJobKind | null = unit.screen\n ? 'page'\n : unit.creation\n ? (CREATION_JOB_KINDS[unit.creation.kind] ?? null)\n : (AI_BUILD_ITEM_RUNNER_KINDS[unit.op] ?? null)\n if (!kind) return AI_JOB_PAGE_STEP_MINIMUM_MS\n return aiJobStepRunMinimumMs(aiBuildUnitJob(job, unit, { kind, units, ledger, ops: new Map() }))\n}\n\n/** The runner kinds this plugin's own item operations use, for the time a pass needs without the registry. */\nconst AI_BUILD_ITEM_RUNNER_KINDS: Readonly<Record<string, AiJobKind>> = {\n template: 'template',\n campaign: 'campaign',\n workflow: 'workflow',\n function: 'logic',\n edit: 'edit',\n navigation: 'navigation',\n duplicate: 'duplicate',\n settings: 'settings',\n media: 'media',\n tracking: 'tracking',\n}\n\n/**\n * What a Free build's credits say before it runs (AGL-3722), on its measured\n * p90 rather than its ceiling: `null` when what is left this month covers the\n * p90 — or when nothing is known about what is left, since each pass's\n * reservation still decides — and `null` too for a build the person chose\n * to build as far as it goes (`confirmed`), whose prompt `onConfirmed` is\n * told so the door records it. Otherwise a 409 carrying the prompt: the\n * range, what is left, and the smaller first build. Nothing left at all is a\n * 429. Read off the same two walls the reservation refuses at\n * (`readFreeAiCreditsLeft`), net of give-backs.\n */\nexport async function aiBuildFreeCreditsRefusal(input: {\n firestore: FirebaseFirestore.Firestore\n orgId: string\n org: object | null\n range: AiCreditRange\n smaller?: AiCreditsSmaller | null\n confirmed?: boolean\n onConfirmed?: (prompt: AiCreditsPrompt) => void\n now: Date\n freeCreditsLeft?: typeof readFreeAiCreditsLeft\n}): Promise<AiJobAdmissionRefusal | null> {\n const read = input.freeCreditsLeft ?? readFreeAiCreditsLeft\n const credits = await read(input.firestore, { orgId: input.orgId, org: input.org, now: input.now })\n if (!credits) return null\n if (credits.left <= 0) return { status: 429, error: aiFreeCreditsNoneLeftText(credits.resetsOn) }\n const prompt = aiCreditsPromptFor(input.range, credits, input.smaller ?? null)\n if (!prompt) return null\n if (!input.confirmed) {\n return { status: 409, error: aiCreditsPromptText(prompt, 'build'), code: AI_CREDITS_CONFIRM_CODE, credits: prompt }\n }\n input.onConfirmed?.(prompt)\n return null\n}\n\nexport interface AiBuildAdmissionDeps {\n opsFor?: (context: AiBuildOpsContext) => Promise<AiBuildOps>\n freeCreditsLeft?: typeof readFreeAiCreditsLeft\n ownerOf?: typeof resolveOrgIdForHost\n now?: () => Date\n}\n\n/**\n * A build is admitted for a site of the job's own org where a page can be\n * built; and confirmed only for a plan it can build here — its shape, its\n * operations as this site has them, and on the Free taste a measured p90\n * the month's Free credits still cover — or the person's go-ahead to build\n * what fits (AGL-3722).\n */\nexport function createAiBuildJobAdmission(deps: AiBuildAdmissionDeps = {}): AiJobAdmission {\n const opsFor = deps.opsFor ?? ((context) => aiBuildOps(context))\n const ownerOf = deps.ownerOf ?? resolveOrgIdForHost\n return async (context) => {\n if (!context.hostId) return { status: 400, error: 'Open the site to build on before asking Assist to build' }\n const owner = await ownerOf(context.hostId)\n if (!owner || owner !== context.orgId) return { status: 404, error: 'Unknown site' }\n if (!aiJobStepRunnerFor('page')) return { status: 400, error: 'Building from a request is not available yet.' }\n const plan = context.plan\n if (!plan) return null\n const org = context.org as Partial<AglynOrgBilling> | null\n const freeTaste = aiBuildFreeTaste(org)\n const host = await readHost(context.firestore, context.hostId)\n const ops = await opsFor({ orgId: context.orgId, hostId: context.hostId, org, host, freeTaste })\n const shape = aiBuildPlanShapeRefusal(plan, { freeTaste, ops })\n if (shape) return { status: 400, error: shape }\n // Something only the person can give (AGL-3751): asked, never built without.\n const missing = aiBuildPlanMissingInput(plan, ops)\n if (missing) return { status: 400, error: missing }\n if (freeTaste) {\n const refusal = await aiBuildFreeCreditsRefusal({\n firestore: context.firestore,\n orgId: context.orgId,\n org,\n range: aiBuildCreditRange(plan, { ops }),\n smaller: aiBuildSmaller(plan, ops),\n confirmed: context.creditsConfirmed === true,\n onConfirmed: context.onCreditsConfirmed,\n now: deps.now?.() ?? new Date(),\n freeCreditsLeft: deps.freeCreditsLeft,\n })\n if (refusal) return refusal\n }\n return null\n }\n}\n\nexport const aiBuildJobAdmission = createAiBuildJobAdmission()\n\n/**\n * Registers the build with the least time a pass needs, the time its next\n * pass needs, the passes its largest plan may take, and its admission.\n */\nexport function registerAiBuildJob(): void {\n registerAiJobStep('build', runAiJobBuildStep, {\n minimumMs: AI_JOB_PAGE_STEP_MINIMUM_MS,\n minimumMsFor: aiBuildJobRunMinimumMs,\n })\n registerAiJobStepPasses('build', AI_BUILD_MAX_PASSES)\n registerAiJobAdmission('build', aiBuildJobAdmission)\n}\n"],"names":["aiJobCancelAsked","resolveEffectivePlan","resolveOrgIdForHost","AI_BUILD_LIMITS","AI_BUILD_MADE_INPUT","AI_BUILD_PUBLISH_INPUT","aiArticle","aiBuildCreditRange","aiBuildDegradation","aiBuildInitialLedger","aiBuildItemDelivered","aiBuildItemOpen","aiBuildNextUnit","aiBuildOrder","aiBuildItemOutputNote","aiBuildPlacedItemLines","aiBuildPlanMissingInput","aiBuildPlanShapeRefusal","aiBuildSmaller","aiBuildUnits","isAiPlanNewRef","AI_SITE_MAX_SECTIONS","AI_CREDITS_CONFIRM_CODE","aiCreditsPromptFor","aiCreditsPromptText","aiFreeCreditsNoneLeftText","aiSiteWords","readFreeAiCreditsLeft","aiModelForStep","AI_BUILD_UNIT_EMPTY_COPY","aiBuildBuiltRefs","aiUnitErrorRetryable","aiUnitFailure","aiUnitSpend","aiBuildOps","aiJobAdmissionRefusal","registerAiJobAdmission","aiOriginJobId","readAiDraftNodes","aiConfirmedPlan","aiUnspentOutcome","AI_JOB_PAGE_STEP_MINIMUM_MS","aiPluginDraftAdmissionRefusal","aiPluginDraftWriter","aiSitePageWritten","aiSiteResolvedRef","AI_LAYOUT_SITE_PAGES_INPUT","aiLayoutSitePagesOfPlan","AI_LAYOUT_FORM_PAGE_INPUT","AI_LAYOUT_LANGUAGE_INPUT","aiLayoutFormPageOfPlan","aiDatasetListingsOf","AI_SITE_EVENT_OP","aiEventsListings","AI_FORM_DATASET_MADE_INPUT","AI_LAYOUT_LISTINGS_INPUT","AI_BUILD_STORE_OP","AI_BUILD_STORE_PAGES_PRESENT_NOTE","aiBuildStoreLayoutLinks","aiBuildStoreLayoutOf","aiBuildStorePagesOf","aiBuildStorePagesStillMissing","writeAiStoreLinksLayoutDraft","AI_SITE_STORE_LINKS_INPUT","AI_SITE_STORE_PAGES_NOTE","aiStoreFrameLinks","aiStorePagesToWrite","AI_SITE_STORE_PAGES_INPUT","aiSiteStorePageId","aiSiteStorePagesRefusal","runAiSiteStorePagesUnit","AI_JOB_BRIEF_MAX_CHARS","aiJobPublishesBuild","aiMergeSitePublish","aiPublishGuidedSite","AI_PLANNED_JOB_KINDS","aiJobStepRunMinimumMs","aiJobStepRunnerFor","registerAiJobStep","registerAiJobStepPasses","AI_BUILD_NO_PLAN_COPY","aiBuildUnavailableCopy","noun","AI_BUILD_PAGE_NOT_WRITTEN_COPY","AI_BUILD_MAX_PASSES","units","CREATION_JOB_KINDS","layout","form","component","email","aiBuildUnitJobKind","unit","ops","screen","creation","kind","runnerKind","get","op","aiBuildUnitJobId","job","id","item","$id","slot","aiBuildUnitJob","context","plan","unitPlan","built","ledger","outputs","labels","entry","values","label","brief","trim","reuse","create","screens","items","placedByScreens","Set","flatMap","sections","section","uses","filter","has","duplicateOf","writesTo","push","name","why","purpose","builtLayout","template","record","dataset","map","ref","title","slug","placedByCode","includes","fields","briefLines","inputs","args","originJobId","rows","Map","row","made","pages","one","layouts","entries","length","madeFor","formPage","datasets","find","toLowerCase","some","listings","eventUnits","ledgerRows","written","Boolean","planned","storePages","steps","join","slice","failed","failure","extra","status","readAiStoreSitePages","firestore","hostId","snapshot","collection","doc","select","docs","String","layoutId","aiBuildStorePagesInput","kept","own","page","unitJobId","key","sitePages","shop","replace","split","facts","shopPath","aiBuildStoreLinksOutputs","input","write","output","store","builtLayouts","proposal","links","missing","first","rest","state","storeLinks","hrefs","header","cart","footer","link","href","screenPaths","draft","versionId","uid","createdBy","aiJobId","now","resource","hostSubdomain","note","aiBuildStoreLinksToPublish","reverse","aiBuildFreeTaste","org","readHost","data","createAiJobBuildStep","deps","runnerFor","writerFor","opsFor","admissionFor","pluginAdmission","readNodes","publish","storePagesRunner","storePagesRefusal","readSitePages","writeStoreLinks","model","modelFor","ordered","starting","init","host","orgId","freeTaste","othersOpen","finish","outcome","extraPages","extraOutputs","previous","sitePublish","retry","published","already","pageIds","signal","live","unwrittenHrefs","catch","error","console","jobId","settle","spent","continue","degradation","skip","degradedBy","refusal","derived","ours","reason","message","stopped","ids","done","set","capability","degraded","notes","draftResource","writer","admission","drafts","dependencies","dep","content","draftContent","checked","check","ok","problems","act","business","about","runner","undefined","draftId","runAiJobBuildStep","aiBuildJobRunMinimumMs","AI_BUILD_ITEM_RUNNER_KINDS","campaign","workflow","function","edit","navigation","duplicate","settings","media","tracking","aiBuildFreeCreditsRefusal","read","freeCreditsLeft","credits","left","resetsOn","prompt","range","smaller","confirmed","code","onConfirmed","createAiBuildJobAdmission","ownerOf","owner","shape","creditsConfirmed","onCreditsConfirmed","Date","aiBuildJobAdmission","registerAiBuildJob","minimumMs","minimumMsFor"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,qBAAiB;AAGlD,SAASC,oBAAoB,QAAQ,2CAA0C;AAC/E,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SACEC,eAAe,EACfC,mBAAmB,EACnBC,sBAAsB,EACtBC,SAAS,EACTC,kBAAkB,EAClBC,kBAAkB,EAClBC,oBAAoB,EACpBC,oBAAoB,EACpBC,eAAe,EACfC,eAAe,EACfC,YAAY,EACZC,qBAAqB,EACrBC,sBAAsB,EACtBC,uBAAuB,EACvBC,uBAAuB,EACvBC,cAAc,EACdC,YAAY,QAIP,2BAAuB;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/ai/src/lib/jobs/ai-job-build-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 { aiJobCancelAsked } from './ai-job-cancel'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport type { PluginAiCapability } from '@aglyn/aglyn/plugin-manager/plugin-ai-capabilities'\nimport { resolveEffectivePlan } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { resolveOrgIdForHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport {\n AI_BUILD_LIMITS,\n AI_BUILD_MADE_INPUT,\n AI_BUILD_PUBLISH_INPUT,\n aiArticle,\n aiBuildCreditRange,\n aiBuildDegradation,\n aiBuildInitialLedger,\n aiBuildItemDelivered,\n aiBuildItemOpen,\n aiBuildNextUnit,\n aiBuildOrder,\n aiBuildItemOutputNote,\n aiBuildPlacedItemLines,\n aiBuildPlanMissingInput,\n aiBuildPlanShapeRefusal,\n aiBuildSmaller,\n aiBuildUnits,\n type AiBuildMade,\n type AiBuildOps,\n type AiBuildUnit,\n} from '../model/ai-build-job'\nimport { isAiPlanNewRef, type AiBuildPlanCreateKind } from '../model/ai-build-plan'\nimport type {\n AiJob,\n AiJobItemFailure,\n AiJobItemLedger,\n AiJobKind,\n AiJobOutput,\n AiJobPlan,\n} from '../model/ai-jobs.types'\nimport { AI_SITE_MAX_SECTIONS } from '../model/ai-site-job'\nimport {\n AI_CREDITS_CONFIRM_CODE,\n aiCreditsPromptFor,\n aiCreditsPromptText,\n type AiCreditRange,\n type AiCreditsPrompt,\n type AiCreditsSmaller,\n} from '../model/ai-credit-estimate'\nimport { aiFreeCreditsNoneLeftText, aiSiteWords } from '../model/ai-site-job'\nimport { readFreeAiCreditsLeft } from '../usage/free-ai-credits-left'\nimport { aiModelForStep } from '../providers/routing'\nimport {\n AI_BUILD_UNIT_EMPTY_COPY,\n aiBuildBuiltRefs,\n aiUnitErrorRetryable,\n aiUnitFailure,\n aiUnitSpend,\n} from './ai-build-unit-outcome'\nimport { aiBuildOps, type AiBuildOpsContext } from './ai-build-capabilities'\nimport {\n aiJobAdmissionRefusal,\n registerAiJobAdmission,\n type AiJobAdmission,\n type AiJobAdmissionContext,\n type AiJobAdmissionRefusal,\n} from './ai-job-admission'\nimport { aiOriginJobId } from './ai-job-draft-ids'\nimport { readAiDraftNodes } from './ai-job-drafts'\nimport { aiConfirmedPlan, aiUnspentOutcome } from './ai-job-generation'\nimport { AI_JOB_PAGE_STEP_MINIMUM_MS } from './ai-job-page-budget'\nimport {\n aiPluginDraftAdmissionRefusal,\n aiPluginDraftWriter,\n type AiPluginDraftWriterLookup,\n} from './ai-job-plugin-drafts'\nimport { aiSitePageWritten, aiSiteResolvedRef } from './ai-job-site-step'\nimport { AI_LAYOUT_SITE_PAGES_INPUT, aiLayoutSitePagesOfPlan } from './ai-job-layout-site-pages'\nimport { AI_LAYOUT_FORM_PAGE_INPUT, AI_LAYOUT_LANGUAGE_INPUT, aiJobUsesLayoutLanguage, aiLayoutFormPageOfPlan } from './ai-job-page-language'\nimport { aiDatasetListingsOf } from './ai-job-site-datasets'\nimport { AI_SITE_EVENT_OP, aiEventsListings } from './ai-job-site-events'\nimport { AI_FORM_DATASET_MADE_INPUT } from './ai-job-form-dataset'\nimport { AI_LAYOUT_LISTINGS_INPUT } from '../layout-language/ai-layout-listings'\nimport {\n AI_BUILD_STORE_OP,\n AI_BUILD_STORE_PAGES_PRESENT_NOTE,\n aiBuildStoreLayoutLinks,\n aiBuildStoreLayoutOf,\n aiBuildStorePagesOf,\n aiBuildStorePagesStillMissing,\n type AiBuildStoreLinksState,\n type AiStoreSitePage,\n} from '../model/ai-build-store-pages'\nimport type { AiStoreLayoutLinks } from '../model/ai-layout-store-links'\nimport { writeAiStoreLinksLayoutDraft } from './ai-job-store-links-layout'\nimport type { AiSitePublishStoreLinks } from './ai-site-publish'\nimport {\n AI_SITE_STORE_LINKS_INPUT,\n AI_SITE_STORE_PAGES_NOTE,\n aiStoreFrameLinks,\n aiStorePagesToWrite,\n} from '../model/ai-site-store-pages'\nimport {\n AI_SITE_STORE_PAGES_INPUT,\n aiSiteStorePageId,\n aiSiteStorePagesRefusal,\n runAiSiteStorePagesUnit,\n type AiSiteStorePagesInput,\n} from './ai-job-site-store-pages'\nimport {\n AI_JOB_BRIEF_MAX_CHARS,\n type AiJobItemOutcome,\n type AiJobStepOutcome,\n type AiJobStepRunner,\n} from './ai-job-text-step'\nimport { aiJobPublishesBuild, aiMergeSitePublish, aiPublishGuidedSite } from './ai-site-publish'\nimport {\n AI_PLANNED_JOB_KINDS,\n aiJobStepRunMinimumMs,\n aiJobStepRunnerFor,\n registerAiJobStep,\n registerAiJobStepPasses,\n} from './ai-jobs'\n\n/**\n * The build step (AGL-3616): the generation step of a `build` job, run once\n * the member confirmed the plan their request produced.\n *\n * Like the site scaffold it generalizes, it builds nothing itself and asks no\n * model of its own. Each pass takes the next unit in dependency order and\n * hands it to what builds that kind of thing — a page, layout, form,\n * component, email design or template to this plugin's own step, under a job\n * derived for the unit; another plugin's resource to that plugin's writer on\n * the resource-draft seam, with the content the owner's capability derives\n * from the item's arguments. One unit, one pass, one recorded spend.\n *\n * ── Settled item by item ────────────────────────────────────────────────\n *\n * Where a unit stands is read from the job's ITEM LEDGER, never from counting\n * outputs: the machine writes each pass's row in the transaction that\n * records its spend (`recordStep`). A unit that fails is a FAILED ROW, not a\n * failed job: the pass reports it, the machine gives back that item's spend\n * where the failure was ours, and the next pass builds the next unit. What\n * depended on it is built without it, or skipped where it cannot stand\n * without it (`aiBuildDegradation`). The machine ends the job when nothing is\n * left: `done` when anything was delivered, `failed` — its planning given\n * back too — when nothing was.\n *\n * ── Drafts, unless asked and confirmed ───────────────────────────────────\n *\n * Every unit writes the draft its own kind writes, which nothing publishes.\n * Only a build whose request asked to publish AND whose member ticked the\n * plan card's box puts its built pages live, once, on its last pass, through\n * the guided start's publish.\n */\n\n/** What a build answers with no confirmed plan to build. */\nexport const AI_BUILD_NO_PLAN_COPY = 'This build has no confirmed plan to build.'\n\n/** What a unit says when nothing on this site builds its operation any more. */\nexport const aiBuildUnavailableCopy = (noun: string): string =>\n `Not built: ${aiArticle(noun)} cannot be made on this site right now.`\n\n\n/** What a page that was reported built but holds none of its plan says. */\nexport const AI_BUILD_PAGE_NOT_WRITTEN_COPY = 'The page was not written from its plan.'\n\n\n/**\n * The most passes a build's step may take: every unit at a page's worst — its\n * sections and its listing — so a runner that never finishes is still\n * bounded while the largest plan is not. Try again starts the count over.\n */\nexport const AI_BUILD_MAX_PASSES = AI_BUILD_LIMITS.units * (AI_SITE_MAX_SECTIONS + 1) + 1\n\n/** The job kind a creation of the build is built by. */\nconst CREATION_JOB_KINDS: Partial<Record<AiBuildPlanCreateKind, AiJobKind>> = {\n layout: 'layout',\n form: 'form',\n component: 'component',\n email: 'email',\n}\n\n/** The job kind a unit is built by, where an AI runner builds it. */\nexport function aiBuildUnitJobKind(unit: AiBuildUnit, ops: AiBuildOps): AiJobKind | null {\n if (unit.screen) return 'page'\n if (unit.creation) return CREATION_JOB_KINDS[unit.creation.kind] ?? null\n const runnerKind = ops.get(unit.op)?.runnerKind\n return runnerKind ? (runnerKind as AiJobKind) : null\n}\n\n/** What the job drawer says under an item another plugin's writer made (`model/ai-build-job.ts`). */\nexport { aiBuildItemOutputNote }\n\n/** The id a unit's job, and so its draft, is named by. */\nexport function aiBuildUnitJobId(job: Pick<AiJob, '$id'>, unit: AiBuildUnit): string {\n return unit.creation?.id ?? unit.screen?.id ?? unit.item?.id ?? `${job.$id}-${unit.slot}`\n}\n\n/**\n * The job a unit is built under (generalizing `aiSiteUnitJob`): this job's\n * org, site, creator and model; the kind that builds the unit; a plan\n * narrowed to the unit, its `new:` references resolved to what was built and\n * the failed ones left out; and a brief that says what the unit is, what it\n * is built without, and which blocks its sections place.\n */\nexport function aiBuildUnitJob(\n job: AiJob,\n unit: AiBuildUnit,\n context: {\n kind: AiJobKind\n units: readonly AiBuildUnit[]\n ledger: readonly AiJobItemLedger[]\n ops: AiBuildOps\n briefLines?: readonly string[]\n },\n): AiJob {\n const plan = job.plan as AiJobPlan\n const built = aiBuildBuiltRefs(context.units, context.ledger, job.outputs ?? [])\n const labels = { ...(plan.labels ?? {}) }\n for (const entry of built.values()) labels[entry.id] = entry.label\n const brief = [job.brief.trim()]\n const unitPlan: AiJobPlan = { ...plan, labels, reuse: [...plan.reuse], create: [], screens: [] }\n delete unitPlan.items\n const placedByScreens = new Set(plan.screens.flatMap((screen) => screen.sections.flatMap((section) => section.uses)))\n if (unit.creation) {\n unitPlan.reuse = plan.reuse.filter((entry) => !placedByScreens.has(entry.id))\n unitPlan.create = [\n {\n ...unit.creation,\n duplicateOf: aiSiteResolvedRef(unit.creation.duplicateOf, built),\n // The dataset a form writes to, new or the site's own (AGL-3616); one\n // this build failed to make leaves the form as it always was.\n ...(unit.creation.writesTo ? { writesTo: aiSiteResolvedRef(unit.creation.writesTo, built) } : {}),\n },\n ]\n brief.push(`Build the ${unit.creation.kind} “${unit.creation.name}”: ${unit.creation.why}`)\n }\n if (unit.screen) {\n const screen = unit.screen\n for (const entry of built.values()) {\n unitPlan.reuse.push({ kind: entry.kind, id: entry.id, purpose: `the ${entry.kind} this request built` })\n }\n let builtLayout: string | null = null\n for (const entry of built.values()) if (entry.kind === 'layout') builtLayout = builtLayout ?? entry.id\n unitPlan.screens = [\n {\n ...screen,\n // A page whose layout failed renders inside the site's own: the page\n // step falls back to it when the plan names none.\n layout: aiSiteResolvedRef(screen.layout, built) ?? (isAiPlanNewRef(screen.layout) ? builtLayout : null),\n template: aiSiteResolvedRef(screen.template, built),\n duplicateOf: aiSiteResolvedRef(screen.duplicateOf, built),\n record: screen.record\n ? { ...screen.record, dataset: aiSiteResolvedRef(screen.record.dataset, built) ?? screen.record.dataset }\n : null,\n sections: screen.sections.map((section) => ({\n ...section,\n uses: section.uses\n .map((ref) => aiSiteResolvedRef(ref, built))\n .filter((ref): ref is string => !!ref),\n })),\n },\n ]\n brief.push(`Build the page “${screen.title}”, at ${screen.slug}.`)\n // A build's events are listed by the platform (AGL-3755), never written by the page.\n brief.push(\n ...aiBuildPlacedItemLines(unit, { units: context.units, ledger: context.ledger, ops: context.ops, placedByCode: [AI_SITE_EVENT_OP] }),\n )\n }\n const item = unit.item\n if (item) {\n const noun = context.ops.get(item.op)?.noun ?? item.op\n brief.push(`Build the ${noun} “${item.name}”${item.why ? `: ${item.why}` : '.'}`)\n // A planned kind's step builds the plan's first creation of its kind.\n unitPlan.create = AI_PLANNED_JOB_KINDS.includes(context.kind)\n ? [{ kind: context.kind as AiBuildPlanCreateKind, name: item.name, why: item.why, duplicateOf: null, fields: [], ...(item.id ? { id: item.id } : {}) }]\n : []\n }\n brief.push(...(context.briefLines ?? []))\n const inputs: Record<string, unknown> = {\n ...job.inputs,\n ...(item?.args ?? {}),\n originJobId: aiOriginJobId(job),\n }\n delete inputs[AI_BUILD_PUBLISH_INPUT]\n // An item is told the pages and layouts this build made before it, which\n // its arguments may link as `new:<name>` (a menu item, AGL-3728).\n if (item) {\n const rows = new Map(context.ledger.map((row) => [row.slot, row]))\n const made: AiBuildMade = {\n pages: context.units.flatMap((one) => {\n const row = rows.get(one.slot)\n return one.screen?.id && row && aiBuildItemDelivered(row) ? [{ title: one.screen.title, id: one.screen.id }] : []\n }),\n layouts: [...built.entries()].filter(([, entry]) => entry.kind === 'layout').map(([name, entry]) => ({ name, id: entry.id })),\n }\n if (made.pages.length || made.layouts.length) inputs[AI_BUILD_MADE_INPUT] = made\n }\n // A dataset this build made for its form, which the form may bind (AGL-3616).\n const madeFor = unit.creation?.kind === 'form' && isAiPlanNewRef(unit.creation.writesTo) ? unitPlan.create[0]?.writesTo : null\n if (madeFor) inputs[AI_FORM_DATASET_MADE_INPUT] = madeFor\n // A build's pages and layouts are designed in the layout language and\n // compiled (AGL-3660), told the pages the build plans and where its form is.\n if (context.kind === 'page' || context.kind === 'layout') {\n inputs[AI_LAYOUT_LANGUAGE_INPUT] = true\n const pages = aiLayoutSitePagesOfPlan(plan.screens)\n if (pages.length) inputs[AI_LAYOUT_SITE_PAGES_INPUT] = pages\n const formPage = aiLayoutFormPageOfPlan(plan)\n if (formPage) inputs[AI_LAYOUT_FORM_PAGE_INPUT] = formPage\n // The datasets this build made, repeated in the sections that name them (AGL-3616),\n // and the site's own the plan reuses (AGL-3747): the page reads their fields,\n // and the record pages the site already serves for them, off its inventory.\n const datasets = [...built.entries()]\n .filter(([, entry]) => entry.kind === 'dataset')\n .map(([name, entry]) => ({ id: entry.id, name: context.units.find((one) => one.item?.name.toLowerCase() === name)?.label ?? entry.label }))\n for (const entry of plan.reuse) {\n if (entry.kind !== 'dataset' || datasets.some((one) => one.id === entry.id)) continue\n datasets.push({ id: entry.id, name: plan.labels?.[entry.id] ?? entry.id })\n }\n const listings = aiDatasetListingsOf(datasets, plan.screens)\n // The events this build wrote, in the sections that name them (AGL-3755).\n const eventUnits = context.units.filter((one) => one.item?.op === AI_SITE_EVENT_OP)\n const ledgerRows = new Map(context.ledger.map((row) => [row.slot, row]))\n listings.push(\n ...aiEventsListings({\n written: eventUnits\n .filter((one) => {\n const row = ledgerRows.get(one.slot)\n return Boolean(row && aiBuildItemDelivered(row) && row.outputs.length)\n })\n .map((one) => one.item?.name ?? one.label),\n planned: eventUnits.map((one) => one.item?.name ?? one.label),\n screens: plan.screens,\n }),\n )\n if (listings.length) inputs[AI_LAYOUT_LISTINGS_INPUT] = listings\n }\n // A build that makes the site a store links its account and policies from\n // the layout it makes (AGL-3676), by path: they are written after it.\n const storePages = aiBuildStorePagesOf(plan)\n if (context.kind === 'layout' && storePages) inputs[AI_SITE_STORE_LINKS_INPUT] = aiStoreFrameLinks(storePages.pages)\n return {\n ...job,\n $id: aiBuildUnitJobId(job, unit),\n kind: context.kind,\n steps: [],\n outputs: [],\n items: null,\n plan: item && !AI_PLANNED_JOB_KINDS.includes(context.kind) ? null : unitPlan,\n inputs,\n brief: brief.join('\\n').slice(0, AI_JOB_BRIEF_MAX_CHARS),\n }\n}\n\n/** The unit's failure, for its row: ours or not, why, in customer-safe words. */\nfunction failed(\n slot: string,\n failure: AiJobItemFailure,\n extra: Partial<AiJobItemOutcome> = {},\n): AiJobItemOutcome {\n return { slot, status: 'failed', failure, ...extra }\n}\n\nexport interface AiJobBuildStepDeps {\n /** The runner registry; specs hand in fakes. */\n runnerFor?: typeof aiJobStepRunnerFor\n /** The draft writer registry; specs hand in fakes. */\n writerFor?: AiPluginDraftWriterLookup\n /** The operations this site may use; the registry and its gates otherwise. */\n opsFor?: (context: AiBuildOpsContext) => Promise<AiBuildOps>\n /** A runner kind's own admission, asked before its item runs; the registry's otherwise. */\n admissionFor?: typeof aiJobAdmissionRefusal\n /** Another plugin's admission for its writer; the seam's otherwise. */\n pluginAdmission?: typeof aiPluginDraftAdmissionRefusal\n /** The draft reader a built page is checked through. */\n readNodes?: typeof readAiDraftNodes\n /** The publish a build asked for and confirmed. */\n publish?: typeof aiPublishGuidedSite\n /** A store's own pages' pass and whether they may be added here (AGL-3676); specs hand in fakes. */\n storePages?: AiJobStepRunner\n storePagesRefusal?: typeof aiSiteStorePagesRefusal\n /** The site's pages as they are now, which a store's own pages are checked against before they are written. */\n readSitePages?: typeof readAiStoreSitePages\n /** The draft version of the site's layout a store's links are written into. */\n writeStoreLinks?: typeof writeAiStoreLinksLayoutDraft\n}\n\n/** The site's pages as a store's own pages are checked against them (AGL-3676): every page that is not deleted. */\nexport async function readAiStoreSitePages(firestore: FirebaseFirestore.Firestore, hostId: string): Promise<AiStoreSitePage[]> {\n const snapshot = await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('screens')\n .select('displayName', 'slug', 'kind', 'deletedAt', 'layoutId')\n .get()\n return snapshot.docs.flatMap((doc) => {\n const kind = doc.get('kind')\n if (doc.get('deletedAt') || (kind && kind !== 'template')) return []\n const slug = String(doc.get('slug') ?? '')\n const layoutId = doc.get('layoutId')\n return slug\n ? [{ id: doc.id, slug, title: String(doc.get('displayName') ?? ''), template: kind === 'template', layoutId: typeof layoutId === 'string' && layoutId ? layoutId : null }]\n : []\n })\n}\n\n/**\n * What a build's store pages unit is told (AGL-3676): the pages its plan kept,\n * less any the site has gained since — never counting the pages this unit\n * wrote itself on an earlier pass, which it finds again by their ids — what\n * their words link, and the layout they render inside: the plan's Shop\n * page's, else the site's own (`aiBuildStoreLayoutOf`).\n */\nexport function aiBuildStorePagesInput(\n job: AiJob,\n context: { unitJobId: string; sitePages: readonly AiStoreSitePage[]; units: readonly AiBuildUnit[]; ledger: readonly AiJobItemLedger[] },\n): AiSiteStorePagesInput | null {\n const plan = job.plan as AiJobPlan\n const kept = aiBuildStorePagesOf(plan)\n if (!kept) return null\n const own = new Set(kept.pages.map((page) => aiSiteStorePageId(context.unitJobId, page.key)))\n const pages = aiBuildStorePagesStillMissing(\n kept.pages,\n context.sitePages.filter((page) => !page.id || !own.has(page.id)),\n )\n const built = aiBuildBuiltRefs(context.units, context.ledger, job.outputs ?? [])\n const shop = plan.screens.find((screen) => !screen.record && screen.slug.replace(/^\\/+/, '').split('/')[0].toLowerCase() === kept.facts.shopPath.slice(1))\n const layout = shop ? aiSiteResolvedRef(shop.layout, built) : null\n return {\n pages,\n facts: kept.facts,\n layoutId: aiBuildStoreLayoutOf(layout && !isAiPlanNewRef(layout) ? layout : null, context.sitePages),\n }\n}\n\n/**\n * Adds a store's links to the site's own layout (AGL-3676), as a draft\n * version, where the build made no layout of its own for its store pages: the\n * outputs that record it — the layout version written (`storeLinks: draft`),\n * and on the first page `storeLinks: missing` where the layout had no header\n * or footer list to add them to, or there is no layout at all.\n */\nexport async function aiBuildStoreLinksOutputs(\n firestore: FirebaseFirestore.Firestore,\n input: {\n job: AiJob\n unitJobId: string\n store: AiSiteStorePagesInput\n outputs: readonly AiJobOutput[]\n sitePages: readonly AiStoreSitePage[]\n builtLayouts: ReadonlySet<string>\n now: Date\n },\n write: typeof writeAiStoreLinksLayoutDraft = writeAiStoreLinksLayoutDraft,\n): Promise<AiJobOutput[]> {\n const outputs = input.outputs.map((output) => ({ ...output }))\n const layoutId = input.store.layoutId\n // A layout this build made was told the store's links as it was compiled.\n if (layoutId && input.builtLayouts.has(layoutId)) return outputs\n const written = new Set(outputs.map((output) => output.proposal?.['storePage']).filter((key): key is string => typeof key === 'string'))\n const links = aiBuildStoreLayoutLinks(input.store.pages, written)\n const missing = (): AiJobOutput[] => {\n const [first, ...rest] = outputs\n const state: AiBuildStoreLinksState = 'missing'\n return first ? [{ ...first, proposal: { ...(first.proposal ?? {}), storeLinks: state } }, ...rest] : outputs\n }\n if (!layoutId || !input.job.hostId) return missing()\n const hrefs = new Set([...links.header, ...(links.cart ? [links.cart] : []), ...links.footer].map((link) => link.href.slice(1)))\n const screenPaths: Record<string, string> = {}\n for (const page of input.sitePages) {\n const slug = page.slug.replace(/^\\/+/, '').split('/')[0].toLowerCase()\n if (page.id && hrefs.has(slug)) screenPaths[page.id] = slug\n }\n const draft = await write(firestore, {\n hostId: input.job.hostId,\n layoutId,\n versionId: `${input.unitJobId}-links`.slice(0, 64),\n links,\n screenPaths,\n uid: input.job.createdBy,\n aiJobId: aiOriginJobId(input.job),\n now: input.now,\n })\n if (draft.status === 'present') return outputs\n if (draft.status === 'gone') return missing()\n const versionId = draft.versionId\n const layout: AiJobOutput[] = versionId\n ? [\n {\n resource: 'layout',\n id: draft.layoutId,\n versionId,\n hostId: input.job.hostId,\n hostSubdomain: outputs.find((output) => output.hostSubdomain)?.hostSubdomain,\n label: draft.name,\n note: 'A new draft version with Account and policy links. Visitors see it once it is published.',\n proposal: { storeLinks: 'draft' satisfies AiBuildStoreLinksState, links, screenPaths },\n },\n ]\n : []\n return [...(draft.status === 'unrecognized' ? missing() : outputs), ...layout]\n}\n\n/** The store's links a build drafted into the site's layout (AGL-3676), as its publish puts them live; `null` where it drafted none. */\nexport function aiBuildStoreLinksToPublish(outputs: readonly AiJobOutput[]): AiSitePublishStoreLinks | null {\n // The newest: a retried store drafts its links again after the first attempt's (AGL-3739).\n const draft = [...outputs]\n .reverse()\n .find((output) => output.resource === 'layout' && output.proposal?.['storeLinks'] === 'draft' && output.versionId)\n if (!draft?.versionId) return null\n return {\n layoutId: draft.id,\n versionId: draft.versionId,\n links: draft.proposal?.['links'] as AiStoreLayoutLinks,\n screenPaths: (draft.proposal?.['screenPaths'] ?? {}) as Record<string, string>,\n }\n}\n\n/** Whether a build's workspace spends the Free taste. */\nexport function aiBuildFreeTaste(org: object | null | undefined): boolean {\n return Boolean(org) && resolveEffectivePlan(org as never) === 'free'\n}\n\n/** The site document a gate reads, or `null`. */\nasync function readHost(firestore: FirebaseFirestore.Firestore, hostId: string | null) {\n if (!hostId) return null\n return ((await firestore.collection('hosts').doc(hostId).get()).data() ?? null) as Record<string, unknown> | null\n}\n\nexport function createAiJobBuildStep(deps: AiJobBuildStepDeps = {}): AiJobStepRunner {\n const runnerFor = deps.runnerFor ?? aiJobStepRunnerFor\n const writerFor = deps.writerFor ?? aiPluginDraftWriter\n const opsFor = deps.opsFor ?? ((context) => aiBuildOps(context))\n const admissionFor = deps.admissionFor ?? aiJobAdmissionRefusal\n const pluginAdmission = deps.pluginAdmission ?? aiPluginDraftAdmissionRefusal\n const readNodes = deps.readNodes ?? readAiDraftNodes\n const publish = deps.publish ?? aiPublishGuidedSite\n const storePagesRunner = deps.storePages ?? runAiSiteStorePagesUnit\n const storePagesRefusal = deps.storePagesRefusal ?? aiSiteStorePagesRefusal\n const readSitePages = deps.readSitePages ?? readAiStoreSitePages\n const writeStoreLinks = deps.writeStoreLinks ?? writeAiStoreLinksLayoutDraft\n\n return async (context): Promise<AiJobStepOutcome> => {\n const { job, firestore } = context\n const model = context.modelFor?.('job.plan') ?? aiModelForStep('job.plan')\n const plan = aiConfirmedPlan(job)\n if (!plan) return { ...aiUnspentOutcome(model), failure: AI_BUILD_NO_PLAN_COPY }\n const org = (context.org ?? null) as Partial<AglynOrgBilling> | null\n const units = aiBuildUnits(plan)\n const ordered = aiBuildOrder(units) ?? units\n const starting = !job.items?.length\n const ledger = starting ? aiBuildInitialLedger(units) : (job.items as AiJobItemLedger[])\n const init = starting ? { items: ledger } : {}\n const unit = aiBuildNextUnit(ordered, ledger)\n const rows = new Map(ledger.map((row) => [row.slot, row]))\n const host = await readHost(firestore, job.hostId ?? null)\n const ops = await opsFor({\n orgId: job.orgId,\n hostId: job.hostId ?? null,\n org,\n host,\n freeTaste: aiBuildFreeTaste(org),\n })\n\n /** Whether units other than this one are still to build. */\n const othersOpen = (slot: string) =>\n ordered.some((one) => one.slot !== slot && aiBuildItemOpen(rows.get(one.slot) ?? { status: 'pending' }))\n\n /**\n * The build's last pass puts its pages live, where it was asked and\n * confirmed. Once it has, Try again's last pass puts only the pages the\n * retry built live (AGL-3739, AGL-3730's fix for a site start),\n * merged into the record of the first.\n */\n const finish = async (\n outcome: AiJobStepOutcome,\n extraPages: readonly AiJobOutput[] = [],\n extraOutputs: readonly AiJobOutput[] = [],\n ): Promise<AiJobStepOutcome> => {\n if (!aiJobPublishesBuild(job) || !job.hostId) return outcome\n const previous = job.sitePublish ?? null\n const retry = Boolean(previous?.published.length)\n const already = new Set((previous?.published ?? []).map((page) => page.id))\n // A record template renders once per record only once its binding is\n // saved, so it is never published at its own address (AGL-3616).\n // A store's own pages (AGL-3676) go live with the pages the build planned.\n const pageIds = new Set(\n units\n .filter(\n (one) =>\n ((one.screen && !one.screen.record) || one.op === AI_BUILD_STORE_OP) &&\n aiBuildItemDelivered(rows.get(one.slot) ?? { status: 'pending' }),\n )\n .flatMap((one) => rows.get(one.slot)?.outputs ?? []),\n )\n const built = [\n ...(job.outputs ?? []).filter((output) => output.resource === 'screen' && pageIds.has(output.id)),\n ...extraPages,\n ]\n const pages = built.filter((page) => !already.has(page.id))\n if (!pages.length) return outcome\n // A canceled build never puts anything live (AGL-3616): its pages stay drafts.\n if (await aiJobCancelAsked(firestore, job, context.signal)) return outcome\n // The store pages a layout this build made links and that were not written come out of it.\n const storePages = aiBuildStorePagesOf(plan)\n const live = new Set(built.map((page) => page.proposal?.['storePage']).filter(Boolean))\n const unwrittenHrefs = storePages\n ? aiStorePagesToWrite(storePages.pages).filter((page) => !live.has(page.key)).map((page) => page.href)\n : []\n // A retry puts the store's links live only with store pages it built:\n // the first publish's links draft is live already, and a person may have edited it since.\n const storeLinks =\n !retry || pages.some((page) => page.proposal?.['storePage'])\n ? aiBuildStoreLinksToPublish([...(job.outputs ?? []), ...extraOutputs])\n : null\n const sitePublish = await publish(firestore, {\n job,\n outputs: pages,\n now: context.now,\n ...(unwrittenHrefs.length ? { unwrittenHrefs } : {}),\n ...(storeLinks ? { storeLinks } : {}),\n ...(retry ? { retry: true } : {}),\n }).catch((error: unknown) => {\n console.error('ai build publish threw', { orgId: job.orgId, jobId: job.$id, error })\n return null\n })\n if (!sitePublish) return outcome\n return { ...outcome, sitePublish: previous ? aiMergeSitePublish(previous, sitePublish) : sitePublish }\n }\n\n if (!unit) return finish({ ...aiUnspentOutcome(model), ...init })\n\n const settle = (item: AiJobItemOutcome, spent: AiJobStepOutcome = aiUnspentOutcome(model)): AiJobStepOutcome => ({\n ...spent,\n ...init,\n item,\n ...(item.status === 'running' || othersOpen(unit.slot) ? { continue: true } : {}),\n })\n\n // What its dependencies came to.\n const degradation = aiBuildDegradation(unit, { units, ledger, ops })\n if (degradation.skip) {\n return settle({ slot: unit.slot, status: 'skipped', note: degradation.skip, degradedBy: degradation.degradedBy })\n }\n // A store's own pages (AGL-3676): written by code, behind the site start's gate.\n if (unit.op === AI_BUILD_STORE_OP) {\n if (!job.hostId) return settle({ slot: unit.slot, status: 'skipped', note: 'Not built: open the site first.' })\n if (rows.get(unit.slot)?.status !== 'running') {\n const refusal = await storePagesRefusal({ ...context, job }).catch((error: unknown) => {\n console.error('ai build store pages admission failed', { orgId: job.orgId, jobId: job.$id, error })\n return AI_BUILD_UNIT_EMPTY_COPY\n })\n if (refusal) return settle({ slot: unit.slot, status: 'skipped', note: `Not built: ${refusal}` })\n }\n const unitJobId = aiBuildUnitJobId(job, unit)\n const sitePages = await readSitePages(firestore, job.hostId)\n const input = aiBuildStorePagesInput(job, { unitJobId, sitePages, units, ledger })\n if (!input) return settle({ slot: unit.slot, status: 'skipped', note: aiBuildUnavailableCopy('store page') })\n if (!aiStorePagesToWrite(input.pages).length) {\n return settle({ slot: unit.slot, status: 'skipped', note: AI_BUILD_STORE_PAGES_PRESENT_NOTE })\n }\n const derived: AiJob = {\n ...job,\n $id: unitJobId,\n kind: 'text',\n steps: [],\n outputs: [],\n items: null,\n plan: null,\n inputs: { ...job.inputs, originJobId: aiOriginJobId(job), [AI_SITE_STORE_PAGES_INPUT]: input },\n }\n let outcome: AiJobStepOutcome\n try {\n outcome = await storePagesRunner({ ...context, job: derived })\n } catch (error) {\n if (aiUnitErrorRetryable(error)) throw error\n console.error('ai build store pages threw', { orgId: job.orgId, jobId: job.$id, error })\n return settle(failed(unit.slot, { ours: true, reason: 'step-failure', message: AI_BUILD_UNIT_EMPTY_COPY }))\n }\n const stopped = aiUnitFailure(unit.slot, outcome)\n if (stopped) return settle(stopped, aiUnitSpend(outcome))\n // The site's own header and footer link them (AGL-3676), in a draft\n // version of its layout; a layout this build made already does.\n const builtLayouts = new Set(\n [...aiBuildBuiltRefs(units, ledger, job.outputs ?? []).values()].filter((entry) => entry.kind === 'layout').map((entry) => entry.id),\n )\n const outputs = await aiBuildStoreLinksOutputs(\n firestore,\n { job, unitJobId, store: input, outputs: outcome.outputs, sitePages, builtLayouts, now: context.now },\n writeStoreLinks,\n ).catch((error: unknown) => {\n console.error('ai build store links not written', { orgId: job.orgId, jobId: job.$id, error })\n return outcome.outputs\n })\n const ids = outputs.map((output) => output.id)\n const done = settle({ slot: unit.slot, status: 'succeeded', outputs: ids, note: AI_SITE_STORE_PAGES_NOTE }, { ...aiUnitSpend(outcome), outputs })\n if (done.continue) return done\n rows.set(unit.slot, { ...(rows.get(unit.slot) as AiJobItemLedger), status: 'succeeded', outputs: ids })\n return finish(\n done,\n outputs.filter((output) => output.resource === 'screen'),\n outputs,\n )\n }\n\n const capability = ops.get(unit.op)\n const noun = capability?.noun ?? unit.op\n if (!capability) return settle({ slot: unit.slot, status: 'skipped', note: aiBuildUnavailableCopy(noun) })\n const degraded = degradation.degradedBy.length > 0\n const note = degradation.notes.length ? degradation.notes.join(' ') : null\n\n // Another plugin's resource: its writer, with the content its capability derives.\n if (capability.draftResource) {\n const item = unit.item\n const writer = writerFor(capability.draftResource)\n if (!item || !writer || !job.hostId) {\n return settle({ slot: unit.slot, status: 'skipped', note: aiBuildUnavailableCopy(noun) })\n }\n const admission: AiJobAdmissionContext = {\n firestore,\n orgId: job.orgId,\n hostId: job.hostId,\n inputs: {},\n org,\n uid: job.createdBy,\n }\n const refusal = await pluginAdmission(admission, {\n kind: 'build',\n drafts: [{ resource: capability.draftResource, label: capability.noun }],\n writerFor,\n })\n if (refusal) return settle({ slot: unit.slot, status: 'skipped', note: `Not built: ${refusal.error}` })\n const dependencies: Record<string, { op: string; id: string }> = {}\n for (const slot of unit.deps) {\n const dep = units.find((one) => one.slot === slot)\n const row = rows.get(slot)\n if (!dep || !row || !aiBuildItemDelivered(row) || !row.outputs.length) continue\n dependencies[`new:${dep.label}`] = { op: dep.op, id: row.outputs[0] }\n }\n const content = capability.draftContent?.({ name: item.name, args: item.args }, { hostId: job.hostId, dependencies }) ?? item.args\n const checked = writer.check(content, { hostId: job.hostId })\n if (checked.ok === false) {\n return settle(\n failed(unit.slot, { ours: true, reason: 'step-failure', message: checked.problems[0] ?? AI_BUILD_UNIT_EMPTY_COPY }),\n )\n }\n const id = aiBuildUnitJobId(job, unit)\n const written = await writer.write({\n orgId: job.orgId,\n hostId: job.hostId,\n uid: job.createdBy,\n org,\n now: context.now,\n // Drafts of one build share what must not repeat (a cover photo) and read its business (AGL-3755).\n act: { id: aiOriginJobId(job), business: aiSiteWords(job.inputs).about || job.brief || '' },\n id,\n name: item.name,\n content,\n })\n if (written.ok === false) {\n return settle(failed(unit.slot, { ours: false, reason: 'review', message: written.error }))\n }\n const output: AiJobOutput = {\n resource: 'draft',\n id: written.id,\n versionId: written.versionId,\n hostId: job.hostId,\n label: written.name,\n draftResource: capability.draftResource,\n // A resource with no draft state is live once written (AGL-3745, AGL-3746).\n note: aiBuildItemOutputNote(capability, written),\n }\n return settle(\n {\n slot: unit.slot,\n status: degraded ? 'degraded' : 'succeeded',\n outputs: [written.id],\n note,\n ...(degraded ? { degradedBy: degradation.degradedBy } : {}),\n },\n { ...aiUnspentOutcome(model), outputs: [output] },\n )\n }\n\n // This plugin's own runner, under a job derived for the unit.\n const kind = aiBuildUnitJobKind(unit, ops)\n const runner = kind ? runnerFor(kind) : null\n if (!kind || !runner) return settle({ slot: unit.slot, status: 'skipped', note: aiBuildUnavailableCopy(noun) })\n const derived = aiBuildUnitJob(job, unit, { kind, units, ledger, ops, briefLines: degradation.briefLines })\n // An item's kind is asked its own admission first (a campaign's plan,\n // a template's subject), once, before its first pass.\n if (unit.item && rows.get(unit.slot)?.status !== 'running') {\n const refusal = await admissionFor(kind, {\n firestore,\n orgId: job.orgId,\n hostId: job.hostId ?? null,\n inputs: derived.inputs,\n org,\n uid: job.createdBy,\n }).catch((error: unknown) => {\n console.error('ai build item admission failed', { orgId: job.orgId, jobId: job.$id, slot: unit.slot, error })\n return { status: 403 as const, error: AI_BUILD_UNIT_EMPTY_COPY }\n })\n if (refusal) return settle({ slot: unit.slot, status: 'skipped', note: `Not built: ${refusal.error}` })\n }\n\n let outcome: AiJobStepOutcome\n try {\n outcome = await runner({ ...context, job: derived })\n } catch (error) {\n // A provider that will answer later is the machine's to retry; anything\n // else is this item's failure, and the build goes on.\n if (aiUnitErrorRetryable(error)) throw error\n console.error('ai build unit threw', { orgId: job.orgId, jobId: job.$id, slot: unit.slot, error })\n return settle(failed(unit.slot, { ours: true, reason: 'provider', message: AI_BUILD_UNIT_EMPTY_COPY }))\n }\n const spent = aiUnitSpend(outcome)\n const ids = outcome.outputs.map((output) => output.id)\n const stopped = aiUnitFailure(unit.slot, outcome)\n if (stopped) return settle(stopped, spent)\n // A page counts as built only when its plan's sections are in it (AGL-3596).\n if (unit.screen && job.hostId) {\n const page = outcome.outputs.find((output) => output.resource === 'screen')\n const written =\n page !== undefined &&\n (await aiSitePageWritten(\n firestore,\n {\n hostId: job.hostId,\n unitJobId: derived.$id,\n screen: unit.screen,\n draftId: page.id,\n layoutLanguage: aiJobUsesLayoutLanguage(derived),\n },\n readNodes,\n ))\n if (!written) {\n return settle(\n failed(unit.slot, { ours: true, reason: 'step-failure', message: AI_BUILD_PAGE_NOT_WRITTEN_COPY }),\n { ...spent, outputs: outcome.outputs.filter((output) => output.resource !== 'screen') },\n )\n }\n }\n const done = settle(\n {\n slot: unit.slot,\n status: degraded ? 'degraded' : 'succeeded',\n outputs: ids,\n note,\n ...(degraded ? { degradedBy: degradation.degradedBy } : {}),\n },\n spent,\n )\n if (done.continue) return done\n // The last unit: what was built goes live where it was asked and confirmed.\n rows.set(unit.slot, { ...(rows.get(unit.slot) as AiJobItemLedger), status: degraded ? 'degraded' : 'succeeded', outputs: ids })\n return finish(done, unit.screen ? outcome.outputs.filter((output) => output.resource === 'screen') : [])\n }\n}\n\nexport const runAiJobBuildStep = createAiJobBuildStep()\n\n/**\n * The least time a build's next pass needs: what the step that builds its\n * next unit registers for the job derived for it; a page pass's when the\n * next unit is another plugin's draft, which asks no model.\n */\nexport function aiBuildJobRunMinimumMs(job: AiJob): number {\n const plan = aiConfirmedPlan(job)\n if (!plan) return AI_JOB_PAGE_STEP_MINIMUM_MS\n const units = aiBuildUnits(plan)\n const ordered = aiBuildOrder(units) ?? units\n const ledger = job.items?.length ? job.items : aiBuildInitialLedger(units)\n const unit = aiBuildNextUnit(ordered, ledger)\n if (!unit) return AI_JOB_PAGE_STEP_MINIMUM_MS\n const kind: AiJobKind | null = unit.screen\n ? 'page'\n : unit.creation\n ? (CREATION_JOB_KINDS[unit.creation.kind] ?? null)\n : (AI_BUILD_ITEM_RUNNER_KINDS[unit.op] ?? null)\n if (!kind) return AI_JOB_PAGE_STEP_MINIMUM_MS\n return aiJobStepRunMinimumMs(aiBuildUnitJob(job, unit, { kind, units, ledger, ops: new Map() }))\n}\n\n/** The runner kinds this plugin's own item operations use, for the time a pass needs without the registry. */\nconst AI_BUILD_ITEM_RUNNER_KINDS: Readonly<Record<string, AiJobKind>> = {\n template: 'template',\n campaign: 'campaign',\n workflow: 'workflow',\n function: 'logic',\n edit: 'edit',\n navigation: 'navigation',\n duplicate: 'duplicate',\n settings: 'settings',\n media: 'media',\n tracking: 'tracking',\n}\n\n/**\n * What a Free build's credits say before it runs (AGL-3722), on its measured\n * p90 rather than its ceiling: `null` when what is left this month covers the\n * p90 — or when nothing is known about what is left, since each pass's\n * reservation still decides — and `null` too for a build the person chose\n * to build as far as it goes (`confirmed`), whose prompt `onConfirmed` is\n * told so the door records it. Otherwise a 409 carrying the prompt: the\n * range, what is left, and the smaller first build. Nothing left at all is a\n * 429. Read off the same two walls the reservation refuses at\n * (`readFreeAiCreditsLeft`), net of give-backs.\n */\nexport async function aiBuildFreeCreditsRefusal(input: {\n firestore: FirebaseFirestore.Firestore\n orgId: string\n org: object | null\n range: AiCreditRange\n smaller?: AiCreditsSmaller | null\n confirmed?: boolean\n onConfirmed?: (prompt: AiCreditsPrompt) => void\n now: Date\n freeCreditsLeft?: typeof readFreeAiCreditsLeft\n}): Promise<AiJobAdmissionRefusal | null> {\n const read = input.freeCreditsLeft ?? readFreeAiCreditsLeft\n const credits = await read(input.firestore, { orgId: input.orgId, org: input.org, now: input.now })\n if (!credits) return null\n if (credits.left <= 0) return { status: 429, error: aiFreeCreditsNoneLeftText(credits.resetsOn) }\n const prompt = aiCreditsPromptFor(input.range, credits, input.smaller ?? null)\n if (!prompt) return null\n if (!input.confirmed) {\n return { status: 409, error: aiCreditsPromptText(prompt, 'build'), code: AI_CREDITS_CONFIRM_CODE, credits: prompt }\n }\n input.onConfirmed?.(prompt)\n return null\n}\n\nexport interface AiBuildAdmissionDeps {\n opsFor?: (context: AiBuildOpsContext) => Promise<AiBuildOps>\n freeCreditsLeft?: typeof readFreeAiCreditsLeft\n ownerOf?: typeof resolveOrgIdForHost\n now?: () => Date\n}\n\n/**\n * A build is admitted for a site of the job's own org where a page can be\n * built; and confirmed only for a plan it can build here — its shape, its\n * operations as this site has them, and on the Free taste a measured p90\n * the month's Free credits still cover — or the person's go-ahead to build\n * what fits (AGL-3722).\n */\nexport function createAiBuildJobAdmission(deps: AiBuildAdmissionDeps = {}): AiJobAdmission {\n const opsFor = deps.opsFor ?? ((context) => aiBuildOps(context))\n const ownerOf = deps.ownerOf ?? resolveOrgIdForHost\n return async (context) => {\n if (!context.hostId) return { status: 400, error: 'Open the site to build on before asking Assist to build' }\n const owner = await ownerOf(context.hostId)\n if (!owner || owner !== context.orgId) return { status: 404, error: 'Unknown site' }\n if (!aiJobStepRunnerFor('page')) return { status: 400, error: 'Building from a request is not available yet.' }\n const plan = context.plan\n if (!plan) return null\n const org = context.org as Partial<AglynOrgBilling> | null\n const freeTaste = aiBuildFreeTaste(org)\n const host = await readHost(context.firestore, context.hostId)\n const ops = await opsFor({ orgId: context.orgId, hostId: context.hostId, org, host, freeTaste })\n const shape = aiBuildPlanShapeRefusal(plan, { freeTaste, ops })\n if (shape) return { status: 400, error: shape }\n // Something only the person can give (AGL-3751): asked, never built without.\n const missing = aiBuildPlanMissingInput(plan, ops)\n if (missing) return { status: 400, error: missing }\n if (freeTaste) {\n const refusal = await aiBuildFreeCreditsRefusal({\n firestore: context.firestore,\n orgId: context.orgId,\n org,\n range: aiBuildCreditRange(plan, { ops }),\n smaller: aiBuildSmaller(plan, ops),\n confirmed: context.creditsConfirmed === true,\n onConfirmed: context.onCreditsConfirmed,\n now: deps.now?.() ?? new Date(),\n freeCreditsLeft: deps.freeCreditsLeft,\n })\n if (refusal) return refusal\n }\n return null\n }\n}\n\nexport const aiBuildJobAdmission = createAiBuildJobAdmission()\n\n/**\n * Registers the build with the least time a pass needs, the time its next\n * pass needs, the passes its largest plan may take, and its admission.\n */\nexport function registerAiBuildJob(): void {\n registerAiJobStep('build', runAiJobBuildStep, {\n minimumMs: AI_JOB_PAGE_STEP_MINIMUM_MS,\n minimumMsFor: aiBuildJobRunMinimumMs,\n })\n registerAiJobStepPasses('build', AI_BUILD_MAX_PASSES)\n registerAiJobAdmission('build', aiBuildJobAdmission)\n}\n"],"names":["aiJobCancelAsked","resolveEffectivePlan","resolveOrgIdForHost","AI_BUILD_LIMITS","AI_BUILD_MADE_INPUT","AI_BUILD_PUBLISH_INPUT","aiArticle","aiBuildCreditRange","aiBuildDegradation","aiBuildInitialLedger","aiBuildItemDelivered","aiBuildItemOpen","aiBuildNextUnit","aiBuildOrder","aiBuildItemOutputNote","aiBuildPlacedItemLines","aiBuildPlanMissingInput","aiBuildPlanShapeRefusal","aiBuildSmaller","aiBuildUnits","isAiPlanNewRef","AI_SITE_MAX_SECTIONS","AI_CREDITS_CONFIRM_CODE","aiCreditsPromptFor","aiCreditsPromptText","aiFreeCreditsNoneLeftText","aiSiteWords","readFreeAiCreditsLeft","aiModelForStep","AI_BUILD_UNIT_EMPTY_COPY","aiBuildBuiltRefs","aiUnitErrorRetryable","aiUnitFailure","aiUnitSpend","aiBuildOps","aiJobAdmissionRefusal","registerAiJobAdmission","aiOriginJobId","readAiDraftNodes","aiConfirmedPlan","aiUnspentOutcome","AI_JOB_PAGE_STEP_MINIMUM_MS","aiPluginDraftAdmissionRefusal","aiPluginDraftWriter","aiSitePageWritten","aiSiteResolvedRef","AI_LAYOUT_SITE_PAGES_INPUT","aiLayoutSitePagesOfPlan","AI_LAYOUT_FORM_PAGE_INPUT","AI_LAYOUT_LANGUAGE_INPUT","aiJobUsesLayoutLanguage","aiLayoutFormPageOfPlan","aiDatasetListingsOf","AI_SITE_EVENT_OP","aiEventsListings","AI_FORM_DATASET_MADE_INPUT","AI_LAYOUT_LISTINGS_INPUT","AI_BUILD_STORE_OP","AI_BUILD_STORE_PAGES_PRESENT_NOTE","aiBuildStoreLayoutLinks","aiBuildStoreLayoutOf","aiBuildStorePagesOf","aiBuildStorePagesStillMissing","writeAiStoreLinksLayoutDraft","AI_SITE_STORE_LINKS_INPUT","AI_SITE_STORE_PAGES_NOTE","aiStoreFrameLinks","aiStorePagesToWrite","AI_SITE_STORE_PAGES_INPUT","aiSiteStorePageId","aiSiteStorePagesRefusal","runAiSiteStorePagesUnit","AI_JOB_BRIEF_MAX_CHARS","aiJobPublishesBuild","aiMergeSitePublish","aiPublishGuidedSite","AI_PLANNED_JOB_KINDS","aiJobStepRunMinimumMs","aiJobStepRunnerFor","registerAiJobStep","registerAiJobStepPasses","AI_BUILD_NO_PLAN_COPY","aiBuildUnavailableCopy","noun","AI_BUILD_PAGE_NOT_WRITTEN_COPY","AI_BUILD_MAX_PASSES","units","CREATION_JOB_KINDS","layout","form","component","email","aiBuildUnitJobKind","unit","ops","screen","creation","kind","runnerKind","get","op","aiBuildUnitJobId","job","id","item","$id","slot","aiBuildUnitJob","context","plan","unitPlan","built","ledger","outputs","labels","entry","values","label","brief","trim","reuse","create","screens","items","placedByScreens","Set","flatMap","sections","section","uses","filter","has","duplicateOf","writesTo","push","name","why","purpose","builtLayout","template","record","dataset","map","ref","title","slug","placedByCode","includes","fields","briefLines","inputs","args","originJobId","rows","Map","row","made","pages","one","layouts","entries","length","madeFor","formPage","datasets","find","toLowerCase","some","listings","eventUnits","ledgerRows","written","Boolean","planned","storePages","steps","join","slice","failed","failure","extra","status","readAiStoreSitePages","firestore","hostId","snapshot","collection","doc","select","docs","String","layoutId","aiBuildStorePagesInput","kept","own","page","unitJobId","key","sitePages","shop","replace","split","facts","shopPath","aiBuildStoreLinksOutputs","input","write","output","store","builtLayouts","proposal","links","missing","first","rest","state","storeLinks","hrefs","header","cart","footer","link","href","screenPaths","draft","versionId","uid","createdBy","aiJobId","now","resource","hostSubdomain","note","aiBuildStoreLinksToPublish","reverse","aiBuildFreeTaste","org","readHost","data","createAiJobBuildStep","deps","runnerFor","writerFor","opsFor","admissionFor","pluginAdmission","readNodes","publish","storePagesRunner","storePagesRefusal","readSitePages","writeStoreLinks","model","modelFor","ordered","starting","init","host","orgId","freeTaste","othersOpen","finish","outcome","extraPages","extraOutputs","previous","sitePublish","retry","published","already","pageIds","signal","live","unwrittenHrefs","catch","error","console","jobId","settle","spent","continue","degradation","skip","degradedBy","refusal","derived","ours","reason","message","stopped","ids","done","set","capability","degraded","notes","draftResource","writer","admission","drafts","dependencies","dep","content","draftContent","checked","check","ok","problems","act","business","about","runner","undefined","draftId","layoutLanguage","runAiJobBuildStep","aiBuildJobRunMinimumMs","AI_BUILD_ITEM_RUNNER_KINDS","campaign","workflow","function","edit","navigation","duplicate","settings","media","tracking","aiBuildFreeCreditsRefusal","read","freeCreditsLeft","credits","left","resetsOn","prompt","range","smaller","confirmed","code","onConfirmed","createAiBuildJobAdmission","ownerOf","owner","shape","creditsConfirmed","onCreditsConfirmed","Date","aiBuildJobAdmission","registerAiBuildJob","minimumMs","minimumMsFor"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,qBAAiB;AAGlD,SAASC,oBAAoB,QAAQ,2CAA0C;AAC/E,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SACEC,eAAe,EACfC,mBAAmB,EACnBC,sBAAsB,EACtBC,SAAS,EACTC,kBAAkB,EAClBC,kBAAkB,EAClBC,oBAAoB,EACpBC,oBAAoB,EACpBC,eAAe,EACfC,eAAe,EACfC,YAAY,EACZC,qBAAqB,EACrBC,sBAAsB,EACtBC,uBAAuB,EACvBC,uBAAuB,EACvBC,cAAc,EACdC,YAAY,QAIP,2BAAuB;AAC9B,SAASC,cAA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 +195,15 @@ export declare const AI_LAYOUT_SECTION_EMPTY_CODE = "layout-section-no-items";
195
195
  * that are still in the page after anything later took words out.
196
196
  */
197
197
  export declare function aiLayoutShownItems(itemIds: readonly (readonly string[])[], storedIds: Readonly<Record<string, string>>, nodes: Readonly<Record<string, unknown>>): number[];
198
+ /** The plan indices of the sections that show fewer of their planned items than they must (AGL-3660). */
199
+ export declare function aiLayoutShortItemSections(screen: Pick<AiBuildPlanScreen, 'sections'>, items: readonly number[], quotesOnly?: readonly number[]): number[];
200
+ /**
201
+ * What a page built in the layout language says about the planned sections
202
+ * it was published without (AGL-3771): each one the last answer could not
203
+ * fill, or left with only its heading once its gaps were taken out, rather
204
+ * than the page refused. `null` when every section is shown.
205
+ */
206
+ export declare function aiLayoutLeftOutNote(screen: Pick<AiBuildPlanScreen, 'sections'>, sectionIds: readonly string[], nodes: Readonly<Record<string, unknown>>): string | null;
198
207
  /**
199
208
  * The sections a page planned with repeated items — cards, steps, a list —
200
209
  * that show none, or too few, once the page is built (AGL-3660). A heading
@@ -203,7 +212,9 @@ export declare function aiLayoutShownItems(itemIds: readonly (readonly string[])
203
212
  */
204
213
  export declare function aiLayoutEmptyItemSections(screen: Pick<AiBuildPlanScreen, 'sections'>, items: readonly number[],
205
214
  /** Sections whose only items were customer quotes, which no answer may give (AGL-3676). */
206
- quotesOnly?: readonly number[]): AiDoctrineViolation[];
215
+ quotesOnly?: readonly number[],
216
+ /** Sections the page no longer shows (AGL-3771), which ask for nothing. */
217
+ emptied?: readonly number[]): AiDoctrineViolation[];
207
218
  /**
208
219
  * The check a language page answer is held to: each planned section read,
209
220
  * the page compiled, stored and checked whole. Sections that read are kept
@@ -20,7 +20,7 @@ import { aiHomeScreenIds } from "../model/ai-site-inventory.js";
20
20
  import { AI_LAYOUT_POST_ADDRESS_TOKENS, aiCompileLayoutPage } from "../layout-language/ai-layout-compiler.js";
21
21
  import { aiLayoutListingAt, aiLayoutListingsOf, aiLayoutRecordHref } from "../layout-language/ai-layout-listings.js";
22
22
  import { AI_LAYOUT_LANGUAGE_TEXT, AI_LAYOUT_PAGE_TOOL, aiReadLayoutPage } from "../layout-language/ai-layout-language.js";
23
- import { aiLayoutCopyCheck } from "../layout-language/ai-layout-gaps.js";
23
+ import { aiLayoutCopyCheck, aiLayoutWithoutSections } from "../layout-language/ai-layout-gaps.js";
24
24
  import { aiLayoutStoredTree } from "../layout-language/ai-layout-store.js";
25
25
  import { AI_GENERATION_MAX_ATTEMPTS } from "../runtime/ai-generation-bounds.js";
26
26
  import { AI_STEP_TIERS } from "../providers/catalog.js";
@@ -347,19 +347,39 @@ export const AI_JOB_PAGE_LANGUAGE_BUDGET = aiJobStepBudget({
347
347
  */ export function aiLayoutShownItems(itemIds, storedIds, nodes) {
348
348
  return itemIds.map((ids)=>ids.filter((id)=>storedIds[id] !== undefined && storedIds[id] in nodes).length);
349
349
  }
350
+ /** The plan indices of the sections that show fewer of their planned items than they must (AGL-3660). */ export function aiLayoutShortItemSections(screen, items, quotesOnly = []) {
351
+ return screen.sections.flatMap((section, index)=>{
352
+ var _items_index;
353
+ if (quotesOnly.includes(index)) return [];
354
+ const least = leastItems(section.items);
355
+ return least && ((_items_index = items[index]) != null ? _items_index : 0) < least ? [
356
+ index
357
+ ] : [];
358
+ });
359
+ }
360
+ /**
361
+ * What a page built in the layout language says about the planned sections
362
+ * it was published without (AGL-3771): each one the last answer could not
363
+ * fill, or left with only its heading once its gaps were taken out, rather
364
+ * than the page refused. `null` when every section is shown.
365
+ */ export function aiLayoutLeftOutNote(screen, sectionIds, nodes) {
366
+ const names = screen.sections.flatMap((section, index)=>index > 0 && sectionIds[index] && !(sectionIds[index] in nodes) ? [
367
+ `“${section.name}”`
368
+ ] : []);
369
+ if (!names.length) return null;
370
+ return names.length === 1 ? `Left out: the section ${names[0]}, which could not be built well enough to publish. Add it in the Besigner when you are ready.` : `Left out: the sections ${names.join(', ')}, which could not be built well enough to publish. Add them in the Besigner when you are ready.`;
371
+ }
350
372
  /**
351
373
  * The sections a page planned with repeated items — cards, steps, a list —
352
374
  * that show none, or too few, once the page is built (AGL-3660). A heading
353
375
  * and an intro over nothing is a section a visitor reads as broken, so it is
354
376
  * asked for again.
355
- */ export function aiLayoutEmptyItemSections(screen, items, /** Sections whose only items were customer quotes, which no answer may give (AGL-3676). */ quotesOnly = []) {
377
+ */ export function aiLayoutEmptyItemSections(screen, items, /** Sections whose only items were customer quotes, which no answer may give (AGL-3676). */ quotesOnly = [], /** Sections the page no longer shows (AGL-3771), which ask for nothing. */ emptied = []) {
378
+ const short = aiLayoutShortItemSections(screen, items, quotesOnly);
356
379
  return screen.sections.flatMap((section, index)=>{
357
380
  var _items_index;
358
- if (quotesOnly.includes(index)) return [];
359
- const least = leastItems(section.items);
360
- if (!least) return [];
381
+ if (!short.includes(index) || emptied.includes(index)) return [];
361
382
  const shown = (_items_index = items[index]) != null ? _items_index : 0;
362
- if (shown >= least) return [];
363
383
  return [
364
384
  {
365
385
  rule: null,
@@ -451,10 +471,12 @@ export const AI_JOB_PAGE_LANGUAGE_BUDGET = aiJobStepBudget({
451
471
  ] : []
452
472
  ]
453
473
  }, last);
454
- const { dropped } = copy;
474
+ const dropped = [
475
+ ...copy.dropped
476
+ ];
455
477
  // An attribute a rule has one answer for is settled, not asked of the model again (AGL-3660),
456
478
  // and a link sent home for nothing is sent to the form or left out (AGL-3729).
457
- const nodes = aiSettleUnrelatedScreenLinks(aiSettleMechanicalRules({
479
+ let nodes = aiSettleUnrelatedScreenLinks(aiSettleMechanicalRules({
458
480
  rootId: CANVAS_ROOT_ELEMENT_ID,
459
481
  nodes: copy.nodes
460
482
  }, 'page'), 'page', _extends({}, context, {
@@ -462,6 +484,23 @@ export const AI_JOB_PAGE_LANGUAGE_BUDGET = aiJobStepBudget({
462
484
  input.targets.pageId
463
485
  ] : []
464
486
  })).nodes;
487
+ // Each section's items as they are stored, after anything the gaps took out.
488
+ const items = aiLayoutShownItems(compiled.itemIds, stored.storedIds, nodes);
489
+ // The last answer's sections that still show none of their planned items
490
+ // are taken out rather than the whole page refused (AGL-3771): a site
491
+ // start's home refused for one such section published a site with
492
+ // nothing at its address. The page's first section heads it, and is
493
+ // never taken out.
494
+ const emptied = last ? aiLayoutShortItemSections(input.screen, items, compiled.quotesOnly).filter((index)=>index > 0 && !!input.sectionIds[index]) : [];
495
+ if (emptied.length) {
496
+ const without = aiLayoutWithoutSections(nodes, CANVAS_ROOT_ELEMENT_ID, emptied.map((index)=>({
497
+ id: input.sectionIds[index],
498
+ name: input.screen.sections[index].name,
499
+ why: `planned with ${input.screen.sections[index].items} items and showing ${items[index] || 'none'}`
500
+ })));
501
+ nodes = without.nodes;
502
+ dropped.push(...without.dropped);
503
+ }
465
504
  const report = validateAiDoctrineTree({
466
505
  rootId: CANVAS_ROOT_ELEMENT_ID,
467
506
  nodes
@@ -470,15 +509,13 @@ export const AI_JOB_PAGE_LANGUAGE_BUDGET = aiJobStepBudget({
470
509
  // The layout language draws its own picture cards (AGL-3660).
471
510
  repeatsCompiled: true
472
511
  }));
473
- // Each section's items as they are stored, after anything the gaps took out.
474
- const items = aiLayoutShownItems(compiled.itemIds, stored.storedIds, nodes);
475
512
  // A street address or opening hours the job was never given is invented
476
513
  // (rule 14, AGL-3596), the same check a layout is held to; a phone number
477
514
  // or an email the compiler already writes as its gap.
478
515
  const violations = [
479
516
  ...report.violations,
480
517
  ...copy.violations,
481
- ...aiLayoutEmptyItemSections(input.screen, items, compiled.quotesOnly),
518
+ ...aiLayoutEmptyItemSections(input.screen, items, compiled.quotesOnly, emptied),
482
519
  ...aiLayoutInventedContactViolations({
483
520
  rootId: CANVAS_ROOT_ELEMENT_ID,
484
521
  nodes: nodes