@aglyn/plugins-ai 1.0.0-beta.284 → 1.0.0-beta.287
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +17 -17
- package/src/lib/assets/site-styles/nonprofit.webp +0 -0
- package/src/lib/assets/site-styles/professional.webp +0 -0
- package/src/lib/assets/site-styles/store.webp +0 -0
- package/src/lib/assets/site-styles/trades.webp +0 -0
- package/src/lib/components/ai-theme-proposal-card.component.js +12 -3
- package/src/lib/components/ai-theme-proposal-card.component.js.map +1 -1
- package/src/lib/declarations.js +5 -2
- package/src/lib/declarations.js.map +1 -1
- package/src/lib/declarations.server.js +12 -0
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/jobs/ai-build-capabilities.d.ts +3 -1
- package/src/lib/jobs/ai-build-capabilities.js +27 -2
- package/src/lib/jobs/ai-build-capabilities.js.map +1 -1
- package/src/lib/jobs/ai-image-reads.d.ts +59 -0
- package/src/lib/jobs/ai-image-reads.js +138 -0
- package/src/lib/jobs/ai-image-reads.js.map +1 -0
- package/src/lib/jobs/ai-job-build-step.d.ts +29 -0
- package/src/lib/jobs/ai-job-build-step.js +83 -12
- package/src/lib/jobs/ai-job-build-step.js.map +1 -1
- package/src/lib/jobs/ai-job-duplicate-step.d.ts +2 -1
- package/src/lib/jobs/ai-job-duplicate-step.js +6 -6
- package/src/lib/jobs/ai-job-duplicate-step.js.map +1 -1
- package/src/lib/jobs/ai-job-import-step.d.ts +4 -2
- package/src/lib/jobs/ai-job-import-step.js +15 -11
- package/src/lib/jobs/ai-job-import-step.js.map +1 -1
- package/src/lib/jobs/ai-job-insight-step.d.ts +10 -0
- package/src/lib/jobs/ai-job-insight-step.js +23 -5
- package/src/lib/jobs/ai-job-insight-step.js.map +1 -1
- package/src/lib/jobs/ai-job-layout-language.js +2 -1
- package/src/lib/jobs/ai-job-layout-language.js.map +1 -1
- package/src/lib/jobs/ai-job-media-step.d.ts +2 -1
- package/src/lib/jobs/ai-job-media-step.js +6 -8
- package/src/lib/jobs/ai-job-media-step.js.map +1 -1
- package/src/lib/jobs/ai-job-navigation-step.d.ts +2 -1
- package/src/lib/jobs/ai-job-navigation-step.js +7 -9
- package/src/lib/jobs/ai-job-navigation-step.js.map +1 -1
- package/src/lib/jobs/ai-job-page-language.js +7 -1
- package/src/lib/jobs/ai-job-page-language.js.map +1 -1
- package/src/lib/jobs/ai-job-page-sections.js +16 -3
- package/src/lib/jobs/ai-job-page-sections.js.map +1 -1
- package/src/lib/jobs/ai-job-page-step.js +9 -1
- package/src/lib/jobs/ai-job-page-step.js.map +1 -1
- package/src/lib/jobs/ai-job-plan-step.d.ts +30 -8
- package/src/lib/jobs/ai-job-plan-step.js +78 -13
- package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
- package/src/lib/jobs/ai-job-privacy-step.d.ts +4 -2
- package/src/lib/jobs/ai-job-privacy-step.js +14 -15
- package/src/lib/jobs/ai-job-privacy-step.js.map +1 -1
- package/src/lib/jobs/ai-job-products-step.js +5 -3
- package/src/lib/jobs/ai-job-products-step.js.map +1 -1
- package/src/lib/jobs/ai-job-settings-step.d.ts +2 -1
- package/src/lib/jobs/ai-job-settings-step.js +7 -8
- package/src/lib/jobs/ai-job-settings-step.js.map +1 -1
- package/src/lib/jobs/ai-job-site-content.d.ts +34 -1
- package/src/lib/jobs/ai-job-site-content.js +67 -8
- package/src/lib/jobs/ai-job-site-content.js.map +1 -1
- package/src/lib/jobs/ai-job-site-datasets.d.ts +53 -3
- package/src/lib/jobs/ai-job-site-datasets.js +298 -30
- package/src/lib/jobs/ai-job-site-datasets.js.map +1 -1
- package/src/lib/jobs/ai-job-site-step.js +6 -3
- package/src/lib/jobs/ai-job-site-step.js.map +1 -1
- package/src/lib/jobs/ai-job-site-store-pages.js +3 -3
- package/src/lib/jobs/ai-job-site-store-pages.js.map +1 -1
- package/src/lib/jobs/ai-job-tracking-step.d.ts +2 -1
- package/src/lib/jobs/ai-job-tracking-step.js +7 -8
- package/src/lib/jobs/ai-job-tracking-step.js.map +1 -1
- package/src/lib/jobs/ai-jobs-beat.d.ts +11 -7
- package/src/lib/jobs/ai-jobs-beat.js +18 -8
- package/src/lib/jobs/ai-jobs-beat.js.map +1 -1
- package/src/lib/jobs/ai-jobs-notify.d.ts +66 -1
- package/src/lib/jobs/ai-jobs-notify.js +136 -3
- package/src/lib/jobs/ai-jobs-notify.js.map +1 -1
- package/src/lib/jobs/ai-layout-stock-photos.d.ts +59 -4
- package/src/lib/jobs/ai-layout-stock-photos.js +897 -81
- package/src/lib/jobs/ai-layout-stock-photos.js.map +1 -1
- package/src/lib/jobs/ai-product-image.d.ts +14 -0
- package/src/lib/jobs/ai-product-image.js +73 -21
- package/src/lib/jobs/ai-product-image.js.map +1 -1
- package/src/lib/jobs/ai-theme-brand-inputs.d.ts +9 -1
- package/src/lib/jobs/ai-theme-brand-inputs.js +28 -2
- package/src/lib/jobs/ai-theme-brand-inputs.js.map +1 -1
- package/src/lib/jobs/fixtures/ai-site-agl4065-datasets.d.ts +175 -0
- package/src/lib/jobs/fixtures/ai-site-agl4065-datasets.js +601 -0
- package/src/lib/jobs/fixtures/ai-site-agl4065-datasets.js.map +1 -0
- package/src/lib/jobs/fixtures/ai-site-agl4065-pages.d.ts +46 -0
- package/src/lib/jobs/fixtures/ai-site-agl4065-pages.js +2862 -0
- package/src/lib/jobs/fixtures/ai-site-agl4065-pages.js.map +1 -0
- package/src/lib/jobs/fixtures/ai-site-agl4065-plans.d.ts +74 -0
- package/src/lib/jobs/fixtures/ai-site-agl4065-plans.js +888 -0
- package/src/lib/jobs/fixtures/ai-site-agl4065-plans.js.map +1 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl4065-judge.d.ts +29 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl4065-judge.js +81 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl4065-judge.js.map +1 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl4065-recordings.d.ts +87 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl4065-recordings.js +225 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl4065-recordings.js.map +1 -0
- package/src/lib/layout-language/ai-layout-compiler.d.ts +11 -0
- package/src/lib/layout-language/ai-layout-compiler.js +194 -18
- package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
- package/src/lib/layout-language/ai-layout-copy.d.ts +37 -0
- package/src/lib/layout-language/ai-layout-copy.js +383 -3
- package/src/lib/layout-language/ai-layout-copy.js.map +1 -1
- package/src/lib/layout-language/ai-layout-design.d.ts +19 -0
- package/src/lib/layout-language/ai-layout-design.js +31 -11
- package/src/lib/layout-language/ai-layout-design.js.map +1 -1
- package/src/lib/layout-language/ai-layout-listings.d.ts +7 -1
- package/src/lib/layout-language/ai-layout-listings.js +9 -1
- package/src/lib/layout-language/ai-layout-listings.js.map +1 -1
- package/src/lib/layout-language/ai-layout-pictures.d.ts +30 -0
- package/src/lib/layout-language/ai-layout-pictures.js +131 -3
- package/src/lib/layout-language/ai-layout-pictures.js.map +1 -1
- package/src/lib/layout-language/ai-layout-storefront.d.ts +18 -4
- package/src/lib/layout-language/ai-layout-storefront.js +100 -20
- package/src/lib/layout-language/ai-layout-storefront.js.map +1 -1
- package/src/lib/model/ai-build-job.d.ts +7 -0
- package/src/lib/model/ai-build-job.js +36 -7
- package/src/lib/model/ai-build-job.js.map +1 -1
- package/src/lib/model/ai-build-plan.d.ts +28 -4
- package/src/lib/model/ai-build-plan.js +49 -9
- package/src/lib/model/ai-build-plan.js.map +1 -1
- package/src/lib/model/ai-build-progress.js +3 -1
- package/src/lib/model/ai-build-progress.js.map +1 -1
- package/src/lib/model/ai-job-notice.d.ts +8 -0
- package/src/lib/model/ai-job-notice.js +33 -0
- package/src/lib/model/ai-job-notice.js.map +1 -1
- package/src/lib/model/ai-job-plan-lines.d.ts +2 -1
- package/src/lib/model/ai-job-plan-lines.js +6 -1
- package/src/lib/model/ai-job-plan-lines.js.map +1 -1
- package/src/lib/model/ai-jobs.types.d.ts +8 -0
- package/src/lib/model/ai-jobs.types.js.map +1 -1
- package/src/lib/model/ai-permissions.d.ts +13 -0
- package/src/lib/model/ai-permissions.js +29 -1
- package/src/lib/model/ai-permissions.js.map +1 -1
- package/src/lib/model/ai-products.d.ts +18 -0
- package/src/lib/model/ai-products.js +32 -0
- package/src/lib/model/ai-products.js.map +1 -1
- package/src/lib/model/ai-site-inspiration.d.ts +3 -2
- package/src/lib/model/ai-site-inspiration.js +3 -2
- package/src/lib/model/ai-site-inspiration.js.map +1 -1
- package/src/lib/plugin.js +4 -13
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/providers/anthropic.js +9 -2
- package/src/lib/providers/anthropic.js.map +1 -1
- package/src/lib/providers/catalog.js +14 -5
- package/src/lib/providers/catalog.js.map +1 -1
- package/src/lib/providers/contract.d.ts +24 -1
- package/src/lib/providers/contract.js.map +1 -1
- package/src/lib/providers/routing.js +5 -2
- package/src/lib/providers/routing.js.map +1 -1
- package/src/lib/runtime/ai-dataset-generation.d.ts +99 -1
- package/src/lib/runtime/ai-dataset-generation.js +251 -3
- package/src/lib/runtime/ai-dataset-generation.js.map +1 -1
- package/src/lib/runtime/ai-dev-replay.d.ts +1 -0
- package/src/lib/runtime/ai-dev-replay.js +4 -2
- package/src/lib/runtime/ai-dev-replay.js.map +1 -1
- package/src/lib/runtime/ai-doctrine-validators.d.ts +47 -3
- package/src/lib/runtime/ai-doctrine-validators.js +343 -27
- package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
- package/src/lib/runtime/ai-doctrine.js +8 -2
- package/src/lib/runtime/ai-doctrine.js.map +1 -1
- package/src/lib/runtime/ai-icon-library.d.ts +27 -1
- package/src/lib/runtime/ai-icon-library.js +30 -3
- package/src/lib/runtime/ai-icon-library.js.map +1 -1
- package/src/lib/runtime/ai-products-generation.d.ts +11 -1
- package/src/lib/runtime/ai-products-generation.js +51 -4
- package/src/lib/runtime/ai-products-generation.js.map +1 -1
- package/src/lib/runtime/assist-answer-cache.d.ts +2 -0
- package/src/lib/runtime/assist-answer-cache.js +5 -2
- package/src/lib/runtime/assist-answer-cache.js.map +1 -1
- package/src/lib/server/ai-allotments.js +7 -2
- package/src/lib/server/ai-allotments.js.map +1 -1
- package/src/lib/server/ai-experiment-versions.js +5 -5
- package/src/lib/server/ai-experiment-versions.js.map +1 -1
- package/src/lib/server/ai-host-permissions-roster.d.ts +25 -0
- package/src/lib/server/ai-host-permissions-roster.js +33 -0
- package/src/lib/server/ai-host-permissions-roster.js.map +1 -0
- package/src/lib/server/ai-host-permissions.js +8 -6
- package/src/lib/server/ai-host-permissions.js.map +1 -1
- package/src/lib/server/ai-image-reads-route.d.ts +17 -0
- package/src/lib/server/ai-image-reads-route.js +106 -0
- package/src/lib/server/ai-image-reads-route.js.map +1 -0
- package/src/lib/server/ai-seo-apply.js +5 -5
- package/src/lib/server/ai-seo-apply.js.map +1 -1
- package/src/lib/server/ai-site-import-route.js +7 -4
- package/src/lib/server/ai-site-import-route.js.map +1 -1
- package/src/lib/server/assist-build.js +1 -0
- package/src/lib/server/assist-build.js.map +1 -1
- package/src/lib/server/assist-chat.d.ts +11 -7
- package/src/lib/server/assist-chat.js +185 -48
- package/src/lib/server/assist-chat.js.map +1 -1
- package/src/lib/server/assist-docs-query.d.ts +51 -0
- package/src/lib/server/assist-docs-query.js +57 -0
- package/src/lib/server/assist-docs-query.js.map +1 -0
- package/src/lib/server/assist-jobs-context.d.ts +102 -0
- package/src/lib/server/assist-jobs-context.js +227 -0
- package/src/lib/server/assist-jobs-context.js.map +1 -0
- package/src/lib/server/assist-view-context.d.ts +8 -4
- package/src/lib/server/assist-view-context.js +12 -7
- package/src/lib/server/assist-view-context.js.map +1 -1
- package/src/lib/server.js +12 -0
- package/src/lib/server.js.map +1 -1
- package/src/lib/tools/ai-dataset-tool.d.ts +11 -1
- package/src/lib/tools/ai-dataset-tool.js +24 -7
- package/src/lib/tools/ai-dataset-tool.js.map +1 -1
- package/src/lib/tools/ai-duplicate-resource-tool.js +5 -6
- package/src/lib/tools/ai-duplicate-resource-tool.js.map +1 -1
- package/src/lib/components/ai-collaborator-permissions-column.component.d.ts +0 -32
- package/src/lib/components/ai-collaborator-permissions-column.component.js +0 -132
- package/src/lib/components/ai-collaborator-permissions-column.component.js.map +0 -1
|
@@ -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 aiBuildItemArgRefs,\n aiBuildItemDelivered,\n aiBuildItemOpen,\n aiBuildNextUnit,\n aiBuildOrder,\n aiBuildItemOutputNote,\n aiBuildPlacedItemLines,\n AI_BUILD_NEEDS_INPUT_CODE,\n aiBuildPlanMissingInput,\n aiBuildPlanShapeRefusal,\n aiBuildRefName,\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 {\n AI_LAYOUT_FORM_PAGE_INPUT,\n AI_LAYOUT_LANGUAGE_INPUT,\n AI_LAYOUT_SITE_MOTION_INPUT,\n aiJobUsesLayoutLanguage,\n aiLayoutFormPageOfPlan,\n aiLayoutSiteMotionOf,\n type AiLayoutSiteMotion,\n} 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/**\n * An item's arguments without the list entries that link what this build\n * could not make (AGL-3832): a menu's `About => new:About` once the page\n * About failed. The item is built with the rest, and its note names what it\n * is without, so its own report never shows a `new:` reference.\n */\nexport function aiBuildItemArgsWithout(\n args: Readonly<Record<string, unknown>>,\n dropped: ReadonlySet<string> | undefined,\n): Record<string, unknown> {\n if (!dropped?.size) return { ...args }\n const links = (entry: unknown) => aiBuildItemArgRefs({ entry }).some((ref) => dropped.has(aiBuildRefName(ref)))\n return Object.fromEntries(\n Object.entries(args).map(([key, value]) => [key, Array.isArray(value) ? value.filter((entry) => !links(entry)) : value]),\n )\n}\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 /** The `new:` names, lowercased, of what failed and the unit is built without (`aiBuildDegradation`). */\n dropped?: ReadonlySet<string>\n /** The motion of the site the build adds to, from its stored look (`aiLayoutSiteMotionOf`); absent, none stored. */\n siteMotion?: AiLayoutSiteMotion | null\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 ...aiBuildItemArgsWithout(item?.args ?? {}, context.dropped),\n originJobId: aiOriginJobId(job),\n }\n delete inputs[AI_BUILD_PUBLISH_INPUT]\n // What a build adds to a site moves the way the site's own pages do\n // (AGL-3949): its look's motion style, drawn with the site's seed.\n if (context.siteMotion && (context.kind === 'page' || context.kind === 'layout' || context.kind === 'template')) {\n inputs[AI_LAYOUT_SITE_MOTION_INPUT] = context.siteMotion\n }\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, {\n kind,\n units,\n ledger,\n ops,\n briefLines: degradation.briefLines,\n dropped: degradation.dropped,\n siteMotion: aiLayoutSiteMotionOf(host?.['siteStyle']),\n })\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 privacy: 'privacy',\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\n // without. The plan step waits for it in `needs_input` (AGL-3978).\n const missing = aiBuildPlanMissingInput(plan, ops)\n if (missing) return { status: 400, error: missing, code: AI_BUILD_NEEDS_INPUT_CODE }\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","aiBuildItemArgRefs","aiBuildItemDelivered","aiBuildItemOpen","aiBuildNextUnit","aiBuildOrder","aiBuildItemOutputNote","aiBuildPlacedItemLines","AI_BUILD_NEEDS_INPUT_CODE","aiBuildPlanMissingInput","aiBuildPlanShapeRefusal","aiBuildRefName","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","AI_LAYOUT_SITE_MOTION_INPUT","aiJobUsesLayoutLanguage","aiLayoutFormPageOfPlan","aiLayoutSiteMotionOf","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","aiBuildItemArgsWithout","args","dropped","size","links","entry","some","ref","has","Object","fromEntries","entries","map","key","value","Array","isArray","filter","aiBuildUnitJobId","job","id","item","$id","slot","aiBuildUnitJob","context","plan","unitPlan","built","ledger","outputs","labels","values","label","brief","trim","reuse","create","screens","items","placedByScreens","Set","flatMap","sections","section","uses","duplicateOf","writesTo","push","name","why","purpose","builtLayout","template","record","dataset","title","slug","placedByCode","includes","fields","briefLines","inputs","originJobId","siteMotion","rows","Map","row","made","pages","one","layouts","length","madeFor","formPage","datasets","find","toLowerCase","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","sitePages","shop","replace","split","facts","shopPath","aiBuildStoreLinksOutputs","input","write","output","store","builtLayouts","proposal","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","privacy","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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../../../../../../../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 type { ResolvedBusinessProfile } from '@aglyn/aglyn/app-utils/business-profile'\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 AI_BUILD_THEME_OP,\n aiArticle,\n aiBuildCreationNoun,\n aiBuildCreditRange,\n aiBuildDegradation,\n aiBuildInitialLedger,\n aiBuildItemArgRefs,\n aiBuildItemDelivered,\n aiBuildItemOpen,\n aiBuildNextUnit,\n aiBuildOrder,\n aiBuildItemOutputNote,\n aiBuildPlacedItemLines,\n AI_BUILD_NEEDS_INPUT_CODE,\n aiBuildPlanMissingInput,\n aiBuildPlanShapeRefusal,\n aiBuildRefName,\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_INPUT_MAX_CHARS, 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 { readAiSiteContext } from '../runtime/site-context'\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 {\n AI_LAYOUT_FORM_PAGE_INPUT,\n AI_LAYOUT_LANGUAGE_INPUT,\n AI_LAYOUT_SITE_MOTION_INPUT,\n aiJobUsesLayoutLanguage,\n aiLayoutFormPageOfPlan,\n aiLayoutSiteMotionOf,\n type AiLayoutSiteMotion,\n} 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 // The theme operation's unit, where the plan named it as its creation (AGL-4077).\n 'theme-change': 'theme',\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/**\n * An item's arguments without the list entries that link what this build\n * could not make (AGL-3832): a menu's `About => new:About` once the page\n * About failed. The item is built with the rest, and its note names what it\n * is without, so its own report never shows a `new:` reference.\n */\nexport function aiBuildItemArgsWithout(\n args: Readonly<Record<string, unknown>>,\n dropped: ReadonlySet<string> | undefined,\n): Record<string, unknown> {\n if (!dropped?.size) return { ...args }\n const links = (entry: unknown) => aiBuildItemArgRefs({ entry }).some((ref) => dropped.has(aiBuildRefName(ref)))\n return Object.fromEntries(\n Object.entries(args).map(([key, value]) => [key, Array.isArray(value) ? value.filter((entry) => !links(entry)) : value]),\n )\n}\n\n/**\n * What a build's theme change says under its proposal (AGL-4077): the theme\n * runner proposes and never saves, so the owner applies it, or not, where\n * every theme change is made.\n */\nexport const AI_BUILD_THEME_PROPOSAL_NOTE =\n 'A proposal, in Setup → Theme. Nothing on the site changes until you apply it there and save.'\n\n/**\n * What a build's units are told about the business (AGL-4077), in the inputs\n * a site start's own units carry: what it does (`businessType`), its name and\n * who it is for. A build started from the chat carries none of them, so its\n * pages searched photos by their section names alone.\n */\nexport interface AiBuildBusinessWords {\n businessType?: string\n businessName?: string\n audience?: string\n}\n\n/** Text held to what a site start's own answer holds, cut at a word. */\nfunction clipWords(value: string | null | undefined): string {\n const text = (value ?? '').replace(/\\s+/g, ' ').trim()\n if (text.length <= AI_SITE_INPUT_MAX_CHARS) return text\n const cut = text.slice(0, AI_SITE_INPUT_MAX_CHARS + 1)\n const space = cut.lastIndexOf(' ')\n return (space > 0 ? cut.slice(0, space) : cut.slice(0, AI_SITE_INPUT_MAX_CHARS)).replace(/[\\s,;:.–—-]+$/, '')\n}\n\n/**\n * The site's business profile as those inputs (AGL-4077): what the business\n * does, else the schema.org type its settings name, as words; its name; who\n * it is for. Only what the profile says; nothing for a site with none.\n */\nexport function aiBuildBusinessWords(profile: ResolvedBusinessProfile | null | undefined): AiBuildBusinessWords {\n if (!profile) return {}\n const type = profile.businessType ? profile.businessType.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase() : ''\n const words: AiBuildBusinessWords = {\n businessType: clipWords(profile.whatYouDo?.value) || clipWords(type),\n businessName: clipWords(profile.name?.value),\n audience: clipWords(profile.audience?.value),\n }\n return Object.fromEntries(Object.entries(words).filter(([, value]) => value)) as AiBuildBusinessWords\n}\n\n/**\n * The business words a page is handed (AGL-4077): only where the build itself\n * names no business, and only what the build does not say already.\n */\nfunction aiBuildBusinessInputs(\n inputs: Readonly<Record<string, unknown>> | null | undefined,\n business: AiBuildBusinessWords | null | undefined,\n): AiBuildBusinessWords {\n if (!business || aiSiteWords(inputs).about) return {}\n const given = (key: string) => typeof inputs?.[key] === 'string' && (inputs[key] as string).trim() !== ''\n return Object.fromEntries(Object.entries(business).filter(([key]) => !given(key))) as AiBuildBusinessWords\n}\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 /** The `new:` names, lowercased, of what failed and the unit is built without (`aiBuildDegradation`). */\n dropped?: ReadonlySet<string>\n /** The motion of the site the build adds to, from its stored look (`aiLayoutSiteMotionOf`); absent, none stored. */\n siteMotion?: AiLayoutSiteMotion | null\n /** What the site's business profile says the business is (`aiBuildBusinessWords`, AGL-4077); absent, nothing read. */\n business?: AiBuildBusinessWords | null\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 const what = unit.creation.kind === 'theme-change' ? aiBuildCreationNoun(unit.creation.kind) : unit.creation.kind\n brief.push(`Build the ${what} “${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 // What the business is, from the site's profile, where the build says\n // nothing of it (AGL-4077): a page's photos are searched with them. Never\n // a layout, which would write the name where the token that reads the\n // site's own name goes, and never an item, whose inputs are its arguments.\n ...(unit.screen ? aiBuildBusinessInputs(job.inputs, context.business) : {}),\n ...aiBuildItemArgsWithout(item?.args ?? {}, context.dropped),\n originJobId: aiOriginJobId(job),\n }\n delete inputs[AI_BUILD_PUBLISH_INPUT]\n // A theme change is a change to the theme the site has (AGL-4077), never a new one.\n if (context.kind === 'theme') inputs['mode'] = 'modify'\n // What a build adds to a site moves the way the site's own pages do\n // (AGL-3949): its look's motion style, drawn with the site's seed.\n if (context.siteMotion && (context.kind === 'page' || context.kind === 'layout' || context.kind === 'template')) {\n inputs[AI_LAYOUT_SITE_MOTION_INPUT] = context.siteMotion\n }\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 // Only a planned kind builds from a plan: an item's other runners, and the theme runner, take none.\n plan: AI_PLANNED_JOB_KINDS.includes(context.kind) ? unitPlan : null,\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 /** The site's business profile, read where the build names no business (AGL-4077). */\n readSiteContext?: typeof readAiSiteContext\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 const readSiteContext = deps.readSiteContext ?? readAiSiteContext\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 // What the business is, for a page or another plugin's draft, read from\n // the site's profile where the build names none (AGL-4077): a build from\n // the chat carries no businessType, so its pages searched photos with\n // nothing of the business to go on. Fail-soft: unread, the unit is built\n // as it was.\n const business =\n job.hostId && !aiSiteWords(job.inputs).about && (unit.screen || capability.draftResource)\n ? await readSiteContext(firestore, { orgId: job.orgId, hostId: job.hostId, host })\n .then((read) => aiBuildBusinessWords(read?.profile))\n .catch((error: unknown) => {\n console.warn('ai build business profile unread', { orgId: job.orgId, jobId: job.$id, error })\n return null\n })\n : 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 || business?.businessType || 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, {\n kind,\n units,\n ledger,\n ops,\n briefLines: degradation.briefLines,\n dropped: degradation.dropped,\n siteMotion: aiLayoutSiteMotionOf(host?.['siteStyle']),\n business,\n })\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 // A theme change's proposal says where it is applied (AGL-4077).\n const theme = kind === 'theme'\n const spent = theme\n ? {\n ...aiUnitSpend(outcome),\n outputs: outcome.outputs.map((output) => (output.resource === 'theme' ? { ...output, note: AI_BUILD_THEME_PROPOSAL_NOTE } : output)),\n }\n : 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: theme ? [note, AI_BUILD_THEME_PROPOSAL_NOTE].filter(Boolean).join(' ') : 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 privacy: 'privacy',\n [AI_BUILD_THEME_OP]: 'theme',\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\n // without. The plan step waits for it in `needs_input` (AGL-3978).\n const missing = aiBuildPlanMissingInput(plan, ops)\n if (missing) return { status: 400, error: missing, code: AI_BUILD_NEEDS_INPUT_CODE }\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","AI_BUILD_THEME_OP","aiArticle","aiBuildCreationNoun","aiBuildCreditRange","aiBuildDegradation","aiBuildInitialLedger","aiBuildItemArgRefs","aiBuildItemDelivered","aiBuildItemOpen","aiBuildNextUnit","aiBuildOrder","aiBuildItemOutputNote","aiBuildPlacedItemLines","AI_BUILD_NEEDS_INPUT_CODE","aiBuildPlanMissingInput","aiBuildPlanShapeRefusal","aiBuildRefName","aiBuildSmaller","aiBuildUnits","isAiPlanNewRef","AI_SITE_INPUT_MAX_CHARS","AI_SITE_MAX_SECTIONS","AI_CREDITS_CONFIRM_CODE","aiCreditsPromptFor","aiCreditsPromptText","aiFreeCreditsNoneLeftText","aiSiteWords","readFreeAiCreditsLeft","readAiSiteContext","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","AI_LAYOUT_SITE_MOTION_INPUT","aiJobUsesLayoutLanguage","aiLayoutFormPageOfPlan","aiLayoutSiteMotionOf","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","aiBuildItemArgsWithout","args","dropped","size","links","entry","some","ref","has","Object","fromEntries","entries","map","key","value","Array","isArray","filter","AI_BUILD_THEME_PROPOSAL_NOTE","clipWords","text","replace","trim","length","cut","slice","space","lastIndexOf","aiBuildBusinessWords","profile","type","businessType","toLowerCase","words","whatYouDo","businessName","name","audience","aiBuildBusinessInputs","inputs","business","about","given","aiBuildUnitJobId","job","id","item","$id","slot","aiBuildUnitJob","context","plan","unitPlan","built","ledger","outputs","labels","values","label","brief","reuse","create","screens","items","placedByScreens","Set","flatMap","sections","section","uses","duplicateOf","writesTo","what","push","why","purpose","builtLayout","template","record","dataset","title","slug","placedByCode","includes","fields","briefLines","originJobId","siteMotion","rows","Map","row","made","pages","one","layouts","madeFor","formPage","datasets","find","listings","eventUnits","ledgerRows","written","Boolean","planned","storePages","steps","join","failed","failure","extra","status","readAiStoreSitePages","firestore","hostId","snapshot","collection","doc","select","docs","String","layoutId","aiBuildStorePagesInput","kept","own","page","unitJobId","sitePages","shop","split","facts","shopPath","aiBuildStoreLinksOutputs","input","write","output","store","builtLayouts","proposal","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","readSiteContext","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","then","read","warn","writer","admission","drafts","dependencies","dep","content","draftContent","checked","check","ok","problems","act","runner","theme","undefined","draftId","layoutLanguage","runAiJobBuildStep","aiBuildJobRunMinimumMs","AI_BUILD_ITEM_RUNNER_KINDS","campaign","workflow","function","edit","navigation","duplicate","settings","media","tracking","privacy","aiBuildFreeCreditsRefusal","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,QA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WAAWxN,QAAQ+N,gBAAgB,KAAK;gBACxCL,aAAa1N,QAAQgO,kBAAkB;gBACvCtH,GAAG,UAAEW,KAAKX,GAAG,oBAARW,KAAKX,GAAG,MAARW,wBAAgB,IAAI4G;gBACzBhB,iBAAiB5F,KAAK4F,eAAe;YACvC;YACA,IAAI/C,SAAS,OAAOA;QACtB;QACA,OAAO;IACT;AACF;AAEA,OAAO,MAAMgE,sBAAsBP,4BAA2B;AAE9D;;;CAGC,GACD,OAAO,SAASQ;IACd3S,kBAAkB,SAAS2Q,mBAAmB;QAC5CiC,WAAWpV;QACXqV,cAAcjC;IAChB;IACA3Q,wBAAwB,SAASK;IACjCnD,uBAAuB,SAASuV;AAClC"}
|
|
@@ -60,7 +60,8 @@ export declare const AI_DUPLICATE_KIND: "duplicate";
|
|
|
60
60
|
*/
|
|
61
61
|
export declare const AI_JOB_DUPLICATE_STEP_MINIMUM_MS = 5000;
|
|
62
62
|
export declare const AI_DUPLICATE_NO_SITE_COPY = "Open the site whose content should be copied.";
|
|
63
|
-
|
|
63
|
+
/** Names "Edit site content" (`site.edit`, AGL-4047), never a role. */
|
|
64
|
+
export declare const AI_DUPLICATE_ROLE_COPY: string;
|
|
64
65
|
export declare const AI_DUPLICATE_LOCKED_COPY = "This site is not accepting changes right now.";
|
|
65
66
|
export declare const AI_DUPLICATE_UNREADABLE_COPY = "The request did not name something on this site to copy.";
|
|
66
67
|
export declare const AI_DUPLICATE_NOT_YET_COPY = "Only something the site already has can be copied, not something this build is making.";
|
|
@@ -14,8 +14,9 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
14
14
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
|
-
*/ import {
|
|
18
|
-
import {
|
|
17
|
+
*/ import { holdsSiteKey } from "@aglyn/aglyn/app-utils/host-permissions";
|
|
18
|
+
import { orgPermissionLabel } from "@aglyn/aglyn/app-utils/org-permissions";
|
|
19
|
+
import { DUPLICABLE_RESOURCE_NOUNS } from "@aglyn/aglyn/app-utils/duplicate-resource";
|
|
19
20
|
import { duplicateResource, recipeFor } from "@aglyn/tenant-data-admin/server/duplicate-resource";
|
|
20
21
|
import { getLockdownVerdict } from "@aglyn/tenant-data-admin/server/lockdown";
|
|
21
22
|
import { resolveOrgIdForHost } from "@aglyn/tenant-data-admin/server/organizations";
|
|
@@ -60,7 +61,7 @@ import { registerAiJobStep } from "./ai-jobs.js";
|
|
|
60
61
|
* No model, so it fits an inline door.
|
|
61
62
|
*/ export const AI_JOB_DUPLICATE_STEP_MINIMUM_MS = 5000;
|
|
62
63
|
export const AI_DUPLICATE_NO_SITE_COPY = 'Open the site whose content should be copied.';
|
|
63
|
-
export const AI_DUPLICATE_ROLE_COPY =
|
|
64
|
+
/** Names "Edit site content" (`site.edit`, AGL-4047), never a role. */ export const AI_DUPLICATE_ROLE_COPY = `Copying on this site needs the "${orgPermissionLabel('site.edit')}" permission on this site — ask an organization admin.`;
|
|
64
65
|
export const AI_DUPLICATE_LOCKED_COPY = 'This site is not accepting changes right now.';
|
|
65
66
|
export const AI_DUPLICATE_UNREADABLE_COPY = 'The request did not name something on this site to copy.';
|
|
66
67
|
export const AI_DUPLICATE_NOT_YET_COPY = 'Only something the site already has can be copied, not something this build is making.';
|
|
@@ -129,10 +130,9 @@ export const AI_DUPLICATE_NOT_YET_COPY = 'Only something the site already has ca
|
|
|
129
130
|
};
|
|
130
131
|
}
|
|
131
132
|
/** Why this member may not copy on this site now, or `null`. */ export async function aiDuplicateAccessRefusal(input, deps = {}) {
|
|
132
|
-
var
|
|
133
|
+
var _deps_lockdown;
|
|
133
134
|
if (!input.host.exists) return 'Unknown site';
|
|
134
|
-
|
|
135
|
-
if (!hostRoleCanWrite(roles[input.uid])) return AI_DUPLICATE_ROLE_COPY;
|
|
135
|
+
if (!holdsSiteKey(input.host, input.uid, 'site.edit')) return AI_DUPLICATE_ROLE_COPY;
|
|
136
136
|
const locked = await ((_deps_lockdown = deps.lockdown) != null ? _deps_lockdown : getLockdownVerdict)({
|
|
137
137
|
staff: false,
|
|
138
138
|
uid: input.uid,
|