@aglyn/plugins-ai 1.0.0-beta.264 → 1.0.0-beta.268
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 +18 -18
- package/src/lib/assets/site-styles/beauty.webp +0 -0
- package/src/lib/assets/site-styles/blog.webp +0 -0
- package/src/lib/assets/site-styles/business.webp +0 -0
- package/src/lib/assets/site-styles/coming-soon.webp +0 -0
- package/src/lib/assets/site-styles/education.webp +0 -0
- package/src/lib/assets/site-styles/events.webp +0 -0
- package/src/lib/assets/site-styles/fitness.webp +0 -0
- package/src/lib/assets/site-styles/landing.webp +0 -0
- package/src/lib/assets/site-styles/music.webp +0 -0
- package/src/lib/assets/site-styles/nonprofit.webp +0 -0
- package/src/lib/assets/site-styles/personal.webp +0 -0
- package/src/lib/assets/site-styles/photography.webp +0 -0
- package/src/lib/assets/site-styles/portfolio.webp +0 -0
- package/src/lib/assets/site-styles/professional.webp +0 -0
- package/src/lib/assets/site-styles/realestate.webp +0 -0
- package/src/lib/assets/site-styles/restaurant.webp +0 -0
- package/src/lib/assets/site-styles/store.webp +0 -0
- package/src/lib/assets/site-styles/studio.webp +0 -0
- package/src/lib/assets/site-styles/trades.webp +0 -0
- package/src/lib/assets/site-styles/wellness.webp +0 -0
- package/src/lib/assets/site-styles/yoga.webp +0 -0
- package/src/lib/components/ai-job-site.d.ts +8 -1
- package/src/lib/components/ai-job-site.js +7 -0
- package/src/lib/components/ai-job-site.js.map +1 -1
- package/src/lib/components/ai-site-build-page.component.js +37 -0
- package/src/lib/components/ai-site-build-page.component.js.map +1 -1
- package/src/lib/components/ai-site-start-card.component.d.ts +12 -0
- package/src/lib/components/ai-site-start-card.component.js +279 -240
- package/src/lib/components/ai-site-start-card.component.js.map +1 -1
- package/src/lib/components/ai-site-start-steps.component.d.ts +114 -0
- package/src/lib/components/ai-site-start-steps.component.js +480 -0
- package/src/lib/components/ai-site-start-steps.component.js.map +1 -0
- package/src/lib/components/ai-site-start-tracking.d.ts +122 -0
- package/src/lib/components/ai-site-start-tracking.js +296 -0
- package/src/lib/components/ai-site-start-tracking.js.map +1 -0
- package/src/lib/components/ai-site-style-previews.d.ts +26 -0
- package/src/lib/components/ai-site-style-previews.js +115 -0
- package/src/lib/components/ai-site-style-previews.js.map +1 -0
- package/src/lib/components/assist-jobs-drawer.component.js +24 -2
- package/src/lib/components/assist-jobs-drawer.component.js.map +1 -1
- package/src/lib/insights/ai-insight-digest.d.ts +9 -0
- package/src/lib/insights/ai-insight-digest.js +35 -11
- package/src/lib/insights/ai-insight-digest.js.map +1 -1
- package/src/lib/jobs/ai-empty-site-sweep.d.ts +154 -0
- package/src/lib/jobs/ai-empty-site-sweep.js +346 -0
- package/src/lib/jobs/ai-empty-site-sweep.js.map +1 -0
- package/src/lib/jobs/ai-job-page-language.d.ts +9 -0
- package/src/lib/jobs/ai-job-page-language.js +20 -2
- package/src/lib/jobs/ai-job-page-language.js.map +1 -1
- package/src/lib/jobs/ai-job-plan-step.d.ts +43 -8
- package/src/lib/jobs/ai-job-plan-step.js +99 -18
- package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
- package/src/lib/jobs/ai-job-site-datasets.d.ts +82 -1
- package/src/lib/jobs/ai-job-site-datasets.js +276 -14
- package/src/lib/jobs/ai-job-site-datasets.js.map +1 -1
- package/src/lib/jobs/ai-jobs-beat.d.ts +11 -3
- package/src/lib/jobs/ai-jobs-beat.js +23 -6
- package/src/lib/jobs/ai-jobs-beat.js.map +1 -1
- package/src/lib/jobs/ai-jobs.js +46 -7
- package/src/lib/jobs/ai-jobs.js.map +1 -1
- package/src/lib/jobs/ai-layout-stock-photos.d.ts +143 -10
- package/src/lib/jobs/ai-layout-stock-photos.js +1046 -102
- package/src/lib/jobs/ai-layout-stock-photos.js.map +1 -1
- package/src/lib/jobs/fixtures/ai-site-foreign-datasets-recording.d.ts +58 -0
- package/src/lib/jobs/fixtures/ai-site-foreign-datasets-recording.js +678 -0
- package/src/lib/jobs/fixtures/ai-site-foreign-datasets-recording.js.map +1 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl3856-beta265-recordings.d.ts +33 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl3856-beta265-recordings.js +270 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl3856-beta265-recordings.js.map +1 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl3856-people-recordings.d.ts +33 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl3856-people-recordings.js +277 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl3856-people-recordings.js.map +1 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl3923-recordings.d.ts +35 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl3923-recordings.js +379 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-agl3923-recordings.js.map +1 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-brightvale-recordings.d.ts +31 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-brightvale-recordings.js +208 -0
- package/src/lib/jobs/fixtures/ai-stock-photo-brightvale-recordings.js.map +1 -0
- package/src/lib/layout-language/ai-layout-compiler.js +49 -12
- package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
- package/src/lib/layout-language/ai-layout-design.d.ts +6 -3
- package/src/lib/layout-language/ai-layout-design.js +19 -13
- package/src/lib/layout-language/ai-layout-design.js.map +1 -1
- package/src/lib/layout-language/ai-layout-listings.d.ts +48 -0
- package/src/lib/layout-language/ai-layout-listings.js +91 -5
- package/src/lib/layout-language/ai-layout-listings.js.map +1 -1
- package/src/lib/layout-language/ai-layout-pictures.d.ts +15 -0
- package/src/lib/layout-language/ai-layout-pictures.js +6 -2
- package/src/lib/layout-language/ai-layout-pictures.js.map +1 -1
- package/src/lib/model/ai-jobs.types.d.ts +20 -0
- package/src/lib/model/ai-jobs.types.js.map +1 -1
- package/src/lib/model/ai-site-home-arcs.d.ts +75 -0
- package/src/lib/model/ai-site-home-arcs.js +741 -0
- package/src/lib/model/ai-site-home-arcs.js.map +1 -0
- package/src/lib/model/ai-site-inventory.d.ts +18 -0
- package/src/lib/model/ai-site-inventory.js.map +1 -1
- package/src/lib/model/ai-site-job.d.ts +9 -6
- package/src/lib/model/ai-site-job.js +8 -5
- package/src/lib/model/ai-site-job.js.map +1 -1
- package/src/lib/model/ai-site-kinds.js +24 -24
- package/src/lib/model/ai-site-kinds.js.map +1 -1
- package/src/lib/model/ai-site-start-handoff.d.ts +49 -0
- package/src/lib/model/ai-site-start-handoff.js +88 -0
- package/src/lib/model/ai-site-start-handoff.js.map +1 -0
- package/src/lib/model/ai-site-start-steps.d.ts +67 -0
- package/src/lib/model/ai-site-start-steps.js +127 -0
- package/src/lib/model/ai-site-start-steps.js.map +1 -0
- package/src/lib/model/ai-site-start.js +4 -1
- package/src/lib/model/ai-site-start.js.map +1 -1
- package/src/lib/runtime/ai-doctrine-validators.d.ts +32 -0
- package/src/lib/runtime/ai-doctrine-validators.js +119 -2
- package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
- package/src/lib/runtime/ai-doctrine.d.ts +6 -1
- package/src/lib/runtime/ai-doctrine.js +9 -5
- package/src/lib/runtime/ai-doctrine.js.map +1 -1
- package/src/lib/runtime/ai-palette.generated.js +5 -2
- package/src/lib/runtime/ai-palette.generated.js.map +1 -1
- package/src/lib/runtime/site-inventory.js +6 -0
- package/src/lib/runtime/site-inventory.js.map +1 -1
- package/src/lib/server/ai-insight-digest-route.js +2 -2
- package/src/lib/server/ai-insight-digest-route.js.map +1 -1
- package/src/lib/usage/assist-free-taste.js +3 -0
- package/src/lib/usage/assist-free-taste.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-site-datasets.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 { checkDatasetQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { pluginResourceDraftWriter } from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { isAiPlanNewRef, type AiBuildPlanCreate, type AiBuildPlanScreen } from '../model/ai-build-plan'\nimport type { AiJob, AiJobOutput, AiJobPlan } from '../model/ai-jobs.types'\nimport type { AiPlanCapabilities } from '../model/ai-plan-capabilities'\nimport { AI_SITE_DATASETS_MAX } from '../model/ai-site-job'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { aiModelForStep } from '../providers/routing'\nimport {\n AI_DATASET_MAX_TOKENS,\n AI_DATASET_STEP,\n aiDatasetDraftContent,\n generateAiDataset,\n} from '../runtime/ai-dataset-generation'\nimport {\n aiLayoutListingId,\n aiLayoutRecordBaseOf,\n aiLayoutRecordsPlacements,\n type AiLayoutListing,\n type AiLayoutListingField,\n type AiLayoutListingScreen,\n} from '../layout-language/ai-layout-listings'\nimport {\n aiLayoutStarterPhotos,\n type AiLayoutPicturePhoto,\n type AiLayoutPictureSlot,\n} from '../layout-language/ai-layout-pictures'\nimport { aiSiteWords } from '../model/ai-site-job'\nimport type { AiJobAdmissionContext } from './ai-job-admission'\nimport { aiOriginJobId } from './ai-job-draft-ids'\nimport { aiSiteProductPhotoSrc } from './ai-job-site-content'\nimport { aiLayoutStockPhotoSource, aiStockPhotoWordsOf } from './ai-layout-stock-photos'\nimport { AI_DATASET_DRAFT_RESOURCE } from './ai-build-unit-outcome'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiGenerationSpent, aiUnspentOutcome } from './ai-job-generation'\nimport { aiPluginDraftAdmissionRefusal } from './ai-job-plugin-drafts'\nimport type { AiJobStepContext, AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\n\n/**\n * A SITE START'S DATASETS (AGL-3616): \"Aglyn AI can also use/create datasets\n * too for whatever it needs\" (Zach, 2026-10-10).\n *\n * A site whose content is a list of like things — a restaurant's menu, a\n * studio's team, a contractor's services, a photographer's portfolio, an\n * events list, its questions and answers — keeps it as a DATASET, the way the\n * docs teach a person to: the owner edits one record and every page listing\n * it follows. On a workspace that may create datasets, the site plan creates\n * one for such content (`create`, kind `dataset`) and names it in the `uses`\n * of each section that lists it. The scaffold then builds each dataset as a\n * unit of its own, after the layout and before the form (which may write\n * its submissions to one) and the pages:\n *\n * - DESIGNED by the `submit_dataset` generation (`ai-dataset-generation.ts`):\n * the planned fields typed, at most a few more, and 3 to 12 records seeded\n * from the brief. Nothing anybody did not say: no review, testimonial,\n * rating, quote or person's name, no price the brief does not state.\n * - WRITTEN by the data plugin's `dataset` writer — this plugin never names\n * the datasets collection — with every rule the console's datasets route\n * has: the member's role and `data.manage`, `release_data_store`,\n * `dataStore` (Starter and up), `datasetsPerOrg` counted inside the create,\n * `recordsPerDataset` and the storage band.\n * - PICTURED where the plan lists it the way a gallery is listed (Zach,\n * 2026-10-10: a ceramic artist's \"Selected work\" came back as text-only\n * cards, where it had been an image-led gallery): a portfolio's pieces, a\n * team, a menu, classes and events, and services or offerings whose\n * section says it shows them in pictures (`aiSiteDatasetPicturesOf`). Such\n * a dataset gets an Image field, and each record a stock photo of its own\n * name in the site's craft, copied into the site's library — never one the\n * job already placed, else a starter photo — searched in code, so it\n * costs no credits (`aiSiteDatasetRecordPhotos`).\n * - LISTED by the pages built after it: each section naming it repeats over\n * the dataset (`aiSiteDatasetListings`, a `records` listing the layout\n * compiler draws, its card led by the record's photo where it has one),\n * and a page the plan made its record template binds its fields by id,\n * its photo the record's, and keeps the address field the writer added.\n *\n * Where datasets cannot be created — the Free taste, Starter's two used up,\n * the data store not released — the plan is told so and creates none, so its\n * sections write the items out. A dataset unit that fails or is refused\n * leaves the pages that list it built without it (they say so), and its\n * record page is not built.\n */\n\n/** The most datasets one site start creates. */\nexport { AI_SITE_DATASETS_MAX } from '../model/ai-site-job'\n\n/** The resource the data plugin's writer is registered under. */\nexport const AI_SITE_DATASET_RESOURCE = AI_DATASET_DRAFT_RESOURCE\n\n/** What the site's plugin list calls the plugin, for \"Turn on Data for this site\". */\nconst DATA_PLUGIN_LABEL = 'Data'\n\n/** The input a dataset unit's own job carries what it needs in. */\nexport const AI_SITE_DATASET_INPUT = 'siteDataset'\n\n/** What a dataset unit's job is told beside its creation. */\nexport interface AiSiteDatasetInput {\n /** The sections that list it, by page: \"Menu › Our dishes (12 items)\". */\n shownIn: string[]\n /** Whether a page of the plan is its record template. */\n recordPages: boolean\n /**\n * The form of the plan that writes its submissions to it (AGL-3616), by\n * name, with that form's planned fields; absent where no form does.\n */\n forForm?: { name: string; fields: string[] }\n /**\n * Whether its records carry a photo, and of what (AGL-3616): `things` for a\n * portfolio's pieces, a menu, classes; `people` for a team. Absent for a\n * list a visitor reads rather than looks at: questions, steps, hours.\n */\n pictures?: AiSiteDatasetPictures\n}\n\n/** What a dataset's records are pictured as: things or people. */\nexport type AiSiteDatasetPictures = 'things' | 'people'\n\n/** A list of questions, voices or plain facts: read, never pictured. */\nconst READ_ONLY_LIST =\n /\\b(faqs?|questions?|q ?& ?a|answers?|testimonials?|reviews?|quotes?|voices|hours|opening|steps?|process|policies|policy|terms|stats?|numbers|figures|milestones|timeline|values|benefits|reasons|features|requirements|checklist|ingredients|donations?|needs|partners|sponsors|supporters|roles|positions|jobs|openings)\\b/i\n/** A list of people: its photos are of the business's people. */\nconst PEOPLE_LIST =\n /\\b(team|staff|people|crew|instructors?|teachers?|tutors?|stylists?|barbers?|therapists?|coaches?|trainers?|chefs?|doctors?|dentists?|hygienists?|practitioners?|artists?|musicians?|performers?|speakers?|founders?|members?)\\b/i\n/** A list a visitor looks at before reading: pictured wherever it is listed. */\nconst PICTURED_LIST =\n /\\b(portfolio|pieces?|works?|projects?|gallery|galleries|collections?|series|menus?|dishes|plates|drinks|cocktails|wines?|beers?|coffees?|pastries|cakes|products?|items|events?|classes|class|workshops?|courses?|retreats?|tours?|trips?|adventures?|experiences?|rooms?|suites?|cabins?|properties|listings|homes|venues?|spaces?|recipes?|artworks?|paintings?|prints?|photos?|photographs?|designs?|commissions?|builds?|vehicles?|animals?|pets?|plants?|flowers?|bouquets?|arrangements?|case studies)\\b/i\n/** A section that says it shows its items in pictures: a gallery, a grid of photos, tiles. */\nconst PICTURED_SECTION =\n /\\b(gallery|galleries|grid|images?|photos?|photographs?|pictures?|lightbox|portfolio|showcase|tiles?|visuals?|lookbook|carousel|slideshow|mosaic|thumbnails?)\\b/i\n\n/**\n * Whether a dataset's records carry a photo, read off the plan (AGL-3616):\n * its name and the names of the sections that list it. Questions, voices and\n * plain facts never; people as people; a list a visitor looks at — pieces,\n * dishes, classes, events, rooms — always; any other list (services,\n * offerings, programs) only where a section that lists it says it shows them\n * in pictures, or names one of those. A dataset no page lists is not\n * pictured. Pure.\n */\nexport function aiSiteDatasetPicturesOf(\n dataset: Pick<AiBuildPlanCreate, 'name'>,\n sections: readonly string[],\n): AiSiteDatasetPictures | null {\n if (!sections.length) return null\n const own = dataset.name\n if (READ_ONLY_LIST.test(own)) return null\n if (PEOPLE_LIST.test(own)) return 'people'\n if (PICTURED_LIST.test(own)) return 'things'\n if (sections.some((section) => READ_ONLY_LIST.test(section) && !PICTURED_SECTION.test(section))) return null\n if (sections.some((section) => PEOPLE_LIST.test(section))) return 'people'\n if (sections.some((section) => PICTURED_LIST.test(section) || PICTURED_SECTION.test(section))) return 'things'\n return null\n}\n\n/** What a dataset row says when its design could not be written: our failure, refunded. */\nexport const AI_SITE_DATASET_NOT_WRITTEN_COPY = 'This dataset could not be added this time.'\n\n/** The note a written dataset carries on the job's page. */\nexport function aiSiteDatasetNote(records: number): string {\n return `${records} ${records === 1 ? 'record' : 'records'} to start, in Data. Edit them there and every page that lists them follows.`\n}\n\n/** The note a record template's row adds: the binding is the member's to save (rule 13). */\nexport const AI_SITE_RECORD_PAGE_NOTE =\n 'A page per record is drafted, not live: open Page Properties → Record pages to save it.'\n\n/** ASSUMED: what one dataset pass reads and writes beside its generation: the site, the writer's reads and its transaction. */\nexport const AI_SITE_DATASET_WRITES_MS = 2_000\n\n/** One dataset's pass: its generation and re-ask at its ceiling, and its writes. */\nexport const AI_SITE_DATASET_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS[AI_DATASET_STEP],\n maxTokens: AI_DATASET_MAX_TOKENS,\n lookups: 0,\n ownReadsMs: AI_SITE_DATASET_WRITES_MS,\n})\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/** The plan's reference to a dataset as a section names it: `new:<name>`, compared lowercased. */\nfunction namesDataset(ref: string, name: string): boolean {\n return isAiPlanNewRef(ref) && ref.slice(ref.indexOf(':') + 1).trim().toLowerCase() === name.trim().toLowerCase()\n}\n\n/** The plan's datasets, in plan order, at most the most a start creates. */\nexport function aiSitePlanDatasets(plan: Pick<AiJobPlan, 'create'>): AiBuildPlanCreate[] {\n return plan.create.filter((entry) => entry.kind === 'dataset').slice(0, AI_SITE_DATASETS_MAX)\n}\n\n/** Where the plan lists a dataset, in words its design reads, whether a page is its record template, and the form that writes to it. */\nexport function aiSiteDatasetInputOf(\n dataset: Pick<AiBuildPlanCreate, 'name'>,\n screens: readonly AiBuildPlanScreen[],\n create: readonly AiBuildPlanCreate[] = [],\n): AiSiteDatasetInput {\n const shownIn: string[] = []\n const sectionNames: string[] = []\n for (const screen of screens) {\n for (const section of screen.sections) {\n if (!section.uses.some((ref) => namesDataset(ref, dataset.name))) continue\n shownIn.push(`${screen.title} › ${section.name}${section.items ? ` (${section.items} items)` : ''}`)\n sectionNames.push(section.name)\n }\n }\n const recordPages = screens.some((screen) => !!screen.record && namesDataset(screen.record.dataset, dataset.name))\n const form = create.find((entry) => entry.kind === 'form' && !!entry.writesTo && namesDataset(entry.writesTo, dataset.name))\n // A form's dataset holds its submissions: nobody's photo.\n const pictures = form ? null : aiSiteDatasetPicturesOf(dataset, sectionNames)\n return {\n shownIn: shownIn.slice(0, 8),\n recordPages,\n ...(form ? { forForm: { name: form.name, fields: form.fields.slice(0, AI_SITE_FORM_DATASET_FIELDS_MAX) } } : {}),\n ...(pictures ? { pictures } : {}),\n }\n}\n\n/** Whether a plan screen is the record template of a dataset the plan creates, and which. */\nexport function aiSiteRecordTemplateOf(screen: Pick<AiBuildPlanScreen, 'record'>): string | null {\n const ref = screen.record?.dataset\n return ref && isAiPlanNewRef(ref) ? ref.slice(ref.indexOf(':') + 1).trim() : null\n}\n\nfunction datasetInputOf(job: Pick<AiJob, 'inputs'>): AiSiteDatasetInput {\n const raw = (job.inputs?.[AI_SITE_DATASET_INPUT] ?? {}) as Partial<AiSiteDatasetInput>\n const form = raw.forForm && typeof raw.forForm === 'object' ? raw.forForm : null\n return {\n shownIn: Array.isArray(raw.shownIn) ? raw.shownIn.map(str).filter(Boolean).slice(0, 8) : [],\n recordPages: raw.recordPages === true,\n ...(form && str(form.name)\n ? {\n forForm: {\n name: str(form.name),\n fields: Array.isArray(form.fields) ? form.fields.map(str).filter(Boolean).slice(0, AI_SITE_FORM_DATASET_FIELDS_MAX) : [],\n },\n }\n : {}),\n ...(raw.pictures === 'things' || raw.pictures === 'people' ? { pictures: raw.pictures } : {}),\n }\n}\n\n/** The most fields a form's dataset is designed with: the data plugin writer's own ceiling is higher. */\nexport const AI_SITE_FORM_DATASET_FIELDS_MAX = 12\n\n/** The field types a planned `Name:type` may name, as the data plugin's writer takes them. */\nconst FORM_DATASET_FIELD_TYPES = ['text', 'number', 'integer', 'boolean', 'list'] as const\n\n/** A planned field as a person reads it: `fullName` and `full_name` are \"Full name\", `fechaDeÚltimaVisita` \"Fecha de última visita\". */\nexport function aiSiteDatasetFieldName(planned: string): string {\n const words = planned\n .replace(/([\\p{Ll}\\p{N}])(\\p{Lu})/gu, '$1 $2')\n .replace(/[_-]+/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n return words ? words.charAt(0).toUpperCase() + words.slice(1).toLowerCase() : ''\n}\n\n/**\n * A dataset a form writes to, as the data plugin's writer takes it\n * (AGL-3616): designed with no model, since its records are the\n * submissions. Its fields are its planned ones — or, where the plan gave it\n * none, the form's — each a person's words for it, text unless the plan\n * typed it as `Name:type`, never required, so a submission that leaves one\n * blank is still a record. It starts with no records. Pure.\n */\nexport function aiSiteFormDatasetContent(\n name: string,\n planned: readonly string[],\n form: { fields: readonly string[] },\n): Record<string, unknown> {\n const specs = (planned.length ? planned : form.fields).slice(0, AI_SITE_FORM_DATASET_FIELDS_MAX)\n const seen = new Set<string>()\n const fields: Array<{ name: string; type: string }> = []\n for (const spec of specs) {\n const at = spec.lastIndexOf(':')\n const typed = at > 0 ? spec.slice(at + 1).trim().toLowerCase() : ''\n const type = (FORM_DATASET_FIELD_TYPES as readonly string[]).includes(typed) ? typed : 'text'\n const fieldName = aiSiteDatasetFieldName(type === typed ? spec.slice(0, at) : spec).slice(0, 60)\n if (!fieldName || seen.has(fieldName.toLowerCase())) continue\n seen.add(fieldName.toLowerCase())\n fields.push({ name: fieldName, type })\n }\n return { name, fields, records: [] }\n}\n\n/** The note a form's dataset carries on the job's page. */\nexport function aiSiteFormDatasetNote(form: string): string {\n return `Empty to start: each submission of the form “${form}” is added here, in Data.`\n}\n\nconst limitReview = (message: string) => ({ reason: 'limit' as const, message, findings: [] })\n\n/** The wall clock a dataset's photos may take inside its pass: the 20 seconds a page's pictures had (AGL-3660). */\nexport const AI_SITE_DATASET_PHOTOS_BUDGET_MS = 20_000\n\n/** The field a pictured dataset's photo is kept in, where the plan gave it none. */\nexport const AI_SITE_DATASET_IMAGE_FIELD = 'Image'\n\n/**\n * The field a pictured dataset keeps what each record's photo shows in\n * (AGL-3856), which its card's and its page's Image take as their alt text:\n * a record's title is what it is called, never what its photo shows.\n */\nexport const AI_SITE_DATASET_IMAGE_ALT_FIELD = 'Image description'\n\n/** A planned field that already names a record's photo. */\nconst IMAGE_FIELD_NAME =\n /^(?:main |cover |hero |featured? )?(?:image|photo|picture|photograph|thumbnail|headshot|portrait|cover)s?$/i\n\n/** One record's photo: the address its Image shows, and the library asset placed, which no page shows again. */\nexport interface AiSiteDatasetRecordPhoto {\n /** The media library's CDN path, or a starter's site path; `null` for none. */\n src: string | null\n /** The `media:` reference of the stock photo placed, or `null` for a starter. */\n placed: string | null\n /** What the photo shows, in its own words (AGL-3856); `null` for none. */\n alt?: string | null\n}\n\n/**\n * A photo for each record of a pictured dataset (AGL-3616), in order: a stock\n * photo of the record's own name, in the site's craft (\"ceramic speckled\n * serving bowl\"), copied into the site's library, where the deployment has a\n * stock library — never twice in the dataset nor one another part of the job\n * placed, inside {@link AI_SITE_DATASET_PHOTOS_BUDGET_MS} — else a starter\n * photo, as a page's empty picture takes one. A team is searched as the\n * business's people. The photo is kept as the asset's CDN path, the form a\n * product keeps (`aiSiteProductPhotoSrc`), so a replace in the library still\n * reaches it. No AI model is asked, so no credits; never throws.\n */\nexport async function aiSiteDatasetRecordPhotos(input: {\n job: Pick<AiJob, '$id' | 'hostId' | 'createdBy' | 'inputs' | 'brief' | 'plan'>\n /** The dataset, as the plan named it. */\n name: string\n /** Each record's name, by position. */\n names: readonly string[]\n pictures: AiSiteDatasetPictures\n signal?: AbortSignal\n stockPhotos?: typeof aiLayoutStockPhotoSource\n}): Promise<AiSiteDatasetRecordPhoto[]> {\n const { job } = input\n if (!input.names.length || !job.hostId) return input.names.map(() => ({ src: null, placed: null }))\n const people = input.pictures === 'people'\n const slots: AiLayoutPictureSlot[] = input.names.map((name, index) => ({\n imageId: `record${index}`,\n frameId: null,\n iconId: null,\n alt: name.trim() || input.name,\n // The record card's own shape: a team's portraits stand, pieces sit wide.\n aspect: people ? 4 / 5 : 4 / 3,\n sectionIndex: 0,\n role: people ? ('about' as const) : ('gallery' as const),\n // A record's name is a search's words, never what its photo shows (AGL-3856).\n standIn: true,\n }))\n const seed = `${job.$id}:records`\n let found: ReadonlyArray<AiLayoutPicturePhoto | null> = []\n try {\n const source = (input.stockPhotos ?? aiLayoutStockPhotoSource)(\n {\n hostId: job.hostId,\n uid: job.createdBy,\n seed,\n business: aiSiteWords(job.inputs).about || job.brief,\n ...aiStockPhotoWordsOf(job),\n sectionNames: [input.name],\n jobId: aiOriginJobId(job),\n // Each record may try its name, its object and the site's world.\n searches: slots.length * 3,\n ...(input.signal ? { signal: input.signal } : {}),\n },\n { budgetMs: AI_SITE_DATASET_PHOTOS_BUDGET_MS },\n )\n if (source) found = await source(slots)\n } catch (error) {\n console.warn('ai site dataset: the stock photos failed; starter photos fill them', { error: String(error) })\n }\n const starters = aiLayoutStarterPhotos(slots, seed)\n const hostId = job.hostId\n return slots.map((_slot, index) => {\n const stock = aiSiteProductPhotoSrc(found[index]?.src, hostId)\n if (stock) return { src: stock, placed: found[index]?.src ?? null, alt: found[index]?.alt?.trim() || null }\n return { src: aiSiteProductPhotoSrc(starters[index]?.src, hostId), placed: null, alt: starters[index]?.alt?.trim() || null }\n })\n}\n\n/**\n * A designed dataset's content with its records' photos (AGL-3616): the\n * planned field that names a photo (\"Image\", \"Photo\") becomes the data\n * plugin's `image` field, else one called \"Image\" is added after the others,\n * and each record holds its photo there; a record with none holds nothing.\n * Pure.\n */\nexport function aiSiteDatasetContentWithPhotos(\n content: Record<string, unknown>,\n photos: ReadonlyArray<string | null>,\n /** What each record's photo shows (AGL-3856), kept in {@link AI_SITE_DATASET_IMAGE_ALT_FIELD}; none adds no field. */\n alts: ReadonlyArray<string | null> = [],\n): Record<string, unknown> {\n const fields = (Array.isArray(content['fields']) ? content['fields'] : []) as Array<{ name: string; type?: string }>\n const named = fields.find((field) => IMAGE_FIELD_NAME.test(str(field.name)))\n const fieldName = named ? named.name : AI_SITE_DATASET_IMAGE_FIELD\n const withImage = named\n ? fields.map((field) => (field === named ? { ...field, type: 'image' } : field))\n : [...fields, { name: AI_SITE_DATASET_IMAGE_FIELD, type: 'image' }]\n const described = alts.some((alt, index) => Boolean(alt && photos[index]))\n const altName = AI_SITE_DATASET_IMAGE_ALT_FIELD\n const nextFields =\n described && !withImage.some((field) => str(field.name).toLowerCase() === altName.toLowerCase())\n ? [...withImage, { name: altName, type: 'text' }]\n : withImage\n const records = (Array.isArray(content['records']) ? content['records'] : []) as Array<Record<string, unknown>>\n return {\n ...content,\n fields: nextFields,\n records: records.map((record, index) => {\n const next = { ...record }\n delete next[fieldName]\n const photo = photos[index]\n const alt = photo && described ? alts[index] : null\n return photo ? { ...next, [fieldName]: photo, ...(alt ? { [altName]: alt } : {}) } : next\n }),\n }\n}\n\nexport interface AiSiteDatasetRunnerDeps {\n generate?: typeof generateAiDataset\n writerFor?: typeof pluginResourceDraftWriter\n /** Where a pictured dataset's photos come from; the stock library, else the starters, otherwise. */\n photos?: typeof aiSiteDatasetRecordPhotos\n}\n\n/** The fields and record names a written dataset reports, as its output's proposal keeps them. */\ninterface AiSiteDatasetProposal {\n fields: AiLayoutListingField[]\n /** Each record's name: its first field's value. */\n recordNames: string[]\n addressField: string | null\n /** The field each record's photo is in, where it has one (AGL-3616). */\n imageField?: string | null\n /** The library photos its records show (`media:` references), which no page places again. */\n photos?: string[]\n /**\n * The fields most of its first records leave empty, by id (AGL-3616): a\n * tour's venues not yet known. A card never binds one — it would print\n * nothing on most records — so its listing leaves them out.\n */\n sparseFields?: string[]\n}\n\n/**\n * The fields of a designed dataset that its records leave empty on most of\n * them — every record, or more than half — by the id the data plugin gave\n * each (AGL-3616). Its first field is the record's name and is never one. The\n * live low-tide-hollow start (beta.239) seeded its tour dates with no venue,\n * rightly inventing none, and its cards bound the venue as their eyebrow.\n */\nexport function aiDatasetSparseFields(\n dataset: { fields: ReadonlyArray<{ name: string }>; records: ReadonlyArray<ReadonlyArray<string | undefined>> },\n written: readonly AiLayoutListingField[],\n): string[] {\n if (!dataset.records.length) return []\n const idOf = (name: string, column: number) =>\n written.find((field) => field.name.trim().toLowerCase() === name.trim().toLowerCase())?.id ?? written[column]?.id ?? null\n return dataset.fields.flatMap((field, column) => {\n if (column === 0) return []\n const filled = dataset.records.filter((values) => (values[column] ?? '').trim()).length\n const id = idOf(field.name, column)\n return id && filled * 2 <= dataset.records.length ? [id] : []\n })\n}\n\nfunction proposalOf(output: Pick<AiJobOutput, 'proposal'>): AiSiteDatasetProposal {\n const raw = (output.proposal ?? {}) as Partial<AiSiteDatasetProposal>\n return {\n fields: Array.isArray(raw.fields)\n ? raw.fields.filter((field) => field && typeof field.id === 'string' && field.id).map((field) => ({ id: field.id, name: str(field.name) || field.id, type: str(field.type) || 'text' }))\n : [],\n recordNames: Array.isArray(raw.recordNames) ? raw.recordNames.map(str).filter(Boolean).slice(0, 12) : [],\n addressField: str(raw.addressField) || null,\n imageField: str(raw.imageField) || null,\n photos: Array.isArray(raw.photos) ? raw.photos.map(str).filter((src) => src.startsWith('media:')).slice(0, 24) : [],\n sparseFields: Array.isArray(raw.sparseFields) ? raw.sparseFields.map(str).filter(Boolean) : [],\n }\n}\n\n/**\n * The dataset unit's runner, on the job the scaffold derived for it: the one\n * creation its plan carries, designed by the model and written by the data\n * plugin, under the creation's own id. A pass repeated after its write finds\n * the dataset the writer wrote and reports it again, spending nothing.\n */\nexport function createAiSiteDatasetRunner(deps: AiSiteDatasetRunnerDeps = {}): AiJobStepRunner {\n const generate = deps.generate ?? generateAiDataset\n const writerFor = deps.writerFor ?? pluginResourceDraftWriter\n const photosFor = deps.photos ?? aiSiteDatasetRecordPhotos\n return async (context): Promise<AiJobStepOutcome> => {\n const { job, firestore, signal } = context\n const model = context.modelFor?.(AI_DATASET_STEP) ?? aiModelForStep(AI_DATASET_STEP)\n const creation = (job.plan as AiJobPlan | null)?.create?.find((entry) => entry.kind === 'dataset')\n const keeper = writerFor(AI_SITE_DATASET_RESOURCE)\n if (!job.hostId || !creation) return { ...aiUnspentOutcome(model), failure: 'Open the site before adding its data.' }\n if (!keeper) return { ...aiUnspentOutcome(model), failure: 'Datasets are not available on this site.' }\n const host = await firestore.collection('hosts').doc(job.hostId).get()\n const hostSubdomain = str(host.get('subdomain')) || null\n const output = (id: string, name: string, proposal: AiSiteDatasetProposal, records: number): AiJobOutput => ({\n resource: 'draft',\n draftResource: AI_SITE_DATASET_RESOURCE,\n id,\n hostId: job.hostId ?? null,\n hostSubdomain,\n label: name,\n note: aiSiteDatasetNote(records),\n proposal: proposal as unknown as Record<string, unknown>,\n })\n const input = datasetInputOf(job)\n // Asked again under the same id: the dataset already written.\n const written = await keeper.writer.read({ hostId: job.hostId, id: job.$id })\n if (written) {\n const facts = written.facts as { fields?: AiLayoutListingField[]; addressField?: string | null; imageField?: string | null }\n const again = output(\n written.id,\n written.name || creation.name,\n { fields: facts.fields ?? [], recordNames: [], addressField: facts.addressField ?? null, imageField: facts.imageField ?? null },\n 0,\n )\n return aiUnspentOutcome(model, {\n outputs: [input.forForm ? { ...again, note: aiSiteFormDatasetNote(input.forForm.name) } : again],\n })\n }\n // A form's dataset (AGL-3616): its records are the submissions, so it is\n // designed from the plan with no model, and starts empty.\n if (input.forForm) {\n const content = aiSiteFormDatasetContent(creation.name, creation.fields, input.forForm)\n const checked = keeper.writer.check(content, { hostId: job.hostId })\n if (checked.ok === false) {\n console.error('ai site dataset: the dataset writer refused a form dataset we made', { orgId: job.orgId, jobId: job.$id, problems: checked.problems })\n return { ...aiUnspentOutcome(model), failure: AI_SITE_DATASET_NOT_WRITTEN_COPY }\n }\n const result = await keeper.writer.write({\n orgId: job.orgId,\n hostId: job.hostId,\n uid: job.createdBy,\n org: (context.org ?? null) as Readonly<Record<string, unknown>> | null,\n now: context.now,\n id: job.$id,\n name: creation.name,\n content,\n })\n if (result.ok === false) {\n if (result.status === 400) return { ...aiUnspentOutcome(model), failure: AI_SITE_DATASET_NOT_WRITTEN_COPY }\n return { ...aiUnspentOutcome(model), review: limitReview(result.error) }\n }\n const facts = result.facts as { fields?: AiLayoutListingField[]; addressField?: string | null }\n return aiUnspentOutcome(model, {\n outputs: [\n {\n ...output(result.id, result.name, { fields: facts.fields ?? [], recordNames: [], addressField: null }, 0),\n note: aiSiteFormDatasetNote(input.forForm.name),\n },\n ],\n })\n }\n const generation = await generate({\n brief: job.brief,\n merchantWords: job.brief,\n name: creation.name,\n why: creation.why,\n fields: creation.fields,\n shownIn: input.shownIn,\n recordPages: input.recordPages,\n model,\n maxTokens: AI_SITE_DATASET_BUDGET.maxTokens(model),\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(generation)\n if (generation.status === 'refused') return { ...spent, refused: true }\n if (generation.status === 'needs_input') return { ...spent, failure: generation.message }\n const designed = aiDatasetDraftContent(creation.name, generation.value, { recordPages: input.recordPages })\n // A list a visitor looks at keeps its records' photos (AGL-3616): searched\n // in code, never asked of the model, so they cost no credits.\n const photos = input.pictures\n ? await photosFor({\n job,\n name: creation.name,\n names: generation.value.records.map((values) => values[0] ?? ''),\n pictures: input.pictures,\n ...(signal ? { signal } : {}),\n }).catch(() => [] as AiSiteDatasetRecordPhoto[])\n : []\n const content = input.pictures\n ? aiSiteDatasetContentWithPhotos(\n designed,\n generation.value.records.map((_values, index) => photos[index]?.src ?? null),\n generation.value.records.map((_values, index) => photos[index]?.alt ?? null),\n )\n : designed\n // The data plugin's own rules, before anything is written: content we\n // made that its model refuses is our failure, refunded.\n const checked = keeper.writer.check(content, { hostId: job.hostId })\n if (checked.ok === false) {\n console.error('ai site dataset: the dataset writer refused a dataset we made', { orgId: job.orgId, jobId: job.$id, problems: checked.problems })\n return { ...spent, failure: AI_SITE_DATASET_NOT_WRITTEN_COPY }\n }\n const result = await keeper.writer.write({\n orgId: job.orgId,\n hostId: job.hostId,\n uid: job.createdBy,\n org: (context.org ?? null) as Readonly<Record<string, unknown>> | null,\n now: context.now,\n id: job.$id,\n name: creation.name,\n content,\n })\n if (result.ok === false) {\n if (result.status === 400) return { ...spent, failure: AI_SITE_DATASET_NOT_WRITTEN_COPY }\n // The allowance, the role, the plan or the flag: the workspace's to change.\n return { ...spent, review: limitReview(result.error) }\n }\n const facts = result.facts as {\n fields?: AiLayoutListingField[]\n records?: number\n addressField?: string | null\n imageField?: string | null\n }\n const placed = photos.flatMap((photo) => (photo.placed ? [photo.placed] : []))\n const proposal: AiSiteDatasetProposal = {\n fields: facts.fields ?? [],\n recordNames: generation.value.records.map((values) => values[0] ?? '').filter(Boolean).slice(0, 12),\n addressField: facts.addressField ?? null,\n ...(facts.imageField ? { imageField: facts.imageField } : {}),\n ...(placed.length ? { photos: placed } : {}),\n sparseFields: aiDatasetSparseFields(generation.value, facts.fields ?? []),\n }\n return { ...spent, outputs: [output(result.id, result.name, proposal, facts.records ?? generation.value.records.length)] }\n }\n}\n\nexport const runAiSiteDatasetUnit = createAiSiteDatasetRunner()\n\n/**\n * Whether a dataset may be created for this member on this site, asked before\n * its first pass so a refusal spends nothing; `null` admits. The data plugin\n * must run here (on for the workspace and the site, past its release flag),\n * and its writer says whether this member may make one now: the role, the\n * plan, the flag, the allowance.\n */\nexport async function aiSiteDatasetRefusal(\n context: Pick<AiJobStepContext, 'firestore' | 'org' | 'now'> & { job: Pick<AiJob, 'orgId' | 'hostId' | 'createdBy'> },\n deps: { admission?: typeof aiPluginDraftAdmissionRefusal; writerFor?: (resource: string) => ReturnType<typeof pluginResourceDraftWriter> } = {},\n): Promise<string | null> {\n const { job } = context\n if (!job.hostId) return 'Open the site first.'\n const writerFor = deps.writerFor ?? pluginResourceDraftWriter\n const admission: AiJobAdmissionContext = {\n firestore: context.firestore,\n orgId: job.orgId,\n hostId: job.hostId,\n inputs: {},\n org: context.org ?? null,\n uid: job.createdBy,\n }\n const refused = await (deps.admission ?? aiPluginDraftAdmissionRefusal)(admission, {\n kind: 'site',\n drafts: [{ resource: AI_SITE_DATASET_RESOURCE, label: DATA_PLUGIN_LABEL }],\n writerFor: (resource) => writerFor(resource)?.writer ?? null,\n ownerFor: (resource) => writerFor(resource)?.pluginId ?? null,\n now: context.now,\n })\n return refused?.error ?? null\n}\n\n/**\n * A site plan's dataset capability on this workspace (AGL-3616): where the\n * workspace's plan includes datasets, whether the data plugin runs here and\n * this member may create one now, and how many a start may make. A clause the\n * plan's turn completes is the reason where it may not.\n */\nexport async function aiSitePlanDatasetCapability(\n capabilities: AiPlanCapabilities,\n context: Parameters<typeof aiSiteDatasetRefusal>[0],\n deps: Parameters<typeof aiSiteDatasetRefusal>[1] = {},\n): Promise<AiPlanCapabilities> {\n if (!capabilities.create.dataset.allowed) return capabilities\n const refusal = await aiSiteDatasetRefusal(context, deps).catch((error: unknown) => {\n console.error('ai site plan: the dataset admission failed', { orgId: context.job.orgId, error })\n return 'datasets could not be checked just now'\n })\n const left = Math.min(AI_SITE_DATASETS_MAX, checkDatasetQuota(context.org as never, 0).limit)\n const dataset = refusal\n ? { allowed: false, left: 0, reason: `datasets cannot be created here: ${refusal.replace(/\\.$/, '')}` }\n : { allowed: true, left, reason: null }\n return { ...capabilities, create: { ...capabilities.create, dataset } }\n}\n\n/**\n * A `records` listing for each dataset that was made and that a section of the\n * plan names (AGL-3616). Its fields, where none are given, are read off the\n * site's inventory when the page is designed (`aiLayoutListingsWithDatasets`).\n */\nexport function aiDatasetListingsOf(\n datasets: ReadonlyArray<{\n id: string\n name: string\n records?: string[]\n fields?: AiLayoutListingField[]\n imageField?: string | null\n /** The record's page-address field, where the writer added one (AGL-3727). */\n addressField?: string | null\n }>,\n screens: readonly AiLayoutListingScreen[],\n): AiLayoutListing[] {\n return datasets.flatMap((dataset) => {\n const placements = aiLayoutRecordsPlacements(dataset, screens)\n if (!placements.length) return []\n // Each card links its record's own page where the plan makes one (AGL-3727).\n const recordBase = aiLayoutRecordBaseOf(dataset, screens)\n return [\n {\n id: aiLayoutListingId('records', dataset.id),\n kind: 'records' as const,\n name: dataset.name,\n records: dataset.records ?? [],\n datasetId: dataset.id,\n ...(dataset.fields?.length ? { fields: dataset.fields } : {}),\n // Its card leads with the record's photo (AGL-3616).\n ...(dataset.imageField ? { imageField: dataset.imageField } : {}),\n // The address is read off the site's inventory where the build does not know it yet.\n ...(recordBase ? { recordBase, ...(dataset.addressField ? { addressField: dataset.addressField } : {}) } : {}),\n placements,\n },\n ]\n })\n}\n\n/**\n * A `records` listing for each dataset the workspace already keeps that a\n * site start's plan reuses and a section names (AGL-3771), as a build lists\n * the ones it reuses (AGL-3747). A second site in a workspace reuses the\n * first one's menu: its plan names the dataset by id, the start listed only\n * the datasets it made, and the page was asked to \"place\" a dataset no block\n * can draw — the home's \"Del menú\" section was refused for showing none of\n * its six items, and the Menú page published with no menu. A dataset one of\n * the plan's forms writes into holds the site's submissions, and is never\n * listed on a page.\n */\nexport function aiSiteReusedDatasetListings(input: {\n plan: Pick<AiJobPlan, 'reuse' | 'create' | 'labels'>\n screens: readonly AiLayoutListingScreen[]\n /** The listings the start already has, whose datasets are not listed twice. */\n listed: ReadonlyArray<Pick<AiLayoutListing, 'datasetId'>>\n}): AiLayoutListing[] {\n const submissions = new Set(\n input.plan.create.flatMap((entry) => (entry.kind === 'form' && entry.writesTo && !isAiPlanNewRef(entry.writesTo) ? [entry.writesTo] : [])),\n )\n const listed = new Set(input.listed.map((listing) => listing.datasetId).filter(Boolean))\n const datasets = input.plan.reuse\n .filter((entry) => entry.kind === 'dataset' && !submissions.has(entry.id) && !listed.has(entry.id))\n .map((entry) => ({ id: entry.id, name: input.plan.labels?.[entry.id] || entry.id }))\n return aiDatasetListingsOf(datasets, input.screens)\n}\n\n/**\n * The site's datasets a layout or a page unit is handed (AGL-3616), each a\n * `records` listing with the sections of the plan's pages that name it, once\n * its unit wrote it. A dataset not yet written, or one that failed, lists\n * nowhere: the pages built without it write the items out.\n */\nexport function aiSiteDatasetListings(input: {\n outputs: readonly AiJobOutput[]\n datasets: ReadonlyArray<Pick<AiBuildPlanCreate, 'name'>>\n screens: readonly AiLayoutListingScreen[]\n /** The ids each dataset's unit delivered, by plan name lowercased. */\n delivered: ReadonlyMap<string, string>\n}): AiLayoutListing[] {\n const made = input.datasets.flatMap((dataset) => {\n const id = input.delivered.get(dataset.name.trim().toLowerCase())\n const output = id\n ? input.outputs.find((entry) => entry.resource === 'draft' && entry.draftResource === AI_SITE_DATASET_RESOURCE && entry.id === id)\n : undefined\n if (!id || !output) return []\n const proposal = proposalOf(output)\n return [\n {\n id,\n // Placed by the name the plan's sections gave it.\n name: dataset.name,\n records: proposal.recordNames,\n // The address field is the record page's, never a card's words; the\n // photo is the card's picture, never its words; a field most records\n // leave empty is no card's either (AGL-3616).\n fields: proposal.fields.filter(\n (field, index) =>\n field.id !== proposal.addressField &&\n field.id !== proposal.imageField &&\n (index === 0 || !proposal.sparseFields?.includes(field.id)),\n ),\n imageField: proposal.imageField ?? null,\n addressField: proposal.addressField,\n },\n ]\n })\n return aiDatasetListingsOf(made, input.screens)\n}\n\n/** The library photos the site's datasets' records show (AGL-3616), which a page does not place again. */\nexport function aiSiteDatasetPlacedPhotos(outputs: readonly AiJobOutput[]): string[] {\n return [\n ...new Set(\n outputs\n .filter((output) => output.resource === 'draft' && output.draftResource === AI_SITE_DATASET_RESOURCE)\n .flatMap((output) => proposalOf(output).photos ?? []),\n ),\n ]\n}\n\n/** What a page is told about the datasets built before it. */\nexport function aiSiteDatasetBriefLines(outputs: readonly AiJobOutput[]): string[] {\n const datasets = outputs.filter((output) => output.resource === 'draft' && output.draftResource === AI_SITE_DATASET_RESOURCE)\n return datasets.flatMap((output) => {\n const names = proposalOf(output).recordNames\n return names.length\n ? [`This site's dataset “${output.label}” holds: ${names.map((name) => `“${name}”`).join(', ')}. Where a page names one, name it as written; never name one that is not in this list.`]\n : []\n })\n}\n"],"names":["checkDatasetQuota","pluginResourceDraftWriter","isAiPlanNewRef","AI_SITE_DATASETS_MAX","AI_STEP_TIERS","aiModelForStep","AI_DATASET_MAX_TOKENS","AI_DATASET_STEP","aiDatasetDraftContent","generateAiDataset","aiLayoutListingId","aiLayoutRecordBaseOf","aiLayoutRecordsPlacements","aiLayoutStarterPhotos","aiSiteWords","aiOriginJobId","aiSiteProductPhotoSrc","aiLayoutStockPhotoSource","aiStockPhotoWordsOf","AI_DATASET_DRAFT_RESOURCE","aiJobStepBudget","aiGenerationSpent","aiUnspentOutcome","aiPluginDraftAdmissionRefusal","AI_SITE_DATASET_RESOURCE","DATA_PLUGIN_LABEL","AI_SITE_DATASET_INPUT","READ_ONLY_LIST","PEOPLE_LIST","PICTURED_LIST","PICTURED_SECTION","aiSiteDatasetPicturesOf","dataset","sections","length","own","name","test","some","section","AI_SITE_DATASET_NOT_WRITTEN_COPY","aiSiteDatasetNote","records","AI_SITE_RECORD_PAGE_NOTE","AI_SITE_DATASET_WRITES_MS","AI_SITE_DATASET_BUDGET","tier","maxTokens","lookups","ownReadsMs","str","value","trim","namesDataset","ref","slice","indexOf","toLowerCase","aiSitePlanDatasets","plan","create","filter","entry","kind","aiSiteDatasetInputOf","screens","shownIn","sectionNames","screen","uses","push","title","items","recordPages","record","form","find","writesTo","pictures","forForm","fields","AI_SITE_FORM_DATASET_FIELDS_MAX","aiSiteRecordTemplateOf","datasetInputOf","job","raw","inputs","Array","isArray","map","Boolean","FORM_DATASET_FIELD_TYPES","aiSiteDatasetFieldName","planned","words","replace","charAt","toUpperCase","aiSiteFormDatasetContent","specs","seen","Set","spec","at","lastIndexOf","typed","type","includes","fieldName","has","add","aiSiteFormDatasetNote","limitReview","message","reason","findings","AI_SITE_DATASET_PHOTOS_BUDGET_MS","AI_SITE_DATASET_IMAGE_FIELD","AI_SITE_DATASET_IMAGE_ALT_FIELD","IMAGE_FIELD_NAME","aiSiteDatasetRecordPhotos","input","names","hostId","src","placed","people","slots","index","imageId","frameId","iconId","alt","aspect","sectionIndex","role","standIn","seed","$id","found","source","stockPhotos","uid","createdBy","business","about","brief","jobId","searches","signal","budgetMs","error","console","warn","String","starters","_slot","stock","aiSiteDatasetContentWithPhotos","content","photos","alts","named","field","withImage","described","altName","nextFields","next","photo","aiDatasetSparseFields","written","idOf","column","id","flatMap","filled","values","proposalOf","output","proposal","recordNames","addressField","imageField","startsWith","sparseFields","createAiSiteDatasetRunner","deps","generate","writerFor","photosFor","context","facts","firestore","model","modelFor","creation","keeper","failure","host","collection","doc","get","hostSubdomain","resource","draftResource","label","note","writer","read","again","outputs","checked","check","ok","orgId","problems","result","write","org","now","status","review","generation","merchantWords","why","spent","refused","designed","catch","_values","runAiSiteDatasetUnit","aiSiteDatasetRefusal","admission","drafts","ownerFor","pluginId","aiSitePlanDatasetCapability","capabilities","allowed","refusal","left","Math","min","limit","aiDatasetListingsOf","datasets","placements","recordBase","datasetId","aiSiteReusedDatasetListings","submissions","listed","listing","reuse","labels","aiSiteDatasetListings","made","delivered","undefined","aiSiteDatasetPlacedPhotos","aiSiteDatasetBriefLines","join"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,2CAA0C;AAC5E,SAASC,yBAAyB,QAAQ,qDAAoD;AAC9F,SAASC,cAAc,QAAwD,4BAAwB;AAGvG,SAASC,oBAAoB,QAAQ,0BAAsB;AAC3D,SAASC,aAAa,QAAQ,0BAAsB;AACpD,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SACEC,qBAAqB,EACrBC,eAAe,EACfC,qBAAqB,EACrBC,iBAAiB,QACZ,sCAAkC;AACzC,SACEC,iBAAiB,EACjBC,oBAAoB,EACpBC,yBAAyB,QAIpB,2CAAuC;AAC9C,SACEC,qBAAqB,QAGhB,2CAAuC;AAC9C,SAASC,WAAW,QAAQ,0BAAsB;AAElD,SAASC,aAAa,QAAQ,wBAAoB;AAClD,SAASC,qBAAqB,QAAQ,2BAAuB;AAC7D,SAASC,wBAAwB,EAAEC,mBAAmB,QAAQ,8BAA0B;AACxF,SAASC,yBAAyB,QAAQ,6BAAyB;AACnE,SAASC,eAAe,QAAQ,qBAAiB;AACjD,SAASC,iBAAiB,EAAEC,gBAAgB,QAAQ,yBAAqB;AACzE,SAASC,6BAA6B,QAAQ,4BAAwB;AAGtE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CC,GAED,8CAA8C,GAC9C,S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AAM,YAAzBkB,qBAA6B,EAAE;;KAEzD;AACH;AAEA,4DAA4D,GAC5D,OAAO,SAASmF,wBAAwBlD,OAA+B;IACrE,MAAMmC,WAAWnC,QAAQtJ,MAAM,CAAC,CAACsH,SAAWA,OAAOyB,QAAQ,KAAK,WAAWzB,OAAO0B,aAAa,KAAKrL;IACpG,OAAO8N,SAASvE,OAAO,CAAC,CAACI;QACvB,MAAMzD,QAAQwD,WAAWC,QAAQE,WAAW;QAC5C,OAAO3D,MAAMxF,MAAM,GACf;YAAC,CAAC,qBAAqB,EAAEiJ,OAAO2B,KAAK,CAAC,SAAS,EAAEpF,MAAMjC,GAAG,CAAC,CAACrD,OAAS,CAAC,CAAC,EAAEA,KAAK,CAAC,CAAC,EAAEkO,IAAI,CAAC,MAAM,sFAAsF,CAAC;SAAC,GACrL,EAAE;IACR;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-site-datasets.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 { checkDatasetQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { pluginResourceDraftWriter } from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { pluginRecordIndex } from '@aglyn/aglyn/plugin-manager/plugin-record-index'\nimport {\n AI_BUILD_PLAN_LIMITS,\n AI_PLAN_NEW_REF_PREFIX,\n isAiPlanNewRef,\n type AiBuildPlan,\n type AiBuildPlanCreate,\n type AiBuildPlanScreen,\n} from '../model/ai-build-plan'\nimport type { AiInventoryDataset, AiSiteInventory } from '../model/ai-site-inventory'\nimport { AI_TYPED_LIST_MIN_ITEMS } from '../runtime/ai-doctrine-validators'\nimport type { AiJob, AiJobOutput, AiJobPlan } from '../model/ai-jobs.types'\nimport type { AiPlanCapabilities } from '../model/ai-plan-capabilities'\nimport { AI_SITE_DATASETS_MAX } from '../model/ai-site-job'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { aiModelForStep } from '../providers/routing'\nimport {\n AI_DATASET_MAX_TOKENS,\n AI_DATASET_STEP,\n aiDatasetDraftContent,\n generateAiDataset,\n} from '../runtime/ai-dataset-generation'\nimport {\n aiLayoutListingId,\n aiLayoutRecordBaseOf,\n aiLayoutRecordsPlacements,\n type AiLayoutListing,\n type AiLayoutListingField,\n type AiLayoutListingScreen,\n} from '../layout-language/ai-layout-listings'\nimport {\n aiLayoutStarterPhotos,\n type AiLayoutPicturePhoto,\n type AiLayoutPictureSlot,\n} from '../layout-language/ai-layout-pictures'\nimport { aiSiteWords } from '../model/ai-site-job'\nimport type { AiJobAdmissionContext } from './ai-job-admission'\nimport { aiOriginJobId } from './ai-job-draft-ids'\nimport { aiSiteProductPhotoSrc } from './ai-job-site-content'\nimport { aiLayoutStockPhotoSource, aiStockPhotoWordsOf } from './ai-layout-stock-photos'\nimport { AI_DATASET_DRAFT_RESOURCE } from './ai-build-unit-outcome'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiGenerationSpent, aiUnspentOutcome } from './ai-job-generation'\nimport { aiPluginDraftAdmissionRefusal } from './ai-job-plugin-drafts'\nimport type { AiJobStepContext, AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\n\n/**\n * A SITE START'S DATASETS (AGL-3616): \"Aglyn AI can also use/create datasets\n * too for whatever it needs\" (Zach, 2026-10-10).\n *\n * A site whose content is a list of like things — a restaurant's menu, a\n * studio's team, a contractor's services, a photographer's portfolio, an\n * events list, its questions and answers — keeps it as a DATASET, the way the\n * docs teach a person to: the owner edits one record and every page listing\n * it follows. On a workspace that may create datasets, the site plan creates\n * one for such content (`create`, kind `dataset`) and names it in the `uses`\n * of each section that lists it. The scaffold then builds each dataset as a\n * unit of its own, after the layout and before the form (which may write\n * its submissions to one) and the pages:\n *\n * - DESIGNED by the `submit_dataset` generation (`ai-dataset-generation.ts`):\n * the planned fields typed, at most a few more, and 3 to 12 records seeded\n * from the brief. Nothing anybody did not say: no review, testimonial,\n * rating, quote or person's name, no price the brief does not state.\n * - WRITTEN by the data plugin's `dataset` writer — this plugin never names\n * the datasets collection — with every rule the console's datasets route\n * has: the member's role and `data.manage`, `release_data_store`,\n * `dataStore` (Starter and up), `datasetsPerOrg` counted inside the create,\n * `recordsPerDataset` and the storage band.\n * - PICTURED where the plan lists it the way a gallery is listed (Zach,\n * 2026-10-10: a ceramic artist's \"Selected work\" came back as text-only\n * cards, where it had been an image-led gallery): a portfolio's pieces, a\n * team, a menu, classes and events, and services or offerings whose\n * section says it shows them in pictures (`aiSiteDatasetPicturesOf`). Such\n * a dataset gets an Image field, and each record a stock photo of its own\n * name in the site's craft, copied into the site's library — never one the\n * job already placed, else a starter photo — searched in code, so it\n * costs no credits (`aiSiteDatasetRecordPhotos`).\n * - LISTED by the pages built after it: each section naming it repeats over\n * the dataset (`aiSiteDatasetListings`, a `records` listing the layout\n * compiler draws, its card led by the record's photo where it has one),\n * and a page the plan made its record template binds its fields by id,\n * its photo the record's, and keeps the address field the writer added.\n *\n * Where datasets cannot be created — the Free taste, Starter's two used up,\n * the data store not released — the plan is told so and creates none, so its\n * sections write the items out. A dataset unit that fails or is refused\n * leaves the pages that list it built without it (they say so), and its\n * record page is not built.\n */\n\n/** The most datasets one site start creates. */\nexport { AI_SITE_DATASETS_MAX } from '../model/ai-site-job'\n\n/** The resource the data plugin's writer is registered under. */\nexport const AI_SITE_DATASET_RESOURCE = AI_DATASET_DRAFT_RESOURCE\n\n/** What the site's plugin list calls the plugin, for \"Turn on Data for this site\". */\nconst DATA_PLUGIN_LABEL = 'Data'\n\n/** The input a dataset unit's own job carries what it needs in. */\nexport const AI_SITE_DATASET_INPUT = 'siteDataset'\n\n/** What a dataset unit's job is told beside its creation. */\nexport interface AiSiteDatasetInput {\n /** The sections that list it, by page: \"Menu › Our dishes (12 items)\". */\n shownIn: string[]\n /** Whether a page of the plan is its record template. */\n recordPages: boolean\n /**\n * The form of the plan that writes its submissions to it (AGL-3616), by\n * name, with that form's planned fields; absent where no form does.\n */\n forForm?: { name: string; fields: string[] }\n /**\n * Whether its records carry a photo, and of what (AGL-3616): `things` for a\n * portfolio's pieces, a menu, classes; `people` for a team. Absent for a\n * list a visitor reads rather than looks at: questions, steps, hours.\n */\n pictures?: AiSiteDatasetPictures\n}\n\n/** What a dataset's records are pictured as: things or people. */\nexport type AiSiteDatasetPictures = 'things' | 'people'\n\n/** A list of questions, voices or plain facts: read, never pictured. */\nconst READ_ONLY_LIST =\n /\\b(faqs?|questions?|q ?& ?a|answers?|testimonials?|reviews?|quotes?|voices|hours|opening|steps?|process|policies|policy|terms|stats?|numbers|figures|milestones|timeline|values|benefits|reasons|features|requirements|checklist|ingredients|donations?|needs|partners|sponsors|supporters|roles|positions|jobs|openings)\\b/i\n/** A list of people: its photos are of the business's people. */\nconst PEOPLE_LIST =\n /\\b(team|staff|people|crew|instructors?|teachers?|tutors?|stylists?|barbers?|therapists?|coaches?|trainers?|chefs?|doctors?|dentists?|hygienists?|practitioners?|artists?|musicians?|performers?|speakers?|founders?|members?)\\b/i\n/** A list a visitor looks at before reading: pictured wherever it is listed. */\nconst PICTURED_LIST =\n /\\b(portfolio|pieces?|works?|projects?|gallery|galleries|collections?|series|menus?|dishes|plates|drinks|cocktails|wines?|beers?|coffees?|pastries|cakes|products?|items|events?|classes|class|workshops?|courses?|retreats?|tours?|trips?|adventures?|experiences?|rooms?|suites?|cabins?|properties|listings|homes|venues?|spaces?|recipes?|artworks?|paintings?|prints?|photos?|photographs?|designs?|commissions?|builds?|vehicles?|animals?|pets?|plants?|flowers?|bouquets?|arrangements?|case studies)\\b/i\n/** A section that says it shows its items in pictures: a gallery, a grid of photos, tiles. */\nconst PICTURED_SECTION =\n /\\b(gallery|galleries|grid|images?|photos?|photographs?|pictures?|lightbox|portfolio|showcase|tiles?|visuals?|lookbook|carousel|slideshow|mosaic|thumbnails?)\\b/i\n\n/**\n * Whether a dataset's records carry a photo, read off the plan (AGL-3616):\n * its name and the names of the sections that list it. Questions, voices and\n * plain facts never; people as people; a list a visitor looks at — pieces,\n * dishes, classes, events, rooms — always; any other list (services,\n * offerings, programs) only where a section that lists it says it shows them\n * in pictures, or names one of those. A dataset no page lists is not\n * pictured. Pure.\n */\nexport function aiSiteDatasetPicturesOf(\n dataset: Pick<AiBuildPlanCreate, 'name'>,\n sections: readonly string[],\n): AiSiteDatasetPictures | null {\n if (!sections.length) return null\n const own = dataset.name\n if (READ_ONLY_LIST.test(own)) return null\n if (PEOPLE_LIST.test(own)) return 'people'\n if (PICTURED_LIST.test(own)) return 'things'\n if (sections.some((section) => READ_ONLY_LIST.test(section) && !PICTURED_SECTION.test(section))) return null\n if (sections.some((section) => PEOPLE_LIST.test(section))) return 'people'\n if (sections.some((section) => PICTURED_LIST.test(section) || PICTURED_SECTION.test(section))) return 'things'\n return null\n}\n\n/** What a dataset row says when its design could not be written: our failure, refunded. */\nexport const AI_SITE_DATASET_NOT_WRITTEN_COPY = 'This dataset could not be added this time.'\n\n/** The note a written dataset carries on the job's page. */\nexport function aiSiteDatasetNote(records: number): string {\n return `${records} ${records === 1 ? 'record' : 'records'} to start, in Data. Edit them there and every page that lists them follows.`\n}\n\n/** The note a record template's row adds: the binding is the member's to save (rule 13). */\nexport const AI_SITE_RECORD_PAGE_NOTE =\n 'A page per record is drafted, not live: open Page Properties → Record pages to save it.'\n\n/** ASSUMED: what one dataset pass reads and writes beside its generation: the site, the writer's reads and its transaction. */\nexport const AI_SITE_DATASET_WRITES_MS = 2_000\n\n/** One dataset's pass: its generation and re-ask at its ceiling, and its writes. */\nexport const AI_SITE_DATASET_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS[AI_DATASET_STEP],\n maxTokens: AI_DATASET_MAX_TOKENS,\n lookups: 0,\n ownReadsMs: AI_SITE_DATASET_WRITES_MS,\n})\n\nconst str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/** The plan's reference to a dataset as a section names it: `new:<name>`, compared lowercased. */\nfunction namesDataset(ref: string, name: string): boolean {\n return isAiPlanNewRef(ref) && ref.slice(ref.indexOf(':') + 1).trim().toLowerCase() === name.trim().toLowerCase()\n}\n\n/** The plan's datasets, in plan order, at most the most a start creates. */\nexport function aiSitePlanDatasets(plan: Pick<AiJobPlan, 'create'>): AiBuildPlanCreate[] {\n return plan.create.filter((entry) => entry.kind === 'dataset').slice(0, AI_SITE_DATASETS_MAX)\n}\n\n/** Where the plan lists a dataset, in words its design reads, whether a page is its record template, and the form that writes to it. */\nexport function aiSiteDatasetInputOf(\n dataset: Pick<AiBuildPlanCreate, 'name'>,\n screens: readonly AiBuildPlanScreen[],\n create: readonly AiBuildPlanCreate[] = [],\n): AiSiteDatasetInput {\n const shownIn: string[] = []\n const sectionNames: string[] = []\n for (const screen of screens) {\n for (const section of screen.sections) {\n if (!section.uses.some((ref) => namesDataset(ref, dataset.name))) continue\n shownIn.push(`${screen.title} › ${section.name}${section.items ? ` (${section.items} items)` : ''}`)\n sectionNames.push(section.name)\n }\n }\n const recordPages = screens.some((screen) => !!screen.record && namesDataset(screen.record.dataset, dataset.name))\n const form = create.find((entry) => entry.kind === 'form' && !!entry.writesTo && namesDataset(entry.writesTo, dataset.name))\n // A form's dataset holds its submissions: nobody's photo.\n const pictures = form ? null : aiSiteDatasetPicturesOf(dataset, sectionNames)\n return {\n shownIn: shownIn.slice(0, 8),\n recordPages,\n ...(form ? { forForm: { name: form.name, fields: form.fields.slice(0, AI_SITE_FORM_DATASET_FIELDS_MAX) } } : {}),\n ...(pictures ? { pictures } : {}),\n }\n}\n\n/** Whether a plan screen is the record template of a dataset the plan creates, and which. */\nexport function aiSiteRecordTemplateOf(screen: Pick<AiBuildPlanScreen, 'record'>): string | null {\n const ref = screen.record?.dataset\n return ref && isAiPlanNewRef(ref) ? ref.slice(ref.indexOf(':') + 1).trim() : null\n}\n\nfunction datasetInputOf(job: Pick<AiJob, 'inputs'>): AiSiteDatasetInput {\n const raw = (job.inputs?.[AI_SITE_DATASET_INPUT] ?? {}) as Partial<AiSiteDatasetInput>\n const form = raw.forForm && typeof raw.forForm === 'object' ? raw.forForm : null\n return {\n shownIn: Array.isArray(raw.shownIn) ? raw.shownIn.map(str).filter(Boolean).slice(0, 8) : [],\n recordPages: raw.recordPages === true,\n ...(form && str(form.name)\n ? {\n forForm: {\n name: str(form.name),\n fields: Array.isArray(form.fields) ? form.fields.map(str).filter(Boolean).slice(0, AI_SITE_FORM_DATASET_FIELDS_MAX) : [],\n },\n }\n : {}),\n ...(raw.pictures === 'things' || raw.pictures === 'people' ? { pictures: raw.pictures } : {}),\n }\n}\n\n/** The most fields a form's dataset is designed with: the data plugin writer's own ceiling is higher. */\nexport const AI_SITE_FORM_DATASET_FIELDS_MAX = 12\n\n/** The field types a planned `Name:type` may name, as the data plugin's writer takes them. */\nconst FORM_DATASET_FIELD_TYPES = ['text', 'number', 'integer', 'boolean', 'list'] as const\n\n/** A planned field as a person reads it: `fullName` and `full_name` are \"Full name\", `fechaDeÚltimaVisita` \"Fecha de última visita\". */\nexport function aiSiteDatasetFieldName(planned: string): string {\n const words = planned\n .replace(/([\\p{Ll}\\p{N}])(\\p{Lu})/gu, '$1 $2')\n .replace(/[_-]+/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n return words ? words.charAt(0).toUpperCase() + words.slice(1).toLowerCase() : ''\n}\n\n/**\n * A dataset a form writes to, as the data plugin's writer takes it\n * (AGL-3616): designed with no model, since its records are the\n * submissions. Its fields are its planned ones — or, where the plan gave it\n * none, the form's — each a person's words for it, text unless the plan\n * typed it as `Name:type`, never required, so a submission that leaves one\n * blank is still a record. It starts with no records. Pure.\n */\nexport function aiSiteFormDatasetContent(\n name: string,\n planned: readonly string[],\n form: { fields: readonly string[] },\n): Record<string, unknown> {\n const specs = (planned.length ? planned : form.fields).slice(0, AI_SITE_FORM_DATASET_FIELDS_MAX)\n const seen = new Set<string>()\n const fields: Array<{ name: string; type: string }> = []\n for (const spec of specs) {\n const at = spec.lastIndexOf(':')\n const typed = at > 0 ? spec.slice(at + 1).trim().toLowerCase() : ''\n const type = (FORM_DATASET_FIELD_TYPES as readonly string[]).includes(typed) ? typed : 'text'\n const fieldName = aiSiteDatasetFieldName(type === typed ? spec.slice(0, at) : spec).slice(0, 60)\n if (!fieldName || seen.has(fieldName.toLowerCase())) continue\n seen.add(fieldName.toLowerCase())\n fields.push({ name: fieldName, type })\n }\n return { name, fields, records: [] }\n}\n\n/** The note a form's dataset carries on the job's page. */\nexport function aiSiteFormDatasetNote(form: string): string {\n return `Empty to start: each submission of the form “${form}” is added here, in Data.`\n}\n\nconst limitReview = (message: string) => ({ reason: 'limit' as const, message, findings: [] })\n\n/** The wall clock a dataset's photos may take inside its pass: the 20 seconds a page's pictures had (AGL-3660). */\nexport const AI_SITE_DATASET_PHOTOS_BUDGET_MS = 20_000\n\n/** The field a pictured dataset's photo is kept in, where the plan gave it none. */\nexport const AI_SITE_DATASET_IMAGE_FIELD = 'Image'\n\n/**\n * The field a pictured dataset keeps what each record's photo shows in\n * (AGL-3856), which its card's and its page's Image take as their alt text:\n * a record's title is what it is called, never what its photo shows.\n */\nexport const AI_SITE_DATASET_IMAGE_ALT_FIELD = 'Image description'\n\n/** A planned field that already names a record's photo. */\nconst IMAGE_FIELD_NAME =\n /^(?:main |cover |hero |featured? )?(?:image|photo|picture|photograph|thumbnail|headshot|portrait|cover)s?$/i\n\n/** One record's photo: the address its Image shows, and the library asset placed, which no page shows again. */\nexport interface AiSiteDatasetRecordPhoto {\n /** The media library's CDN path, or a starter's site path; `null` for none. */\n src: string | null\n /** The `media:` reference of the stock photo placed, or `null` for a starter. */\n placed: string | null\n /** What the photo shows, in its own words (AGL-3856); `null` for none. */\n alt?: string | null\n}\n\n/**\n * A photo for each record of a pictured dataset (AGL-3616), in order: a stock\n * photo of the record's own name, in the site's craft (\"ceramic speckled\n * serving bowl\"), copied into the site's library, where the deployment has a\n * stock library — never twice in the dataset nor one another part of the job\n * placed, inside {@link AI_SITE_DATASET_PHOTOS_BUDGET_MS} — else a starter\n * photo, as a page's empty picture takes one. A team is searched as the\n * business's people. The photo is kept as the asset's CDN path, the form a\n * product keeps (`aiSiteProductPhotoSrc`), so a replace in the library still\n * reaches it. No AI model is asked, so no credits; never throws.\n */\nexport async function aiSiteDatasetRecordPhotos(input: {\n job: Pick<AiJob, '$id' | 'hostId' | 'createdBy' | 'inputs' | 'brief' | 'plan'>\n /** The dataset, as the plan named it. */\n name: string\n /** Each record's name, by position. */\n names: readonly string[]\n /** What each record is filed under, by position ({@link aiSiteDatasetCategoryOf}, AGL-3856); absent for a list that files none. */\n categories?: ReadonlyArray<string | null>\n pictures: AiSiteDatasetPictures\n signal?: AbortSignal\n stockPhotos?: typeof aiLayoutStockPhotoSource\n}): Promise<AiSiteDatasetRecordPhoto[]> {\n const { job } = input\n if (!input.names.length || !job.hostId) return input.names.map(() => ({ src: null, placed: null }))\n const people = input.pictures === 'people'\n const slots: AiLayoutPictureSlot[] = input.names.map((name, index) => ({\n imageId: `record${index}`,\n frameId: null,\n iconId: null,\n alt: name.trim() || input.name,\n // The record card's own shape: a team's portraits stand, pieces sit wide.\n aspect: people ? 4 / 5 : 4 / 3,\n sectionIndex: 0,\n role: people ? ('about' as const) : ('gallery' as const),\n // A record's name is a search's words, never what its photo shows (AGL-3856).\n standIn: true,\n // A team's record shows an adult in their role, never a child (AGL-3856).\n ...(people ? { people: true } : {}),\n // A piece's record is OF what it names and what it is filed under (AGL-3856).\n ...(people ? {} : { record: input.categories?.[index]?.trim() ? { category: (input.categories[index] as string).trim() } : {} }),\n }))\n const seed = `${job.$id}:records`\n let found: ReadonlyArray<AiLayoutPicturePhoto | null> = []\n try {\n const source = (input.stockPhotos ?? aiLayoutStockPhotoSource)(\n {\n hostId: job.hostId,\n uid: job.createdBy,\n seed,\n business: aiSiteWords(job.inputs).about || job.brief,\n ...aiStockPhotoWordsOf(job),\n sectionNames: [input.name],\n jobId: aiOriginJobId(job),\n // Each record may try its name, its object and the site's world.\n searches: slots.length * 3,\n ...(input.signal ? { signal: input.signal } : {}),\n },\n { budgetMs: AI_SITE_DATASET_PHOTOS_BUDGET_MS },\n )\n if (source) found = await source(slots)\n } catch (error) {\n console.warn('ai site dataset: the stock photos failed; starter photos fill them', { error: String(error) })\n }\n const starters = aiLayoutStarterPhotos(slots, seed)\n const hostId = job.hostId\n return slots.map((_slot, index) => {\n const stock = aiSiteProductPhotoSrc(found[index]?.src, hostId)\n if (stock) return { src: stock, placed: found[index]?.src ?? null, alt: found[index]?.alt?.trim() || null }\n return { src: aiSiteProductPhotoSrc(starters[index]?.src, hostId), placed: null, alt: starters[index]?.alt?.trim() || null }\n })\n}\n\n/**\n * A designed dataset's content with its records' photos (AGL-3616): the\n * planned field that names a photo (\"Image\", \"Photo\") becomes the data\n * plugin's `image` field, else one called \"Image\" is added after the others,\n * and each record holds its photo there; a record with none holds nothing.\n * Pure.\n */\nexport function aiSiteDatasetContentWithPhotos(\n content: Record<string, unknown>,\n photos: ReadonlyArray<string | null>,\n /** What each record's photo shows (AGL-3856), kept in {@link AI_SITE_DATASET_IMAGE_ALT_FIELD}; none adds no field. */\n alts: ReadonlyArray<string | null> = [],\n): Record<string, unknown> {\n const fields = (Array.isArray(content['fields']) ? content['fields'] : []) as Array<{ name: string; type?: string }>\n const named = fields.find((field) => IMAGE_FIELD_NAME.test(str(field.name)))\n const fieldName = named ? named.name : AI_SITE_DATASET_IMAGE_FIELD\n const withImage = named\n ? fields.map((field) => (field === named ? { ...field, type: 'image' } : field))\n : [...fields, { name: AI_SITE_DATASET_IMAGE_FIELD, type: 'image' }]\n const described = alts.some((alt, index) => Boolean(alt && photos[index]))\n const altName = AI_SITE_DATASET_IMAGE_ALT_FIELD\n const nextFields =\n described && !withImage.some((field) => str(field.name).toLowerCase() === altName.toLowerCase())\n ? [...withImage, { name: altName, type: 'text' }]\n : withImage\n const records = (Array.isArray(content['records']) ? content['records'] : []) as Array<Record<string, unknown>>\n return {\n ...content,\n fields: nextFields,\n records: records.map((record, index) => {\n const next = { ...record }\n delete next[fieldName]\n const photo = photos[index]\n const alt = photo && described ? alts[index] : null\n return photo ? { ...next, [fieldName]: photo, ...(alt ? { [altName]: alt } : {}) } : next\n }),\n }\n}\n\nexport interface AiSiteDatasetRunnerDeps {\n generate?: typeof generateAiDataset\n writerFor?: typeof pluginResourceDraftWriter\n /** Where a pictured dataset's photos come from; the stock library, else the starters, otherwise. */\n photos?: typeof aiSiteDatasetRecordPhotos\n}\n\n/** The fields and record names a written dataset reports, as its output's proposal keeps them. */\ninterface AiSiteDatasetProposal {\n fields: AiLayoutListingField[]\n /** Each record's name: its first field's value. */\n recordNames: string[]\n addressField: string | null\n /** The field each record's photo is in, where it has one (AGL-3616). */\n imageField?: string | null\n /** The library photos its records show (`media:` references), which no page places again. */\n photos?: string[]\n /**\n * The fields most of its first records leave empty, by id (AGL-3616): a\n * tour's venues not yet known. A card never binds one — it would print\n * nothing on most records — so its listing leaves them out.\n */\n sparseFields?: string[]\n /**\n * What its records are filed under (AGL-3921): the category-like field, by\n * id, and each record's value of it, by position as {@link recordNames}.\n * A section named for one value lists only its records.\n */\n groups?: { field: string; values: string[] }\n}\n\n/** A field whose name says it files its records: a category, a type, a kind. */\nconst CATEGORY_FIELD = /^(?:(?:gallery|session|service|event|course|class|product|menu|work|project) )?(?:category|categories|type|kind|collection|genre|group|section|subject|occasion|series)$/i\n\n/**\n * What a designed dataset's records are filed under (AGL-3921): its first\n * field whose name says it files them (\"Category\", \"Type\", \"Session type\"),\n * with each record's value, where they hold at least two different values\n * and some record shares one — a list that files every record apart files\n * none. `null` otherwise. Pure.\n */\nexport function aiSiteDatasetCategoryOf(dataset: {\n fields: ReadonlyArray<{ name: string }>\n records: ReadonlyArray<ReadonlyArray<string | undefined>>\n}): { column: number; name: string; values: Array<string | null> } | null {\n for (const [column, field] of dataset.fields.entries()) {\n if (column === 0 || !CATEGORY_FIELD.test(field.name.trim())) continue\n const values = dataset.records.map((values) => (values[column] ?? '').replace(/\\s+/g, ' ').trim() || null)\n const distinct = new Set(values.filter((value): value is string => Boolean(value)).map((value) => value.toLowerCase()))\n if (distinct.size >= 2 && distinct.size < values.filter(Boolean).length) return { column, name: field.name, values }\n }\n return null\n}\n\n/**\n * A dataset's groups as its proposal keeps them: the written field's id, and\n * the value of each record its {@link AiSiteDatasetProposal.recordNames} names.\n */\nfunction aiSiteDatasetGroupsOf(\n category: ReturnType<typeof aiSiteDatasetCategoryOf>,\n written: readonly AiLayoutListingField[],\n designed: { fields: ReadonlyArray<{ name: string }>; records: ReadonlyArray<ReadonlyArray<string | undefined>> },\n): Pick<AiSiteDatasetProposal, 'groups'> {\n if (!category) return {}\n const field =\n written.find((entry) => entry.name.trim().toLowerCase() === category.name.trim().toLowerCase())?.id ??\n (written.length === designed.fields.length ? written[category.column]?.id : undefined)\n if (!field) return {}\n const values = designed.records.flatMap((record, index) => record[0] ? [category.values[index] ?? ''] : []).slice(0, 12)\n return { groups: { field, values } }\n}\n\n/**\n * The fields of a designed dataset that its records leave empty on most of\n * them — every record, or more than half — by the id the data plugin gave\n * each (AGL-3616). Its first field is the record's name and is never one. The\n * live low-tide-hollow start (beta.239) seeded its tour dates with no venue,\n * rightly inventing none, and its cards bound the venue as their eyebrow.\n */\nexport function aiDatasetSparseFields(\n dataset: { fields: ReadonlyArray<{ name: string }>; records: ReadonlyArray<ReadonlyArray<string | undefined>> },\n written: readonly AiLayoutListingField[],\n): string[] {\n if (!dataset.records.length) return []\n const idOf = (name: string, column: number) =>\n written.find((field) => field.name.trim().toLowerCase() === name.trim().toLowerCase())?.id ?? written[column]?.id ?? null\n return dataset.fields.flatMap((field, column) => {\n if (column === 0) return []\n const filled = dataset.records.filter((values) => (values[column] ?? '').trim()).length\n const id = idOf(field.name, column)\n return id && filled * 2 <= dataset.records.length ? [id] : []\n })\n}\n\nfunction proposalOf(output: Pick<AiJobOutput, 'proposal'>): AiSiteDatasetProposal {\n const raw = (output.proposal ?? {}) as Partial<AiSiteDatasetProposal>\n return {\n fields: Array.isArray(raw.fields)\n ? raw.fields.filter((field) => field && typeof field.id === 'string' && field.id).map((field) => ({ id: field.id, name: str(field.name) || field.id, type: str(field.type) || 'text' }))\n : [],\n recordNames: Array.isArray(raw.recordNames) ? raw.recordNames.map(str).filter(Boolean).slice(0, 12) : [],\n addressField: str(raw.addressField) || null,\n imageField: str(raw.imageField) || null,\n photos: Array.isArray(raw.photos) ? raw.photos.map(str).filter((src) => src.startsWith('media:')).slice(0, 24) : [],\n sparseFields: Array.isArray(raw.sparseFields) ? raw.sparseFields.map(str).filter(Boolean) : [],\n ...(raw.groups && typeof raw.groups === 'object' && str(raw.groups.field) && Array.isArray(raw.groups.values)\n ? { groups: { field: str(raw.groups.field), values: raw.groups.values.slice(0, 12).map(str) } }\n : {}),\n }\n}\n\n/**\n * The dataset unit's runner, on the job the scaffold derived for it: the one\n * creation its plan carries, designed by the model and written by the data\n * plugin, under the creation's own id. A pass repeated after its write finds\n * the dataset the writer wrote and reports it again, spending nothing.\n */\nexport function createAiSiteDatasetRunner(deps: AiSiteDatasetRunnerDeps = {}): AiJobStepRunner {\n const generate = deps.generate ?? generateAiDataset\n const writerFor = deps.writerFor ?? pluginResourceDraftWriter\n const photosFor = deps.photos ?? aiSiteDatasetRecordPhotos\n return async (context): Promise<AiJobStepOutcome> => {\n const { job, firestore, signal } = context\n const model = context.modelFor?.(AI_DATASET_STEP) ?? aiModelForStep(AI_DATASET_STEP)\n const creation = (job.plan as AiJobPlan | null)?.create?.find((entry) => entry.kind === 'dataset')\n const keeper = writerFor(AI_SITE_DATASET_RESOURCE)\n if (!job.hostId || !creation) return { ...aiUnspentOutcome(model), failure: 'Open the site before adding its data.' }\n if (!keeper) return { ...aiUnspentOutcome(model), failure: 'Datasets are not available on this site.' }\n const host = await firestore.collection('hosts').doc(job.hostId).get()\n const hostSubdomain = str(host.get('subdomain')) || null\n const output = (id: string, name: string, proposal: AiSiteDatasetProposal, records: number): AiJobOutput => ({\n resource: 'draft',\n draftResource: AI_SITE_DATASET_RESOURCE,\n id,\n hostId: job.hostId ?? null,\n hostSubdomain,\n label: name,\n note: aiSiteDatasetNote(records),\n proposal: proposal as unknown as Record<string, unknown>,\n })\n const input = datasetInputOf(job)\n // Asked again under the same id: the dataset already written.\n const written = await keeper.writer.read({ hostId: job.hostId, id: job.$id })\n if (written) {\n const facts = written.facts as { fields?: AiLayoutListingField[]; addressField?: string | null; imageField?: string | null }\n const again = output(\n written.id,\n written.name || creation.name,\n { fields: facts.fields ?? [], recordNames: [], addressField: facts.addressField ?? null, imageField: facts.imageField ?? null },\n 0,\n )\n return aiUnspentOutcome(model, {\n outputs: [input.forForm ? { ...again, note: aiSiteFormDatasetNote(input.forForm.name) } : again],\n })\n }\n // A form's dataset (AGL-3616): its records are the submissions, so it is\n // designed from the plan with no model, and starts empty.\n if (input.forForm) {\n const content = aiSiteFormDatasetContent(creation.name, creation.fields, input.forForm)\n const checked = keeper.writer.check(content, { hostId: job.hostId })\n if (checked.ok === false) {\n console.error('ai site dataset: the dataset writer refused a form dataset we made', { orgId: job.orgId, jobId: job.$id, problems: checked.problems })\n return { ...aiUnspentOutcome(model), failure: AI_SITE_DATASET_NOT_WRITTEN_COPY }\n }\n const result = await keeper.writer.write({\n orgId: job.orgId,\n hostId: job.hostId,\n uid: job.createdBy,\n org: (context.org ?? null) as Readonly<Record<string, unknown>> | null,\n now: context.now,\n id: job.$id,\n name: creation.name,\n content,\n })\n if (result.ok === false) {\n if (result.status === 400) return { ...aiUnspentOutcome(model), failure: AI_SITE_DATASET_NOT_WRITTEN_COPY }\n return { ...aiUnspentOutcome(model), review: limitReview(result.error) }\n }\n const facts = result.facts as { fields?: AiLayoutListingField[]; addressField?: string | null }\n return aiUnspentOutcome(model, {\n outputs: [\n {\n ...output(result.id, result.name, { fields: facts.fields ?? [], recordNames: [], addressField: null }, 0),\n note: aiSiteFormDatasetNote(input.forForm.name),\n },\n ],\n })\n }\n const generation = await generate({\n brief: job.brief,\n merchantWords: job.brief,\n name: creation.name,\n why: creation.why,\n fields: creation.fields,\n shownIn: input.shownIn,\n recordPages: input.recordPages,\n model,\n maxTokens: AI_SITE_DATASET_BUDGET.maxTokens(model),\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(generation)\n if (generation.status === 'refused') return { ...spent, refused: true }\n if (generation.status === 'needs_input') return { ...spent, failure: generation.message }\n const designed = aiDatasetDraftContent(creation.name, generation.value, { recordPages: input.recordPages })\n // What each record is filed under, which its photo and the sections that list it by its value read (AGL-3856).\n const category = aiSiteDatasetCategoryOf(generation.value)\n // A list a visitor looks at keeps its records' photos (AGL-3616): searched\n // in code, never asked of the model, so they cost no credits.\n const photos = input.pictures\n ? await photosFor({\n job,\n name: creation.name,\n names: generation.value.records.map((values) => values[0] ?? ''),\n ...(category ? { categories: category.values } : {}),\n pictures: input.pictures,\n ...(signal ? { signal } : {}),\n }).catch(() => [] as AiSiteDatasetRecordPhoto[])\n : []\n const content = input.pictures\n ? aiSiteDatasetContentWithPhotos(\n designed,\n generation.value.records.map((_values, index) => photos[index]?.src ?? null),\n generation.value.records.map((_values, index) => photos[index]?.alt ?? null),\n )\n : designed\n // The data plugin's own rules, before anything is written: content we\n // made that its model refuses is our failure, refunded.\n const checked = keeper.writer.check(content, { hostId: job.hostId })\n if (checked.ok === false) {\n console.error('ai site dataset: the dataset writer refused a dataset we made', { orgId: job.orgId, jobId: job.$id, problems: checked.problems })\n return { ...spent, failure: AI_SITE_DATASET_NOT_WRITTEN_COPY }\n }\n const result = await keeper.writer.write({\n orgId: job.orgId,\n hostId: job.hostId,\n uid: job.createdBy,\n org: (context.org ?? null) as Readonly<Record<string, unknown>> | null,\n now: context.now,\n id: job.$id,\n name: creation.name,\n content,\n })\n if (result.ok === false) {\n if (result.status === 400) return { ...spent, failure: AI_SITE_DATASET_NOT_WRITTEN_COPY }\n // The allowance, the role, the plan or the flag: the workspace's to change.\n return { ...spent, review: limitReview(result.error) }\n }\n const facts = result.facts as {\n fields?: AiLayoutListingField[]\n records?: number\n addressField?: string | null\n imageField?: string | null\n }\n const placed = photos.flatMap((photo) => (photo.placed ? [photo.placed] : []))\n const proposal: AiSiteDatasetProposal = {\n fields: facts.fields ?? [],\n recordNames: generation.value.records.map((values) => values[0] ?? '').filter(Boolean).slice(0, 12),\n addressField: facts.addressField ?? null,\n ...(facts.imageField ? { imageField: facts.imageField } : {}),\n ...(placed.length ? { photos: placed } : {}),\n sparseFields: aiDatasetSparseFields(generation.value, facts.fields ?? []),\n ...aiSiteDatasetGroupsOf(category, facts.fields ?? [], generation.value),\n }\n return { ...spent, outputs: [output(result.id, result.name, proposal, facts.records ?? generation.value.records.length)] }\n }\n}\n\nexport const runAiSiteDatasetUnit = createAiSiteDatasetRunner()\n\n/**\n * Whether a dataset may be created for this member on this site, asked before\n * its first pass so a refusal spends nothing; `null` admits. The data plugin\n * must run here (on for the workspace and the site, past its release flag),\n * and its writer says whether this member may make one now: the role, the\n * plan, the flag, the allowance.\n */\nexport async function aiSiteDatasetRefusal(\n context: Pick<AiJobStepContext, 'firestore' | 'org' | 'now'> & { job: Pick<AiJob, 'orgId' | 'hostId' | 'createdBy'> },\n deps: { admission?: typeof aiPluginDraftAdmissionRefusal; writerFor?: (resource: string) => ReturnType<typeof pluginResourceDraftWriter> } = {},\n): Promise<string | null> {\n const { job } = context\n if (!job.hostId) return 'Open the site first.'\n const writerFor = deps.writerFor ?? pluginResourceDraftWriter\n const admission: AiJobAdmissionContext = {\n firestore: context.firestore,\n orgId: job.orgId,\n hostId: job.hostId,\n inputs: {},\n org: context.org ?? null,\n uid: job.createdBy,\n }\n const refused = await (deps.admission ?? aiPluginDraftAdmissionRefusal)(admission, {\n kind: 'site',\n drafts: [{ resource: AI_SITE_DATASET_RESOURCE, label: DATA_PLUGIN_LABEL }],\n writerFor: (resource) => writerFor(resource)?.writer ?? null,\n ownerFor: (resource) => writerFor(resource)?.pluginId ?? null,\n now: context.now,\n })\n return refused?.error ?? null\n}\n\n/**\n * A site plan's dataset capability on this workspace (AGL-3616): where the\n * workspace's plan includes datasets, whether the data plugin runs here and\n * this member may create one now, and how many a start may make. A clause the\n * plan's turn completes is the reason where it may not.\n */\nexport async function aiSitePlanDatasetCapability(\n capabilities: AiPlanCapabilities,\n context: Parameters<typeof aiSiteDatasetRefusal>[0],\n deps: Parameters<typeof aiSiteDatasetRefusal>[1] = {},\n): Promise<AiPlanCapabilities> {\n if (!capabilities.create.dataset.allowed) return capabilities\n const refusal = await aiSiteDatasetRefusal(context, deps).catch((error: unknown) => {\n console.error('ai site plan: the dataset admission failed', { orgId: context.job.orgId, error })\n return 'datasets could not be checked just now'\n })\n const left = Math.min(AI_SITE_DATASETS_MAX, checkDatasetQuota(context.org as never, 0).limit)\n const dataset = refusal\n ? { allowed: false, left: 0, reason: `datasets cannot be created here: ${refusal.replace(/\\.$/, '')}` }\n : { allowed: true, left, reason: null }\n return { ...capabilities, create: { ...capabilities.create, dataset } }\n}\n\n/**\n * A `records` listing for each dataset that was made and that a section of the\n * plan names (AGL-3616). Its fields, where none are given, are read off the\n * site's inventory when the page is designed (`aiLayoutListingsWithDatasets`).\n */\nexport function aiDatasetListingsOf(\n datasets: ReadonlyArray<{\n id: string\n name: string\n records?: string[]\n fields?: AiLayoutListingField[]\n imageField?: string | null\n /** The record's page-address field, where the writer added one (AGL-3727). */\n addressField?: string | null\n /** What its records are filed under, by position as `records` (AGL-3921): a section named for one value lists its records alone. */\n groups?: { field: string; values: readonly string[] } | null\n }>,\n screens: readonly AiLayoutListingScreen[],\n): AiLayoutListing[] {\n return datasets.flatMap((dataset) => {\n const placements = aiLayoutRecordsPlacements(dataset, screens)\n if (!placements.length) return []\n // Each card links its record's own page where the plan makes one (AGL-3727).\n const recordBase = aiLayoutRecordBaseOf(dataset, screens)\n return [\n {\n id: aiLayoutListingId('records', dataset.id),\n kind: 'records' as const,\n name: dataset.name,\n records: dataset.records ?? [],\n datasetId: dataset.id,\n ...(dataset.fields?.length ? { fields: dataset.fields } : {}),\n // Its card leads with the record's photo (AGL-3616).\n ...(dataset.imageField ? { imageField: dataset.imageField } : {}),\n // The address is read off the site's inventory where the build does not know it yet.\n ...(recordBase ? { recordBase, ...(dataset.addressField ? { addressField: dataset.addressField } : {}) } : {}),\n placements,\n },\n ]\n })\n}\n\n/**\n * A `records` listing for each dataset the workspace already keeps that a\n * site start's plan reuses and a section names (AGL-3771), as a build lists\n * the ones it reuses (AGL-3747). A second site in a workspace reuses the\n * first one's menu: its plan names the dataset by id, the start listed only\n * the datasets it made, and the page was asked to \"place\" a dataset no block\n * can draw — the home's \"Del menú\" section was refused for showing none of\n * its six items, and the Menú page published with no menu. A dataset one of\n * the plan's forms writes into holds the site's submissions, and is never\n * listed on a page.\n */\nexport function aiSiteReusedDatasetListings(input: {\n plan: Pick<AiJobPlan, 'reuse' | 'create' | 'labels'>\n screens: readonly AiLayoutListingScreen[]\n /** The listings the start already has, whose datasets are not listed twice. */\n listed: ReadonlyArray<Pick<AiLayoutListing, 'datasetId'>>\n}): AiLayoutListing[] {\n const submissions = new Set(\n input.plan.create.flatMap((entry) => (entry.kind === 'form' && entry.writesTo && !isAiPlanNewRef(entry.writesTo) ? [entry.writesTo] : [])),\n )\n const listed = new Set(input.listed.map((listing) => listing.datasetId).filter(Boolean))\n const datasets = input.plan.reuse\n .filter((entry) => entry.kind === 'dataset' && !submissions.has(entry.id) && !listed.has(entry.id))\n .map((entry) => ({ id: entry.id, name: input.plan.labels?.[entry.id] || entry.id }))\n return aiDatasetListingsOf(datasets, input.screens)\n}\n\n/**\n * A SITE START NEVER SHOWS ANOTHER SITE'S RECORDS (AGL-3912).\n *\n * Datasets belong to the organization, and so do their records: neither\n * names the site it was written for, and a dataset outlives the site that\n * filled it (the data plugin keeps `visibleTo` and nothing else of a site). A\n * gym's start reused the workspace's \"Session packages\", \"Coaches\" and \"Gym\n * FAQs\", and published a deleted photographer's wedding packages and a\n * deleted studio's coach bio (\"Leads coaching at Ironline Strength Studio\")\n * with four broken photos; a photographer's start reused another\n * photographer's gallery and drew six broken covers.\n *\n * So a site start reuses a dataset only when its records are this site's to\n * show ({@link aiSiteDatasetIsThisSites}):\n * - it holds no records at all — an empty list, such as the one a form\n * writes its submissions to, is the same list on any site; or\n * - its scope names this site alone (`siteOnly`), so it was made for it; or\n * - this site already serves its records pages of their own (`recordBase`).\n * Anything else — records in a dataset shared with the workspace or with\n * other sites, and a dataset whose records could not be counted — was filled\n * for something else, and the plan is settled in code before the rules read\n * it ({@link aiSettleSiteForeignDatasets}): the reuse becomes a creation of\n * the same name and fields, designed from this site's brief with photos of\n * its own, and every section, record template and form that named it names\n * the creation. Where this job may create no dataset, the reuse comes off\n * instead and each section writes its items out. Never a refusal, and\n * nothing a member is asked.\n *\n * An Assist change to a site that exists keeps reusing what the site lists:\n * this is a site start's rule, and only its plan is settled by it.\n */\nexport function aiSiteDatasetIsThisSites(row: Pick<AiInventoryDataset, 'records' | 'siteOnly' | 'recordBase'>): boolean {\n return row.records === 0 || row.siteOnly === true || Boolean(row.recordBase)\n}\n\n/** A planned field that is a record's page address, which the writer adds itself. */\nconst ADDRESS_FIELD_NAME = /^(?:page )?(?:address|slug|url|link)$/i\n\n/** The fields a dataset is made again with: its own, less the photo, its description and the page address the writer adds. */\nfunction remadeFields(row: AiInventoryDataset): string[] {\n const ids = row.fieldIds ?? []\n return row.fields\n .filter((name, index) => {\n const id = ids[index]\n if (id && (id === row.imageField || id === row.addressField)) return false\n if (IMAGE_FIELD_NAME.test(name.trim()) || ADDRESS_FIELD_NAME.test(name.trim())) return false\n return name.trim().toLowerCase() !== AI_SITE_DATASET_IMAGE_ALT_FIELD.toLowerCase()\n })\n .slice(0, AI_BUILD_PLAN_LIMITS.fields)\n}\n\n/**\n * A site start's plan with every dataset it reuses that holds another\n * site's records made again for this one (AGL-3912): each the inventory marks\n * `foreign` ({@link aiSiteInventoryWithRecordCounts}, by\n * {@link aiSiteDatasetIsThisSites}). The creation keeps the dataset's name,\n * which rule 7 does not hold against it as a duplicate. Pure; a plan that\n * reuses none comes back as it was.\n */\nexport function aiSettleSiteForeignDatasets(\n plan: AiBuildPlan,\n inventory: Pick<AiSiteInventory, 'datasets'> | null,\n capabilities: AiPlanCapabilities | null = null,\n): AiBuildPlan {\n const rows = new Map((inventory?.datasets ?? []).map((row) => [row.id, row]))\n const foreign = plan.reuse.filter((entry) => entry.kind === 'dataset' && rows.get(entry.id)?.foreign === true)\n if (!foreign.length) return plan\n const creatable = !capabilities || capabilities.create.dataset.allowed\n const taken = new Map<string, AiBuildPlanCreate | null>([\n ...plan.create.map((entry) => [entry.name.trim().toLowerCase(), entry] as const),\n ...(plan.items ?? []).map((item) => [item.name.trim().toLowerCase(), null] as const),\n ])\n // Each foreign dataset's id → the `new:` reference that replaces it, or `null` where it comes off.\n const replaced = new Map<string, string | null>()\n const added: AiBuildPlanCreate[] = []\n for (const entry of foreign) {\n const row = rows.get(entry.id) as AiInventoryDataset\n const base = row.name.trim() || 'Records'\n if (!creatable) {\n replaced.set(entry.id, null)\n continue\n }\n // The plan already makes one of that name: that one is this site's.\n const same = taken.get(base.toLowerCase())\n if (same?.kind === 'dataset') {\n replaced.set(entry.id, `${AI_PLAN_NEW_REF_PREFIX}${same.name}`)\n continue\n }\n let name = base\n for (let n = 2; taken.has(name.toLowerCase()); n += 1) name = `${base} ${n}`\n const creation: AiBuildPlanCreate = {\n kind: 'dataset',\n name,\n why: entry.purpose || `Lists ${base} on this site.`,\n duplicateOf: null,\n fields: remadeFields(row),\n }\n added.push(creation)\n taken.set(name.toLowerCase(), creation)\n replaced.set(entry.id, `${AI_PLAN_NEW_REF_PREFIX}${name}`)\n }\n const swap = (ref: string): string | null => (replaced.has(ref) ? (replaced.get(ref) ?? null) : ref)\n return {\n ...plan,\n reuse: plan.reuse.filter((entry) => !(entry.kind === 'dataset' && replaced.has(entry.id))),\n create: [\n ...plan.create.map((entry) => {\n if (entry.kind !== 'form' || !entry.writesTo || !replaced.has(entry.writesTo)) return entry\n const writesTo = swap(entry.writesTo)\n if (writesTo) return { ...entry, writesTo }\n // A form whose dataset comes off sends its submissions to the Inbox only.\n const rest = { ...entry }\n delete rest.writesTo\n return rest\n }),\n ...added,\n ],\n screens: plan.screens.map((screen) => {\n // A record template of a dataset made again shows the new one; of one that comes off, it is a page of its own.\n const record =\n screen.record && replaced.has(screen.record.dataset) ? { record: swap(screen.record.dataset) } : null\n const sections = screen.sections.map((section) => {\n if (!section.uses.some((ref) => replaced.has(ref))) return section\n const uses = section.uses.flatMap((ref) => {\n const next = swap(ref)\n return next ? [next] : []\n })\n // A list that comes off is written out on the page, as fewer items than a dataset binds.\n const dropped = section.uses.some((ref) => replaced.has(ref) && !replaced.get(ref))\n return { ...section, uses, ...(dropped ? { items: Math.min(section.items, AI_TYPED_LIST_MIN_ITEMS - 1) } : {}) }\n })\n return {\n ...screen,\n ...(record && screen.record ? { record: record.record ? { ...screen.record, dataset: record.record } : null } : {}),\n sections,\n }\n }),\n }\n}\n\n/** How a dataset's records are counted: the data plugin's index, which answers `facts.records`. */\nexport type AiDatasetRecordCounter = (request: { orgId: string; id: string }) => Promise<number | null>\n\n/** The production counter: the data plugin's `dataset` index, read one dataset at a time. */\nexport const aiDatasetRecordCount: AiDatasetRecordCounter = async ({ orgId, id }) => {\n const index = pluginRecordIndex('dataset')?.index\n if (!index) return null\n const found = await index.get({ orgId, id })\n const records = found?.facts['records']\n return typeof records === 'number' && Number.isFinite(records) ? records : null\n}\n\n/**\n * A site start's inventory with how many records each dataset holds\n * (AGL-3912), and each whose records are not this site's to show\n * ({@link aiSiteDatasetIsThisSites}) marked `foreign`. The count is asked\n * once per plan, of every dataset the site sees, all at once; a count that\n * fails leaves `records` out, which reads as another site's. Never throws.\n */\nexport async function aiSiteInventoryWithRecordCounts(\n inventory: AiSiteInventory | null,\n orgId: string,\n count: AiDatasetRecordCounter = aiDatasetRecordCount,\n): Promise<AiSiteInventory | null> {\n if (!inventory?.datasets.length) return inventory\n const counts = await Promise.all(\n inventory.datasets.map((row) =>\n count({ orgId, id: row.id }).catch((error: unknown) => {\n console.warn('ai site plan: a dataset’s records could not be counted', { orgId, id: row.id, error: String(error) })\n return null\n }),\n ),\n )\n return {\n ...inventory,\n datasets: inventory.datasets.map((row, index) => {\n const records = counts[index]\n const counted = typeof records === 'number' ? { ...row, records } : row\n return aiSiteDatasetIsThisSites(counted) ? counted : { ...counted, foreign: true as const }\n }),\n }\n}\n\n/**\n * The site's datasets a layout or a page unit is handed (AGL-3616), each a\n * `records` listing with the sections of the plan's pages that name it, once\n * its unit wrote it. A dataset not yet written, or one that failed, lists\n * nowhere: the pages built without it write the items out.\n */\nexport function aiSiteDatasetListings(input: {\n outputs: readonly AiJobOutput[]\n datasets: ReadonlyArray<Pick<AiBuildPlanCreate, 'name'>>\n screens: readonly AiLayoutListingScreen[]\n /** The ids each dataset's unit delivered, by plan name lowercased. */\n delivered: ReadonlyMap<string, string>\n}): AiLayoutListing[] {\n const made = input.datasets.flatMap((dataset) => {\n const id = input.delivered.get(dataset.name.trim().toLowerCase())\n const output = id\n ? input.outputs.find((entry) => entry.resource === 'draft' && entry.draftResource === AI_SITE_DATASET_RESOURCE && entry.id === id)\n : undefined\n if (!id || !output) return []\n const proposal = proposalOf(output)\n return [\n {\n id,\n // Placed by the name the plan's sections gave it.\n name: dataset.name,\n records: proposal.recordNames,\n // The address field is the record page's, never a card's words; the\n // photo is the card's picture, never its words; a field most records\n // leave empty is no card's either (AGL-3616).\n fields: proposal.fields.filter(\n (field, index) =>\n field.id !== proposal.addressField &&\n field.id !== proposal.imageField &&\n (index === 0 || !proposal.sparseFields?.includes(field.id)),\n ),\n imageField: proposal.imageField ?? null,\n addressField: proposal.addressField,\n groups: proposal.groups ?? null,\n },\n ]\n })\n return aiDatasetListingsOf(made, input.screens)\n}\n\n/** The library photos the site's datasets' records show (AGL-3616), which a page does not place again. */\nexport function aiSiteDatasetPlacedPhotos(outputs: readonly AiJobOutput[]): string[] {\n return [\n ...new Set(\n outputs\n .filter((output) => output.resource === 'draft' && output.draftResource === AI_SITE_DATASET_RESOURCE)\n .flatMap((output) => proposalOf(output).photos ?? []),\n ),\n ]\n}\n\n/** What a page is told about the datasets built before it. */\nexport function aiSiteDatasetBriefLines(outputs: readonly AiJobOutput[]): string[] {\n const datasets = outputs.filter((output) => output.resource === 'draft' && output.draftResource === AI_SITE_DATASET_RESOURCE)\n return datasets.flatMap((output) => {\n const names = proposalOf(output).recordNames\n return names.length\n ? [`This site's dataset “${output.label}” holds: ${names.map((name) => `“${name}”`).join(', ')}. Where a page names one, name it as written; never name one that is not in this list.`]\n : []\n })\n}\n"],"names":["checkDatasetQuota","pluginResourceDraftWriter","pluginRecordIndex","AI_BUILD_PLAN_LIMITS","AI_PLAN_NEW_REF_PREFIX","isAiPlanNewRef","AI_TYPED_LIST_MIN_ITEMS","AI_SITE_DATASETS_MAX","AI_STEP_TIERS","aiModelForStep","AI_DATASET_MAX_TOKENS","AI_DATASET_STEP","aiDatasetDraftContent","generateAiDataset","aiLayoutListingId","aiLayoutRecordBaseOf","aiLayoutRecordsPlacements","aiLayoutStarterPhotos","aiSiteWords","aiOriginJobId","aiSiteProductPhotoSrc","aiLayoutStockPhotoSource","aiStockPhotoWordsOf","AI_DATASET_DRAFT_RESOURCE","aiJobStepBudget","aiGenerationSpent","aiUnspentOutcome","aiPluginDraftAdmissionRefusal","AI_SITE_DATASET_RESOURCE","DATA_PLUGIN_LABEL","AI_SITE_DATASET_INPUT","READ_ONLY_LIST","PEOPLE_LIST","PICTURED_LIST","PICTURED_SECTION","aiSiteDatasetPicturesOf","dataset","sections","length","own","name","test","some","section","AI_SITE_DATASET_NOT_WRITTEN_COPY","aiSiteDatasetNote","records","AI_SITE_RECORD_PAGE_NOTE","AI_SITE_DATASET_WRITES_MS","AI_SITE_DATASET_BUDGET","tier","maxTokens","lookups","ownReadsMs","str","value","trim","namesDataset","ref","slice","indexOf","toLowerCase","aiSitePlanDatasets","plan","create","filter","entry","kind","aiSiteDatasetInputOf","screens","shownIn","sectionNames","screen","uses","push","title","items","recordPages","record","form","find","writesTo","pictures","forForm","fields","AI_SITE_FORM_DATASET_FIELDS_MAX","aiSiteRecordTemplateOf","datasetInputOf","job","raw","inputs","Array","isArray","map","Boolean","FORM_DATASET_FIELD_TYPES","aiSiteDatasetFieldName","planned","words","replace","charAt","toUpperCase","aiSiteFormDatasetContent","specs","seen","Set","spec","at","lastIndexOf","typed","type","includes","fieldName","has","add","aiSiteFormDatasetNote","limitReview","message","reason","findings","AI_SITE_DATASET_PHOTOS_BUDGET_MS","AI_SITE_DATASET_IMAGE_FIELD","AI_SITE_DATASET_IMAGE_ALT_FIELD","IMAGE_FIELD_NAME","aiSiteDatasetRecordPhotos","input","names","hostId","src","placed","people","slots","index","imageId","frameId","iconId","alt","aspect","sectionIndex","role","standIn","categories","category","seed","$id","found","source","stockPhotos","uid","createdBy","business","about","brief","jobId","searches","signal","budgetMs","error","console","warn","String","starters","_slot","stock","aiSiteDatasetContentWithPhotos","content","photos","alts","named","field","withImage","described","altName","nextFields","next","photo","CATEGORY_FIELD","aiSiteDatasetCategoryOf","column","entries","values","distinct","size","aiSiteDatasetGroupsOf","written","designed","id","undefined","flatMap","groups","aiDatasetSparseFields","idOf","filled","proposalOf","output","proposal","recordNames","addressField","imageField","startsWith","sparseFields","createAiSiteDatasetRunner","deps","generate","writerFor","photosFor","context","facts","firestore","model","modelFor","creation","keeper","failure","host","collection","doc","get","hostSubdomain","resource","draftResource","label","note","writer","read","again","outputs","checked","check","ok","orgId","problems","result","write","org","now","status","review","generation","merchantWords","why","spent","refused","catch","_values","runAiSiteDatasetUnit","aiSiteDatasetRefusal","admission","drafts","ownerFor","pluginId","aiSitePlanDatasetCapability","capabilities","allowed","refusal","left","Math","min","limit","aiDatasetListingsOf","datasets","placements","recordBase","datasetId","aiSiteReusedDatasetListings","submissions","listed","listing","reuse","labels","aiSiteDatasetIsThisSites","row","siteOnly","ADDRESS_FIELD_NAME","remadeFields","ids","fieldIds","aiSettleSiteForeignDatasets","inventory","rows","Map","foreign","creatable","taken","item","replaced","added","base","set","same","n","purpose","duplicateOf","swap","rest","dropped","aiDatasetRecordCount","Number","isFinite","aiSiteInventoryWithRecordCounts","count","counts","Promise","all","counted","aiSiteDatasetListings","made","delivered","aiSiteDatasetPlacedPhotos","aiSiteDatasetBriefLines","join"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,2CAA0C;AAC5E,SAASC,yBAAyB,QAAQ,qDAAoD;AAC9F,SAASC,iBAAiB,QAAQ,kDAAiD;AACnF,SACEC,oBAAoB,EACpBC,sBAAsB,EACtBC,cAAc,QAIT,4BAAwB;AAE/B,SAASC,uBAAuB,QAAQ,uCAAmC;AAG3E,SAASC,oBAAoB,QAAQ,0BAAsB;AAC3D,SAASC,aAAa,QAAQ,0BAAsB;AACpD,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SACEC,qBAAqB,EACrBC,eAAe,EACfC,qBAAqB,EACrBC,iBAAiB,QACZ,sCAAkC;AACzC,SACEC,iBAAiB,EACjBC,oBAAoB,EACpBC,yBAAyB,QAIpB,2CAAuC;AAC9C,SACEC,qBAAqB,QAGhB,2CAAuC;AAC9C,SAASC,WAAW,QAAQ,0BAAsB;AAElD,SAASC,aAAa,QAAQ,wBAAoB;AAClD,SAASC,qBAAqB,QAAQ,2BAAuB;AAC7D,SAASC,wBAAwB,EAAEC,mBAAmB,QAAQ,8BAA0B;AACxF,SAASC,yBAAyB,QAAQ,6BAAyB;AACnE,SAASC,eAAe,QAAQ,qBAAiB;AACjD,SAASC,iBAAiB,EAAEC,gBAAgB,QAAQ,yBAAqB;AACzE,SAASC,6BAA6B,QAAQ,4BAAwB;AAG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
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
17
|
import { type SweepAiJobsResult } from './ai-jobs';
|
|
18
|
+
import { type AiEmptySiteSweepResult } from './ai-empty-site-sweep';
|
|
18
19
|
/**
|
|
19
20
|
* Resume AI generation jobs on the AI jobs beat (AGL-2904, AGL-3026).
|
|
20
21
|
*
|
|
@@ -69,10 +70,17 @@ export type AiJobsBeatResult = {
|
|
|
69
70
|
held: true;
|
|
70
71
|
} | ({
|
|
71
72
|
held: false;
|
|
73
|
+
emptySites: AiEmptySiteSweepResult | null;
|
|
72
74
|
} & SweepAiJobsResult);
|
|
73
75
|
/**
|
|
74
|
-
* One beat: the switch, then
|
|
75
|
-
*
|
|
76
|
-
*
|
|
76
|
+
* One beat: the switch, then the empty sites a guided start left that are
|
|
77
|
+
* due for removal (AGL-3936), then one sweep under its own lease owner. The
|
|
78
|
+
* owner is fresh per beat and fixed for the whole sweep, so two beats
|
|
79
|
+
* overlapping inside a lease never read each other's lease as their own.
|
|
80
|
+
*
|
|
81
|
+
* The removals come first, a few a beat inside
|
|
82
|
+
* `AI_EMPTY_SITE_SWEEP_BUDGET_MS`, and whatever they took comes off the
|
|
83
|
+
* sweep's budget, so the route's arithmetic inside `maxDuration` holds. A
|
|
84
|
+
* removal that fails never holds up a job's step.
|
|
77
85
|
*/
|
|
78
86
|
export declare function runAiJobsBeat(): Promise<AiJobsBeatResult>;
|
|
@@ -17,6 +17,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
17
17
|
*/ import { randomUUID } from "crypto";
|
|
18
18
|
import { featureLockdownRefusal, firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
19
19
|
import { AI_JOB_SWEEP_BUDGET_MS, sweepAiJobs } from "./ai-jobs.js";
|
|
20
|
+
import { sweepAiEmptySites } from "./ai-empty-site-sweep.js";
|
|
20
21
|
/**
|
|
21
22
|
* Resume AI generation jobs on the AI jobs beat (AGL-2904, AGL-3026).
|
|
22
23
|
*
|
|
@@ -64,9 +65,15 @@ import { AI_JOB_SWEEP_BUDGET_MS, sweepAiJobs } from "./ai-jobs.js";
|
|
|
64
65
|
* with the sweep's function time, so the plugin dispatcher never serves it.
|
|
65
66
|
*/ export const AI_JOBS_BEAT_PATH = 'admin/ai-jobs-beat';
|
|
66
67
|
/**
|
|
67
|
-
* One beat: the switch, then
|
|
68
|
-
*
|
|
69
|
-
*
|
|
68
|
+
* One beat: the switch, then the empty sites a guided start left that are
|
|
69
|
+
* due for removal (AGL-3936), then one sweep under its own lease owner. The
|
|
70
|
+
* owner is fresh per beat and fixed for the whole sweep, so two beats
|
|
71
|
+
* overlapping inside a lease never read each other's lease as their own.
|
|
72
|
+
*
|
|
73
|
+
* The removals come first, a few a beat inside
|
|
74
|
+
* `AI_EMPTY_SITE_SWEEP_BUDGET_MS`, and whatever they took comes off the
|
|
75
|
+
* sweep's budget, so the route's arithmetic inside `maxDuration` holds. A
|
|
76
|
+
* removal that fails never holds up a job's step.
|
|
70
77
|
*/ export async function runAiJobsBeat() {
|
|
71
78
|
const locked = await featureLockdownRefusal({
|
|
72
79
|
feature: 'ai-generate'
|
|
@@ -77,16 +84,26 @@ import { AI_JOB_SWEEP_BUDGET_MS, sweepAiJobs } from "./ai-jobs.js";
|
|
|
77
84
|
held: true
|
|
78
85
|
};
|
|
79
86
|
}
|
|
87
|
+
const firestore = firebaseAdmin.app().firestore();
|
|
88
|
+
const startedAt = Date.now();
|
|
89
|
+
const emptySites = await sweepAiEmptySites({
|
|
90
|
+
firestore
|
|
91
|
+
}).catch((error)=>{
|
|
92
|
+
console.error('ai jobs beat: the empty site sweep failed', error);
|
|
93
|
+
return null;
|
|
94
|
+
});
|
|
95
|
+
if (emptySites == null ? void 0 : emptySites.removed) console.info(`ai jobs: ${emptySites.removed} empty site(s) removed`);
|
|
80
96
|
const result = await sweepAiJobs({
|
|
81
|
-
firestore
|
|
97
|
+
firestore,
|
|
82
98
|
owner: `beat:${randomUUID()}`,
|
|
83
|
-
budgetMs: AI_JOB_SWEEP_BUDGET_MS
|
|
99
|
+
budgetMs: Math.max(0, AI_JOB_SWEEP_BUDGET_MS - (Date.now() - startedAt))
|
|
84
100
|
});
|
|
85
101
|
if (result.due) {
|
|
86
102
|
console.info(`ai jobs: ${result.ran} step(s) run, ${result.skipped} skipped, ` + `${result.paused} held by a workspace's AI pause, ` + `${result.remaining} left for the next beat` + (result.budgetExhausted ? ' (budget exhausted)' : ''));
|
|
87
103
|
}
|
|
88
104
|
return _extends({
|
|
89
|
-
held: false
|
|
105
|
+
held: false,
|
|
106
|
+
emptySites
|
|
90
107
|
}, result);
|
|
91
108
|
}
|
|
92
109
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-jobs-beat.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 { randomUUID } from 'crypto'\nimport { featureLockdownRefusal, firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { AI_JOB_SWEEP_BUDGET_MS, sweepAiJobs, type SweepAiJobsResult } from './ai-jobs'\n\n/**\n * Resume AI generation jobs on the AI jobs beat (AGL-2904, AGL-3026).\n *\n * A job's first step runs inline in the console route when it can; every\n * step after it, every step too long for an inline door, and any step a\n * budget cut short, runs here. The sweep bounds itself at\n * `AI_JOB_SWEEP_BUDGET_MS` of wall clock and hands the rest to the next beat\n * — the ordering of the queue is the cursor, so nothing is stored between\n * beats and nothing can be skipped.\n *\n * ## Why the console runs it\n *\n * A step calls the AI provider, and the provider's key is held by the\n * console alone: the tenant app serves every published site, and a\n * credential it holds is one request-handling bug away from a visitor. So\n * the beat is a console route (`server/ai-jobs-beat-route.ts`, registered\n * by the console surface), driven every minute by its own Cloud Scheduler\n * job in `cloud/functions` on the console's cron secret — the reason the\n * sending-domain sweep is a console route and not a job on the tenant's\n * platform beat. A beat must resolve to the minute: a step handed back by\n * a budget, or a page pass waiting on the next, should resume on the next\n * minute, not the next quarter hour.\n *\n * ## The kill switch\n *\n * `ai-generate` on the staff lockdown page is the lever for a provider\n * incident or a spend runaway on the generative doors, and this beat is the\n * one generative caller with no request to refuse. So it asks the same\n * feature verdict a door would — the platform scope and then the feature\n * document — and does nothing while either is locked. A job it leaves\n * queued stays queued: its lease is not taken, so nothing expires and\n * nothing is lost, and the first beat after the lock lifts picks it up.\n *\n * The same switch paused for ONE workspace (AGL-3037) holds that workspace's\n * jobs and no other's: `runAiJobStep` asks the verdict with the job's org\n * before it claims a step, and leaves a paused workspace's job queued.\n */\n\n/** The beat's row in `SCHEDULED_JOBS`, and the mark it leaves for `/api/health/crons`. */\nexport const AI_JOBS_BEAT_CRON_ID = 'ai-jobs-beat'\n\n/**\n * The console path the beat is registered at: the one path this plugin\n * registers outside its own prefixes. `/api/admin/` is where the console's\n * scheduled sweeps live, and the console's edge lets a request past its bot\n * challenge there when it carries the cron secret's header — a route\n * anywhere else would need a firewall rule of its own before a scheduler\n * could reach it. The console app serves this exact path from a named route\n * with the sweep's function time, so the plugin dispatcher never serves it.\n */\nexport const AI_JOBS_BEAT_PATH = 'admin/ai-jobs-beat'\n\n/** What one beat did: nothing while `ai-generate` is locked, else the sweep's account. */\nexport type AiJobsBeatResult =\n | { held: true }\n | ({ held: false } & SweepAiJobsResult)\n\n/**\n * One beat: the switch, then one sweep under its own lease owner. The
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-jobs-beat.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 { randomUUID } from 'crypto'\nimport { featureLockdownRefusal, firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { AI_JOB_SWEEP_BUDGET_MS, sweepAiJobs, type SweepAiJobsResult } from './ai-jobs'\nimport { sweepAiEmptySites, type AiEmptySiteSweepResult } from './ai-empty-site-sweep'\n\n/**\n * Resume AI generation jobs on the AI jobs beat (AGL-2904, AGL-3026).\n *\n * A job's first step runs inline in the console route when it can; every\n * step after it, every step too long for an inline door, and any step a\n * budget cut short, runs here. The sweep bounds itself at\n * `AI_JOB_SWEEP_BUDGET_MS` of wall clock and hands the rest to the next beat\n * — the ordering of the queue is the cursor, so nothing is stored between\n * beats and nothing can be skipped.\n *\n * ## Why the console runs it\n *\n * A step calls the AI provider, and the provider's key is held by the\n * console alone: the tenant app serves every published site, and a\n * credential it holds is one request-handling bug away from a visitor. So\n * the beat is a console route (`server/ai-jobs-beat-route.ts`, registered\n * by the console surface), driven every minute by its own Cloud Scheduler\n * job in `cloud/functions` on the console's cron secret — the reason the\n * sending-domain sweep is a console route and not a job on the tenant's\n * platform beat. A beat must resolve to the minute: a step handed back by\n * a budget, or a page pass waiting on the next, should resume on the next\n * minute, not the next quarter hour.\n *\n * ## The kill switch\n *\n * `ai-generate` on the staff lockdown page is the lever for a provider\n * incident or a spend runaway on the generative doors, and this beat is the\n * one generative caller with no request to refuse. So it asks the same\n * feature verdict a door would — the platform scope and then the feature\n * document — and does nothing while either is locked. A job it leaves\n * queued stays queued: its lease is not taken, so nothing expires and\n * nothing is lost, and the first beat after the lock lifts picks it up.\n *\n * The same switch paused for ONE workspace (AGL-3037) holds that workspace's\n * jobs and no other's: `runAiJobStep` asks the verdict with the job's org\n * before it claims a step, and leaves a paused workspace's job queued.\n */\n\n/** The beat's row in `SCHEDULED_JOBS`, and the mark it leaves for `/api/health/crons`. */\nexport const AI_JOBS_BEAT_CRON_ID = 'ai-jobs-beat'\n\n/**\n * The console path the beat is registered at: the one path this plugin\n * registers outside its own prefixes. `/api/admin/` is where the console's\n * scheduled sweeps live, and the console's edge lets a request past its bot\n * challenge there when it carries the cron secret's header — a route\n * anywhere else would need a firewall rule of its own before a scheduler\n * could reach it. The console app serves this exact path from a named route\n * with the sweep's function time, so the plugin dispatcher never serves it.\n */\nexport const AI_JOBS_BEAT_PATH = 'admin/ai-jobs-beat'\n\n/** What one beat did: nothing while `ai-generate` is locked, else the sweep's account. */\nexport type AiJobsBeatResult =\n | { held: true }\n | ({ held: false; emptySites: AiEmptySiteSweepResult | null } & SweepAiJobsResult)\n\n/**\n * One beat: the switch, then the empty sites a guided start left that are\n * due for removal (AGL-3936), then one sweep under its own lease owner. The\n * owner is fresh per beat and fixed for the whole sweep, so two beats\n * overlapping inside a lease never read each other's lease as their own.\n *\n * The removals come first, a few a beat inside\n * `AI_EMPTY_SITE_SWEEP_BUDGET_MS`, and whatever they took comes off the\n * sweep's budget, so the route's arithmetic inside `maxDuration` holds. A\n * removal that fails never holds up a job's step.\n */\nexport async function runAiJobsBeat(): Promise<AiJobsBeatResult> {\n const locked = await featureLockdownRefusal({ feature: 'ai-generate' })\n if (locked) {\n console.warn('ai jobs beat held: ai-generate is locked')\n return { held: true }\n }\n const firestore = firebaseAdmin.app().firestore()\n const startedAt = Date.now()\n const emptySites = await sweepAiEmptySites({ firestore }).catch((error: unknown) => {\n console.error('ai jobs beat: the empty site sweep failed', error)\n return null\n })\n if (emptySites?.removed) console.info(`ai jobs: ${emptySites.removed} empty site(s) removed`)\n const result = await sweepAiJobs({\n firestore,\n owner: `beat:${randomUUID()}`,\n budgetMs: Math.max(0, AI_JOB_SWEEP_BUDGET_MS - (Date.now() - startedAt)),\n })\n if (result.due) {\n console.info(\n `ai jobs: ${result.ran} step(s) run, ${result.skipped} skipped, ` +\n `${result.paused} held by a workspace's AI pause, ` +\n `${result.remaining} left for the next beat` +\n (result.budgetExhausted ? ' (budget exhausted)' : ''),\n )\n }\n return { held: false, emptySites, ...result }\n}\n"],"names":["randomUUID","featureLockdownRefusal","firebaseAdmin","AI_JOB_SWEEP_BUDGET_MS","sweepAiJobs","sweepAiEmptySites","AI_JOBS_BEAT_CRON_ID","AI_JOBS_BEAT_PATH","runAiJobsBeat","locked","feature","console","warn","held","firestore","app","startedAt","Date","now","emptySites","catch","error","removed","info","result","owner","budgetMs","Math","max","due","ran","skipped","paused","remaining","budgetExhausted"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,sBAAsB,EAAEC,aAAa,QAAQ,2BAA0B;AAChF,SAASC,sBAAsB,EAAEC,WAAW,QAAgC,eAAW;AACvF,SAASC,iBAAiB,QAAqC,2BAAuB;AAEtF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoCC,GAED,wFAAwF,GACxF,OAAO,MAAMC,uBAAuB,eAAc;AAElD;;;;;;;;CAQC,GACD,OAAO,MAAMC,oBAAoB,qBAAoB;AAOrD;;;;;;;;;;CAUC,GACD,OAAO,eAAeC;IACpB,MAAMC,SAAS,MAAMR,uBAAuB;QAAES,SAAS;IAAc;IACrE,IAAID,QAAQ;QACVE,QAAQC,IAAI,CAAC;QACb,OAAO;YAAEC,MAAM;QAAK;IACtB;IACA,MAAMC,YAAYZ,cAAca,GAAG,GAAGD,SAAS;IAC/C,MAAME,YAAYC,KAAKC,GAAG;IAC1B,MAAMC,aAAa,MAAMd,kBAAkB;QAAES;IAAU,GAAGM,KAAK,CAAC,CAACC;QAC/DV,QAAQU,KAAK,CAAC,6CAA6CA;QAC3D,OAAO;IACT;IACA,IAAIF,8BAA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