@aglyn/plugins-ai 1.0.0-beta.238 → 1.0.0-beta.240
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +17 -17
- package/src/lib/components/ai-job-links.js +8 -0
- package/src/lib/components/ai-job-links.js.map +1 -1
- package/src/lib/components/ai-job-requests.d.ts +5 -0
- package/src/lib/components/ai-job-requests.js +4 -2
- package/src/lib/components/ai-job-requests.js.map +1 -1
- package/src/lib/components/ai-jobs-store.d.ts +12 -0
- package/src/lib/components/ai-jobs-store.js +15 -0
- package/src/lib/components/ai-jobs-store.js.map +1 -1
- package/src/lib/components/ai-usage-meter-refresh.d.ts +35 -0
- package/src/lib/components/ai-usage-meter-refresh.js +63 -0
- package/src/lib/components/ai-usage-meter-refresh.js.map +1 -0
- package/src/lib/components/assist-panel.component.js +17 -1
- package/src/lib/components/assist-panel.component.js.map +1 -1
- package/src/lib/components/use-ai-usage-meter.d.ts +2 -0
- package/src/lib/components/use-ai-usage-meter.js +8 -3
- package/src/lib/components/use-ai-usage-meter.js.map +1 -1
- package/src/lib/jobs/ai-build-unit-outcome.d.ts +3 -1
- package/src/lib/jobs/ai-build-unit-outcome.js +19 -3
- package/src/lib/jobs/ai-build-unit-outcome.js.map +1 -1
- package/src/lib/jobs/ai-job-build-step.js +29 -2
- package/src/lib/jobs/ai-job-build-step.js.map +1 -1
- package/src/lib/jobs/ai-job-draft-ids.js +7 -2
- package/src/lib/jobs/ai-job-draft-ids.js.map +1 -1
- package/src/lib/jobs/ai-job-form-dataset.d.ts +100 -0
- package/src/lib/jobs/ai-job-form-dataset.js +161 -0
- package/src/lib/jobs/ai-job-form-dataset.js.map +1 -0
- package/src/lib/jobs/ai-job-form-step.d.ts +15 -3
- package/src/lib/jobs/ai-job-form-step.js +37 -9
- package/src/lib/jobs/ai-job-form-step.js.map +1 -1
- package/src/lib/jobs/ai-job-layout-language.js +7 -2
- package/src/lib/jobs/ai-job-layout-language.js.map +1 -1
- package/src/lib/jobs/ai-job-page-language.d.ts +9 -0
- package/src/lib/jobs/ai-job-page-language.js +44 -4
- package/src/lib/jobs/ai-job-page-language.js.map +1 -1
- package/src/lib/jobs/ai-job-page-sections.js +13 -2
- package/src/lib/jobs/ai-job-page-sections.js.map +1 -1
- package/src/lib/jobs/ai-job-page-step.js +32 -2
- package/src/lib/jobs/ai-job-page-step.js.map +1 -1
- package/src/lib/jobs/ai-job-plan-step.d.ts +18 -0
- package/src/lib/jobs/ai-job-plan-step.js +41 -4
- package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
- package/src/lib/jobs/ai-job-site-datasets.d.ts +183 -0
- package/src/lib/jobs/ai-job-site-datasets.js +530 -0
- package/src/lib/jobs/ai-job-site-datasets.js.map +1 -0
- package/src/lib/jobs/ai-job-site-step.d.ts +15 -8
- package/src/lib/jobs/ai-job-site-step.js +148 -29
- package/src/lib/jobs/ai-job-site-step.js.map +1 -1
- package/src/lib/jobs/fixtures/ai-dataset-site-plan-recordings.d.ts +30 -0
- package/src/lib/jobs/fixtures/ai-dataset-site-plan-recordings.js +637 -0
- package/src/lib/jobs/fixtures/ai-dataset-site-plan-recordings.js.map +1 -0
- package/src/lib/layout-language/ai-layout-compiler.d.ts +10 -0
- package/src/lib/layout-language/ai-layout-compiler.js +93 -1
- package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
- package/src/lib/layout-language/ai-layout-gaps.js +17 -1
- package/src/lib/layout-language/ai-layout-gaps.js.map +1 -1
- package/src/lib/layout-language/ai-layout-listings.d.ts +32 -3
- package/src/lib/layout-language/ai-layout-listings.js +62 -9
- package/src/lib/layout-language/ai-layout-listings.js.map +1 -1
- package/src/lib/layout-language/ai-layout-pictures.js +12 -4
- package/src/lib/layout-language/ai-layout-pictures.js.map +1 -1
- package/src/lib/model/ai-build-job.d.ts +2 -0
- package/src/lib/model/ai-build-job.js +16 -1
- package/src/lib/model/ai-build-job.js.map +1 -1
- package/src/lib/model/ai-build-plan.d.ts +23 -3
- package/src/lib/model/ai-build-plan.js +47 -6
- package/src/lib/model/ai-build-plan.js.map +1 -1
- package/src/lib/model/ai-plan-capabilities.d.ts +7 -0
- package/src/lib/model/ai-plan-capabilities.js.map +1 -1
- package/src/lib/model/ai-site-job.d.ts +19 -2
- package/src/lib/model/ai-site-job.js +21 -6
- package/src/lib/model/ai-site-job.js.map +1 -1
- package/src/lib/runtime/ai-dataset-generation.d.ts +77 -0
- package/src/lib/runtime/ai-dataset-generation.js +127 -0
- package/src/lib/runtime/ai-dataset-generation.js.map +1 -0
- package/src/lib/runtime/ai-doctrine-validators.d.ts +84 -0
- package/src/lib/runtime/ai-doctrine-validators.js +307 -1
- package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
- package/src/lib/runtime/ai-doctrine.js +10 -4
- package/src/lib/runtime/ai-doctrine.js.map +1 -1
- package/src/lib/runtime/ai-node-tree.d.ts +2 -0
- package/src/lib/runtime/ai-node-tree.js +16 -0
- package/src/lib/runtime/ai-node-tree.js.map +1 -1
- package/src/lib/tools/ai-dataset-tool.d.ts +68 -0
- package/src/lib/tools/ai-dataset-tool.js +231 -0
- package/src/lib/tools/ai-dataset-tool.js.map +1 -0
- package/src/lib/usage/free-ai-credits-left.js +26 -2
- package/src/lib/usage/free-ai-credits-left.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/layout-language/ai-layout-pictures.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DEFAULT_SITE_IMAGES } from '@aglyn/aglyn/app-utils/default-site'\nimport type { NodesMap } from '@aglyn/aglyn/types/nodes'\n\n/**\n * THE PICTURES OF A LANGUAGE PAGE (AGL-3660).\n *\n * The compiler writes a picture slot as a frame holding an icon and an\n * `image` with alt text and no source (`ai-layout-compiler.ts`), and stays\n * pure: it never looks a photo up. This module is what runs after it, on the\n * stored page — it finds each empty slot, decides what kind of picture the\n * slot is, and fills it with a photo the site can serve from its own origin.\n *\n * Two sources fill a slot, in order:\n *\n * 1. A stock photo searched for by the slot's own description and copied into\n * the site's media library (`jobs/ai-layout-stock-photos.ts`), when the\n * deployment has a stock-photo key.\n * 2. Otherwise, or when the search finds nothing fitting, one of the STARTER\n * PHOTOS every new site is born with (`DEFAULT_SITE_IMAGES`, served at\n * `/_static/starter/` by the tenant and the console alike, credited in the\n * CREDITS file beside them). They are the platform's own files, so a\n * visitor's browser asks no other host for them.\n *\n * The slot keeps the alt text the model wrote whichever source fills it.\n */\n\n/** What a picture slot is for, read from where it sits and what it says. */\nexport type AiLayoutPictureRole = 'hero' | 'about' | 'gallery'\n\n/** One empty picture slot of a stored page, in document order. */\nexport interface AiLayoutPictureSlot {\n /** The `image` node. */\n imageId: string\n /** The frame around it, which sets the slot's shape. */\n frameId: string | null\n /** The placeholder icon sharing the frame, taken out once a photo fills it. */\n iconId: string | null\n alt: string\n /** The frame's shape as width over height; 1 when it names none. */\n aspect: number\n /** The plan index of the section it sits in, or -1. */\n sectionIndex: number\n role: AiLayoutPictureRole\n /**\n * A product's photo (AGL-3676): what it is of, most specific first — its\n * name, then what its photo should show — searched for with the shop's\n * category and held to it, so a wick trimmer is never a laptop on a desk.\n */\n product?: { subjects: readonly string[] }\n}\n\n/** A photo a slot is filled with. */\nexport interface AiLayoutPicturePhoto {\n /** The site-served address: a starter path or the media library's own. */\n src: string\n width: number\n height: number\n}\n\n/** Words that say a picture shows people, or a section is about them. */\nconst PEOPLE =\n /\\b(about|team|story|owner|owners|founder|founders|staff|crew|people|person|portrait|meet|family|families|who we are|our (?:team|crew|people|story)|therapist|counsel(?:l)?or|coach|doctor|dentist|stylist|trainer|smil(?:e|es|ing)|headshot)\\b/i\n\n/**\n * An `aspectRatio` (`'16 / 9'`) as a number, or `null` where none is named.\n * A responsive one (`{ xs: '4 / 3', md: '4 / 5' }`, as a designed page's\n * pictures carry, AGL-3660) reads at the desktop breakpoint first: one photo\n * serves every width, and the wide screen is where its shape shows most.\n */\nfunction aspectOf(value: unknown): number | null {\n if (value && typeof value === 'object') {\n const byBreakpoint = value as Record<string, unknown>\n for (const breakpoint of ['md', 'lg', 'xl', 'sm', 'xs']) {\n const ratio = aspectOf(byBreakpoint[breakpoint])\n if (ratio !== null) return ratio\n }\n return null\n }\n const match = /^\\s*(\\d+(?:\\.\\d+)?)\\s*\\/\\s*(\\d+(?:\\.\\d+)?)\\s*$/.exec(String(value ?? ''))\n if (!match) return null\n const ratio = Number(match[1]) / Number(match[2])\n return Number.isFinite(ratio) && ratio > 0 ? ratio : null\n}\n\n/** The shape a full-bleed cover's photo is searched for: it fills a wide band. */\nconst COVER_ASPECT = 16 / 9\n\n/**\n * A slot's shape (AGL-3660): the image's own `aspectRatio` (a designed\n * picture card sets it on the image), else its frame's, else — for a frame\n * laid absolutely over its whole section, a designed photo cover — a wide\n * band's. 1 where nothing says.\n */\nfunction slotAspect(image: { sx?: Record<string, unknown> } | undefined, frame: { sx?: Record<string, unknown> } | undefined): number {\n const own = aspectOf(image?.sx?.['aspectRatio']) ?? aspectOf(frame?.sx?.['aspectRatio'])\n if (own !== null) return own\n const sx = frame?.sx\n if (sx?.['position'] === 'absolute' && sx['width'] === '100%' && sx['height'] === '100%') return COVER_ASPECT\n return 1\n}\n\n/** A slot's role: the first section's picture is the hero; people make an about picture. */\nexport function aiLayoutPictureRole(input: {\n sectionIndex: number\n sectionName: string\n alt: string\n}): AiLayoutPictureRole {\n if (input.sectionIndex === 0) return 'hero'\n if (PEOPLE.test(input.sectionName) || PEOPLE.test(input.alt)) return 'about'\n return 'gallery'\n}\n\n/**\n * Every empty picture slot of a stored page, walked from its root in\n * document order. A slot that already has a source — one the owner placed, or\n * an earlier pass filled — is not a slot.\n */\nexport function aiLayoutPictureSlots(\n nodes: NodesMap,\n rootId: string,\n sections: { ids: readonly string[]; names: readonly string[] },\n): AiLayoutPictureSlot[] {\n const map = nodes as unknown as Record<\n string,\n { componentId?: string; props?: Record<string, unknown>; sx?: Record<string, unknown>; nodes?: string[] }\n >\n const slots: AiLayoutPictureSlot[] = []\n const seen = new Set<string>()\n const visit = (id: string, parentId: string | null, sectionIndex: number) => {\n if (seen.has(id)) return\n seen.add(id)\n const node = map[id]\n if (!node) return\n const index = sections.ids.indexOf(id)\n const here = index >= 0 ? index : sectionIndex\n if (node.componentId === 'image') {\n const src = node.props?.['src']\n const alt = typeof node.props?.['alt'] === 'string' ? (node.props['alt'] as string).trim() : ''\n if ((typeof src !== 'string' || !src.trim()) && alt) {\n const frame = parentId ? map[parentId] : undefined\n const iconId =\n frame?.nodes?.find((child) => child !== id && map[child]?.componentId === 'icon') ?? null\n slots.push({\n imageId: id,\n frameId: frame ? parentId : null,\n iconId,\n alt,\n aspect: slotAspect(node, frame),\n sectionIndex: here,\n role: aiLayoutPictureRole({\n sectionIndex: here,\n sectionName: here >= 0 ? (sections.names[here] ?? '') : '',\n alt,\n }),\n })\n }\n }\n for (const child of node.nodes ?? []) visit(child, id, here)\n }\n visit(rootId, null, -1)\n return slots\n}\n\n/** The starter photos, by name. */\nexport const AI_LAYOUT_STARTER_PHOTOS = DEFAULT_SITE_IMAGES\n\ntype StarterName = keyof typeof AI_LAYOUT_STARTER_PHOTOS\n\n/**\n * The starter photos each role draws from, best first. A hero draws from the\n * wide photos that read as a page's opening, an about picture leads with the\n * owner, and the rest are the gallery's.\n */\nconst STARTER_POOLS: Readonly<Record<AiLayoutPictureRole, readonly StarterName[]>> = {\n hero: ['hero', 'desk', 'craft'],\n about: ['about', 'hero'],\n gallery: ['desk', 'plants', 'craft'],\n}\n\nconst ALL_STARTERS = Object.keys(AI_LAYOUT_STARTER_PHOTOS) as StarterName[]\n\n/** A small stable number from a seed, so the same job always picks the same photos. */\nexport function aiLayoutSeedNumber(seed: string): number {\n let hash = 2166136261\n for (let index = 0; index < seed.length; index += 1) {\n hash ^= seed.charCodeAt(index)\n hash = Math.imul(hash, 16777619)\n }\n return hash >>> 0\n}\n\nfunction rotate<T>(list: readonly T[], by: number): T[] {\n if (!list.length) return []\n const start = by % list.length\n return [...list.slice(start), ...list.slice(0, start)]\n}\n\n/**\n * A starter photo for each slot (AGL-3660). No photo repeats on a page while\n * an unused one remains, and every pool turns by the seed, so sites do not\n * all open with the same photo while one job always picks the same.\n *\n * The slots are served by what they are for, not where they sit: the hero\n * first, then the pictures of people (an about picture leads with the owner),\n * then the rest. The live Juniper Clay start (2026-10-08) had six slots and\n * five starters, and the owner's photo went to a stoneware card before the\n * About section that described the artist asked for it. Only a page with more\n * slots than starters repeats one: the photo placed longest ago, never the\n * one in a slot beside it. The owner's portrait goes only to a picture of\n * people; a gallery picture never takes it, even to avoid a repeat.\n */\nexport function aiLayoutStarterPhotos(\n slots: readonly AiLayoutPictureSlot[],\n seed: string,\n): AiLayoutPicturePhoto[] {\n const turn = aiLayoutSeedNumber(seed)\n const order: AiLayoutPictureRole[] = ['hero', 'about', 'gallery']\n const served = slots\n .map((slot, index) => ({ slot, index }))\n .sort((a, b) => order.indexOf(a.slot.role) - order.indexOf(b.slot.role) || a.index - b.index)\n const names: Array<StarterName | undefined> = slots.map(() => undefined)\n /** When each starter was last placed, by its turn in the serving order. */\n const placedAt = new Map<StarterName, number>()\n served.forEach(({ slot, index }, step) => {\n // An about picture leads with the owner on every site; the others turn.\n const pool = slot.role === 'about' ? [...STARTER_POOLS.about] : rotate(STARTER_POOLS[slot.role], turn)\n const rest = rotate(\n ALL_STARTERS.filter((name) => !pool.includes(name)),\n turn,\n )\n // The owner's portrait is a picture of a person, and only a picture of\n // people takes it: never a vase in a gallery (AGL-3660).\n const candidates = [...pool, ...rest].filter((name) => slot.role === 'about' || name !== 'about')\n const unused = candidates.find((candidate) => !placedAt.has(candidate))\n const beside = new Set([names[index - 1], names[index + 1]].filter(Boolean))\n const name =\n unused ??\n [...candidates]\n .sort((a, b) => (placedAt.get(a) ?? -1) - (placedAt.get(b) ?? -1))\n .find((candidate) => !beside.has(candidate)) ??\n candidates[0]\n names[index] = name\n placedAt.set(name, step)\n })\n return names.map((name) => {\n const photo = AI_LAYOUT_STARTER_PHOTOS[name as StarterName]\n return { src: photo.src, width: photo.width, height: photo.height }\n })\n}\n\n/**\n * The page with each slot filled by its photo: the `image` given its source,\n * its intrinsic size and how it loads (the hero eagerly, as the starter home\n * page loads its own), and the placeholder icon taken out of the frame. The\n * alt text is kept as the model wrote it. A slot given no photo is left as\n * the compiler wrote it.\n */\nexport function aiLayoutPlacePictures(\n nodes: NodesMap,\n slots: readonly AiLayoutPictureSlot[],\n photos: ReadonlyArray<AiLayoutPicturePhoto | null>,\n): NodesMap {\n const next = { ...(nodes as unknown as Record<string, Record<string, unknown>>) }\n slots.forEach((slot, index) => {\n const photo = photos[index]\n const node = next[slot.imageId]\n if (!photo || !node) return\n next[slot.imageId] = {\n ...node,\n props: {\n ...((node['props'] as Record<string, unknown> | undefined) ?? {}),\n src: photo.src,\n intrinsicWidth: photo.width,\n intrinsicHeight: photo.height,\n loading: slot.role === 'hero' ? 'eager' : 'lazy',\n },\n }\n if (slot.iconId && slot.frameId && next[slot.frameId]) {\n const frame = next[slot.frameId]\n next[slot.frameId] = {\n ...frame,\n nodes: ((frame['nodes'] as string[] | undefined) ?? []).filter((child) => child !== slot.iconId),\n }\n delete next[slot.iconId]\n }\n })\n return next as unknown as NodesMap\n}\n\n/**\n * A source of photos found for the slots themselves — a stock search copied\n * into the site's library — answering one photo or `null` per slot, in order.\n * It may throw; a slot it leaves unfilled takes a starter photo.\n */\nexport type AiLayoutPictureSource = (\n slots: readonly AiLayoutPictureSlot[],\n) => Promise<ReadonlyArray<AiLayoutPicturePhoto | null>>\n\n/**\n * Fills a stored page's empty picture slots (AGL-3660): from `source` where\n * one is given and it answers, else from the starter photos. Never throws,\n * and never leaves a page worse than it came: a picture is decoration, and a\n * job never fails over one.\n */\nexport async function aiResolveLayoutPictures(\n nodes: NodesMap,\n input: {\n rootId: string\n sectionIds: readonly string[]\n sectionNames: readonly string[]\n /** A per-job word, so two sites do not open with the same photo. */\n seed: string\n source?: AiLayoutPictureSource | null\n },\n): Promise<NodesMap> {\n try {\n const slots = aiLayoutPictureSlots(nodes, input.rootId, {\n ids: input.sectionIds,\n names: input.sectionNames,\n })\n if (!slots.length) return nodes\n let found: ReadonlyArray<AiLayoutPicturePhoto | null> = []\n if (input.source) {\n try {\n found = await input.source(slots)\n } catch (error) {\n console.warn('ai layout pictures: the stock source failed; starter photos fill the page', { error })\n found = []\n }\n }\n const starters = aiLayoutStarterPhotos(slots, input.seed)\n return aiLayoutPlacePictures(\n nodes,\n slots,\n slots.map((_slot, index) => found[index] ?? starters[index]),\n )\n } catch (error) {\n console.error('ai layout pictures: the page keeps its empty picture slots', { error })\n return nodes\n }\n}\n"],"names":["DEFAULT_SITE_IMAGES","PEOPLE","aspectOf","value","byBreakpoint","breakpoint","ratio","match","exec","String","Number","isFinite","COVER_ASPECT","slotAspect","image","frame","own","sx","aiLayoutPictureRole","input","sectionIndex","test","sectionName","alt","aiLayoutPictureSlots","nodes","rootId","sections","map","slots","seen","Set","visit","id","parentId","node","has","add","index","ids","indexOf","here","componentId","src","props","trim","undefined","iconId","find","child","push","imageId","frameId","aspect","role","names","AI_LAYOUT_STARTER_PHOTOS","STARTER_POOLS","hero","about","gallery","ALL_STARTERS","Object","keys","aiLayoutSeedNumber","seed","hash","length","charCodeAt","Math","imul","rotate","list","by","start","slice","aiLayoutStarterPhotos","turn","order","served","slot","sort","a","b","placedAt","Map","forEach","step","unused","pool","rest","filter","name","includes","candidates","candidate","beside","Boolean","get","set","photo","width","height","aiLayoutPlacePictures","photos","next","intrinsicWidth","intrinsicHeight","loading","aiResolveLayoutPictures","sectionIds","sectionNames","found","source","error","console","warn","starters","_slot"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,sCAAqC;AA2DzE,uEAAuE,GACvE,MAAMC,SACJ;AAEF;;;;;CAKC,GACD,SAASC,SAASC,KAAc;IAC9B,IAAIA,SAAS,OAAOA,UAAU,UAAU;QACtC,MAAMC,eAAeD;QACrB,KAAK,MAAME,cAAc;YAAC;YAAM;YAAM;YAAM;YAAM;SAAK,CAAE;YACvD,MAAMC,QAAQJ,SAASE,YAAY,CAACC,WAAW;YAC/C,IAAIC,UAAU,MAAM,OAAOA;QAC7B;QACA,OAAO;IACT;IACA,MAAMC,QAAQ,iDAAiDC,IAAI,CAACC,OAAON,gBAAAA,QAAS;IACpF,IAAI,CAACI,OAAO,OAAO;IACnB,MAAMD,QAAQI,OAAOH,KAAK,CAAC,EAAE,IAAIG,OAAOH,KAAK,CAAC,EAAE;IAChD,OAAOG,OAAOC,QAAQ,CAACL,UAAUA,QAAQ,IAAIA,QAAQ;AACvD;AAEA,gFAAgF,GAChF,MAAMM,eAAe,KAAK;AAE1B;;;;;CAKC,GACD,SAASC,WAAWC,KAAmD,EAAEC,KAAmD;QAC9Gb;QAASY,WAAwCC;IAA7D,MAAMC,OAAMd,YAAAA,SAASY,0BAAAA,YAAAA,MAAOG,EAAE,qBAATH,SAAW,CAAC,cAAc,aAAnCZ,YAAwCA,SAASa,0BAAAA,YAAAA,MAAOE,EAAE,qBAATF,SAAW,CAAC,cAAc;IACvF,IAAIC,QAAQ,MAAM,OAAOA;IACzB,MAAMC,KAAKF,yBAAAA,MAAOE,EAAE;IACpB,IAAIA,CAAAA,sBAAAA,EAAI,CAAC,WAAW,MAAK,cAAcA,EAAE,CAAC,QAAQ,KAAK,UAAUA,EAAE,CAAC,SAAS,KAAK,QAAQ,OAAOL;IACjG,OAAO;AACT;AAEA,0FAA0F,GAC1F,OAAO,SAASM,oBAAoBC,KA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zB,KAAK5B,OAAO,CAAC,GAAG,aAChBrC;gBACHU,OAAO,EAAEV,eAAAA,KAAK,CAAC,QAAQ,YAAdA,eAA2C,EAAE,EAAE4E,MAAM,CAAC,CAAC1C,QAAUA,UAAU+B,KAAKjC,MAAM;;YAEjG,OAAO0D,IAAI,CAACzB,KAAKjC,MAAM,CAAC;QAC1B;IACF;IACA,OAAO0D;AACT;AAWA;;;;;CAKC,GACD,OAAO,eAAeI,wBACpBpF,KAAe,EACfN,KAOC;IAED,IAAI;QACF,MAAMU,QAAQL,qBAAqBC,OAAON,MAAMO,MAAM,EAAE;YACtDa,KAAKpB,MAAM2F,UAAU;YACrBvD,OAAOpC,MAAM4F,YAAY;QAC3B;QACA,IAAI,CAAClF,MAAMsC,MAAM,EAAE,OAAO1C;QAC1B,IAAIuF,QAAoD,EAAE;QAC1D,IAAI7F,MAAM8F,MAAM,EAAE;YAChB,IAAI;gBACFD,QAAQ,MAAM7F,MAAM8F,MAAM,CAACpF;YAC7B,EAAE,OAAOqF,OAAO;gBACdC,QAAQC,IAAI,CAAC,6EAA6E;oBAAEF;gBAAM;gBAClGF,QAAQ,EAAE;YACZ;QACF;QACA,MAAMK,WAAWzC,sBAAsB/C,OAAOV,MAAM8C,IAAI;QACxD,OAAOsC,sBACL9E,OACAI,OACAA,MAAMD,GAAG,CAAC,CAAC0F,OAAOhF;gBAAU0E;oBAAAA,eAAAA,KAAK,CAAC1E,MAAM,YAAZ0E,eAAgBK,QAAQ,CAAC/E,MAAM;;IAE/D,EAAE,OAAO4E,OAAO;QACdC,QAAQD,KAAK,CAAC,8DAA8D;YAAEA;QAAM;QACpF,OAAOzF;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/layout-language/ai-layout-pictures.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DEFAULT_SITE_IMAGES } from '@aglyn/aglyn/app-utils/default-site'\nimport type { NodesMap } from '@aglyn/aglyn/types/nodes'\n\n/**\n * THE PICTURES OF A LANGUAGE PAGE (AGL-3660).\n *\n * The compiler writes a picture slot as a frame holding an icon and an\n * `image` with alt text and no source (`ai-layout-compiler.ts`), and stays\n * pure: it never looks a photo up. This module is what runs after it, on the\n * stored page — it finds each empty slot, decides what kind of picture the\n * slot is, and fills it with a photo the site can serve from its own origin.\n *\n * Two sources fill a slot, in order:\n *\n * 1. A stock photo searched for by the slot's own description and copied into\n * the site's media library (`jobs/ai-layout-stock-photos.ts`), when the\n * deployment has a stock-photo key.\n * 2. Otherwise, or when the search finds nothing fitting, one of the STARTER\n * PHOTOS every new site is born with (`DEFAULT_SITE_IMAGES`, served at\n * `/_static/starter/` by the tenant and the console alike, credited in the\n * CREDITS file beside them). They are the platform's own files, so a\n * visitor's browser asks no other host for them.\n *\n * The slot keeps the alt text the model wrote whichever source fills it.\n */\n\n/** What a picture slot is for, read from where it sits and what it says. */\nexport type AiLayoutPictureRole = 'hero' | 'about' | 'gallery'\n\n/** One empty picture slot of a stored page, in document order. */\nexport interface AiLayoutPictureSlot {\n /** The `image` node. */\n imageId: string\n /** The frame around it, which sets the slot's shape. */\n frameId: string | null\n /** The placeholder icon sharing the frame, taken out once a photo fills it. */\n iconId: string | null\n alt: string\n /** The frame's shape as width over height; 1 when it names none. */\n aspect: number\n /** The plan index of the section it sits in, or -1. */\n sectionIndex: number\n role: AiLayoutPictureRole\n /**\n * A product's photo (AGL-3676): what it is of, most specific first — its\n * name, then what its photo should show — searched for with the shop's\n * category and held to it, so a wick trimmer is never a laptop on a desk.\n */\n product?: { subjects: readonly string[] }\n}\n\n/** A photo a slot is filled with. */\nexport interface AiLayoutPicturePhoto {\n /** The site-served address: a starter path or the media library's own. */\n src: string\n width: number\n height: number\n}\n\n/** Words that say a picture shows people, or a section is about them. */\nconst PEOPLE =\n /\\b(about|team|story|owner|owners|founder|founders|staff|crew|people|person|portrait|meet|family|families|who we are|our (?:team|crew|people|story)|therapist|counsel(?:l)?or|coach|doctor|dentist|stylist|trainer|smil(?:e|es|ing)|headshot)\\b/i\n\n/**\n * An `aspectRatio` (`'16 / 9'`) as a number, or `null` where none is named.\n * A responsive one (`{ xs: '4 / 3', md: '4 / 5' }`, as a designed page's\n * pictures carry, AGL-3660) reads at the desktop breakpoint first: one photo\n * serves every width, and the wide screen is where its shape shows most.\n */\nfunction aspectOf(value: unknown): number | null {\n if (value && typeof value === 'object') {\n const byBreakpoint = value as Record<string, unknown>\n for (const breakpoint of ['md', 'lg', 'xl', 'sm', 'xs']) {\n const ratio = aspectOf(byBreakpoint[breakpoint])\n if (ratio !== null) return ratio\n }\n return null\n }\n const match = /^\\s*(\\d+(?:\\.\\d+)?)\\s*\\/\\s*(\\d+(?:\\.\\d+)?)\\s*$/.exec(String(value ?? ''))\n if (!match) return null\n const ratio = Number(match[1]) / Number(match[2])\n return Number.isFinite(ratio) && ratio > 0 ? ratio : null\n}\n\n/** The shape a full-bleed cover's photo is searched for: it fills a wide band. */\nconst COVER_ASPECT = 16 / 9\n\n/**\n * A slot's shape (AGL-3660): the image's own `aspectRatio` (a designed\n * picture card sets it on the image), else its frame's, else — for a frame\n * laid absolutely over its whole section, a designed photo cover — a wide\n * band's. 1 where nothing says.\n */\nfunction slotAspect(image: { sx?: Record<string, unknown> } | undefined, frame: { sx?: Record<string, unknown> } | undefined): number {\n const own = aspectOf(image?.sx?.['aspectRatio']) ?? aspectOf(frame?.sx?.['aspectRatio'])\n if (own !== null) return own\n const sx = frame?.sx\n if (sx?.['position'] === 'absolute' && sx['width'] === '100%' && sx['height'] === '100%') return COVER_ASPECT\n return 1\n}\n\n/** A slot's role: the first section's picture is the hero; people make an about picture. */\nexport function aiLayoutPictureRole(input: {\n sectionIndex: number\n sectionName: string\n alt: string\n}): AiLayoutPictureRole {\n if (input.sectionIndex === 0) return 'hero'\n if (PEOPLE.test(input.sectionName) || PEOPLE.test(input.alt)) return 'about'\n return 'gallery'\n}\n\n/**\n * Every empty picture slot of a stored page, walked from its root in\n * document order. A slot that already has a source — one the owner placed, or\n * an earlier pass filled — is not a slot.\n */\nexport function aiLayoutPictureSlots(\n nodes: NodesMap,\n rootId: string,\n sections: { ids: readonly string[]; names: readonly string[] },\n): AiLayoutPictureSlot[] {\n const map = nodes as unknown as Record<\n string,\n { componentId?: string; props?: Record<string, unknown>; sx?: Record<string, unknown>; nodes?: string[] }\n >\n const slots: AiLayoutPictureSlot[] = []\n const seen = new Set<string>()\n const visit = (id: string, parentId: string | null, sectionIndex: number) => {\n if (seen.has(id)) return\n seen.add(id)\n const node = map[id]\n if (!node) return\n const index = sections.ids.indexOf(id)\n const here = index >= 0 ? index : sectionIndex\n if (node.componentId === 'image') {\n const src = node.props?.['src']\n const alt = typeof node.props?.['alt'] === 'string' ? (node.props['alt'] as string).trim() : ''\n if ((typeof src !== 'string' || !src.trim()) && alt) {\n const frame = parentId ? map[parentId] : undefined\n const iconId =\n frame?.nodes?.find((child) => child !== id && map[child]?.componentId === 'icon') ?? null\n slots.push({\n imageId: id,\n frameId: frame ? parentId : null,\n iconId,\n alt,\n aspect: slotAspect(node, frame),\n sectionIndex: here,\n role: aiLayoutPictureRole({\n sectionIndex: here,\n sectionName: here >= 0 ? (sections.names[here] ?? '') : '',\n alt,\n }),\n })\n }\n }\n for (const child of node.nodes ?? []) visit(child, id, here)\n }\n visit(rootId, null, -1)\n return slots\n}\n\n/** The starter photos, by name. */\nexport const AI_LAYOUT_STARTER_PHOTOS = DEFAULT_SITE_IMAGES\n\ntype StarterName = keyof typeof AI_LAYOUT_STARTER_PHOTOS\n\n/**\n * The starter photos each role draws from, best first. A hero draws from the\n * wide photos that read as a page's opening, an about picture leads with the\n * owner, and the rest are the gallery's.\n */\nconst STARTER_POOLS: Readonly<Record<AiLayoutPictureRole, readonly StarterName[]>> = {\n hero: ['hero', 'desk', 'craft'],\n about: ['about', 'hero'],\n gallery: ['desk', 'plants', 'craft'],\n}\n\nconst ALL_STARTERS = Object.keys(AI_LAYOUT_STARTER_PHOTOS) as StarterName[]\n\n/** A small stable number from a seed, so the same job always picks the same photos. */\nexport function aiLayoutSeedNumber(seed: string): number {\n let hash = 2166136261\n for (let index = 0; index < seed.length; index += 1) {\n hash ^= seed.charCodeAt(index)\n hash = Math.imul(hash, 16777619)\n }\n return hash >>> 0\n}\n\nfunction rotate<T>(list: readonly T[], by: number): T[] {\n if (!list.length) return []\n const start = by % list.length\n return [...list.slice(start), ...list.slice(0, start)]\n}\n\n/**\n * A starter photo for each slot (AGL-3660). No photo repeats on a page while\n * an unused one remains, and every pool turns by the seed, so sites do not\n * all open with the same photo while one job always picks the same.\n *\n * The slots are served by what they are for, not where they sit: the hero\n * first, then the pictures of people (an about picture leads with the owner),\n * then the rest. The live Juniper Clay start (2026-10-08) had six slots and\n * five starters, and the owner's photo went to a stoneware card before the\n * About section that described the artist asked for it. Only a page with more\n * slots than starters repeats one: the photo placed longest ago, never the\n * one in a slot beside it. The owner's portrait goes only to a picture of\n * people; a gallery picture never takes it, even to avoid a repeat.\n */\nexport function aiLayoutStarterPhotos(\n slots: readonly AiLayoutPictureSlot[],\n seed: string,\n): AiLayoutPicturePhoto[] {\n const turn = aiLayoutSeedNumber(seed)\n const order: AiLayoutPictureRole[] = ['hero', 'about', 'gallery']\n const served = slots\n .map((slot, index) => ({ slot, index }))\n .sort((a, b) => order.indexOf(a.slot.role) - order.indexOf(b.slot.role) || a.index - b.index)\n const names: Array<StarterName | undefined> = slots.map(() => undefined)\n /** When each starter was last placed, by its turn in the serving order. */\n const placedAt = new Map<StarterName, number>()\n served.forEach(({ slot, index }, step) => {\n // An about picture leads with the owner on every site; the others turn.\n const pool = slot.role === 'about' ? [...STARTER_POOLS.about] : rotate(STARTER_POOLS[slot.role], turn)\n const rest = rotate(\n ALL_STARTERS.filter((name) => !pool.includes(name)),\n turn,\n )\n // The owner's portrait is a picture of a person, and only a picture of\n // people takes it: never a vase in a gallery (AGL-3660).\n const candidates = [...pool, ...rest].filter((name) => slot.role === 'about' || name !== 'about')\n const unused = candidates.find((candidate) => !placedAt.has(candidate))\n const beside = new Set([names[index - 1], names[index + 1]].filter(Boolean))\n const name =\n unused ??\n [...candidates]\n .sort((a, b) => (placedAt.get(a) ?? -1) - (placedAt.get(b) ?? -1))\n .find((candidate) => !beside.has(candidate)) ??\n candidates[0]\n names[index] = name\n placedAt.set(name, step)\n })\n return names.map((name) => {\n const photo = AI_LAYOUT_STARTER_PHOTOS[name as StarterName]\n return { src: photo.src, width: photo.width, height: photo.height }\n })\n}\n\n/**\n * The page with each slot filled by its photo: the `image` given its source,\n * its intrinsic size and how it loads (the hero eagerly, as the starter home\n * page loads its own), and the placeholder icon taken out of the frame. The\n * alt text is kept as the model wrote it. A slot given no photo is left as\n * the compiler wrote it.\n */\nexport function aiLayoutPlacePictures(\n nodes: NodesMap,\n slots: readonly AiLayoutPictureSlot[],\n photos: ReadonlyArray<AiLayoutPicturePhoto | null>,\n): NodesMap {\n const next = { ...(nodes as unknown as Record<string, Record<string, unknown>>) }\n // Only the page's first picture loads eagerly (rule 16, AGL-3660): a hero\n // of several photos loaded them all eagerly, and a live Portfolio page was\n // refused for it (2026-10-10). The slots are in document order; every later\n // picture leaves `loading` unset, which the renderer loads when reached.\n const lead = slots.findIndex((_, index) => Boolean(photos[index] && next[slots[index].imageId]))\n slots.forEach((slot, index) => {\n const photo = photos[index]\n const node = next[slot.imageId]\n if (!photo || !node) return\n const props = { ...((node['props'] as Record<string, unknown> | undefined) ?? {}) }\n delete props['loading']\n next[slot.imageId] = {\n ...node,\n props: {\n ...props,\n src: photo.src,\n intrinsicWidth: photo.width,\n intrinsicHeight: photo.height,\n ...(index === lead && slot.role === 'hero' ? { loading: 'eager' } : {}),\n },\n }\n if (slot.iconId && slot.frameId && next[slot.frameId]) {\n const frame = next[slot.frameId]\n next[slot.frameId] = {\n ...frame,\n nodes: ((frame['nodes'] as string[] | undefined) ?? []).filter((child) => child !== slot.iconId),\n }\n delete next[slot.iconId]\n }\n })\n return next as unknown as NodesMap\n}\n\n/**\n * A source of photos found for the slots themselves — a stock search copied\n * into the site's library — answering one photo or `null` per slot, in order.\n * It may throw; a slot it leaves unfilled takes a starter photo.\n */\nexport type AiLayoutPictureSource = (\n slots: readonly AiLayoutPictureSlot[],\n) => Promise<ReadonlyArray<AiLayoutPicturePhoto | null>>\n\n/**\n * Fills a stored page's empty picture slots (AGL-3660): from `source` where\n * one is given and it answers, else from the starter photos. Never throws,\n * and never leaves a page worse than it came: a picture is decoration, and a\n * job never fails over one.\n */\nexport async function aiResolveLayoutPictures(\n nodes: NodesMap,\n input: {\n rootId: string\n sectionIds: readonly string[]\n sectionNames: readonly string[]\n /** A per-job word, so two sites do not open with the same photo. */\n seed: string\n source?: AiLayoutPictureSource | null\n },\n): Promise<NodesMap> {\n try {\n const slots = aiLayoutPictureSlots(nodes, input.rootId, {\n ids: input.sectionIds,\n names: input.sectionNames,\n })\n if (!slots.length) return nodes\n let found: ReadonlyArray<AiLayoutPicturePhoto | null> = []\n if (input.source) {\n try {\n found = await input.source(slots)\n } catch (error) {\n console.warn('ai layout pictures: the stock source failed; starter photos fill the page', { error })\n found = []\n }\n }\n const starters = aiLayoutStarterPhotos(slots, input.seed)\n return aiLayoutPlacePictures(\n nodes,\n slots,\n slots.map((_slot, index) => found[index] ?? starters[index]),\n )\n } catch (error) {\n console.error('ai layout pictures: the page keeps its empty picture slots', { error })\n return nodes\n }\n}\n"],"names":["DEFAULT_SITE_IMAGES","PEOPLE","aspectOf","value","byBreakpoint","breakpoint","ratio","match","exec","String","Number","isFinite","COVER_ASPECT","slotAspect","image","frame","own","sx","aiLayoutPictureRole","input","sectionIndex","test","sectionName","alt","aiLayoutPictureSlots","nodes","rootId","sections","map","slots","seen","Set","visit","id","parentId","node","has","add","index","ids","indexOf","here","componentId","src","props","trim","undefined","iconId","find","child","push","imageId","frameId","aspect","role","names","AI_LAYOUT_STARTER_PHOTOS","STARTER_POOLS","hero","about","gallery","ALL_STARTERS","Object","keys","aiLayoutSeedNumber","seed","hash","length","charCodeAt","Math","imul","rotate","list","by","start","slice","aiLayoutStarterPhotos","turn","order","served","slot","sort","a","b","placedAt","Map","forEach","step","unused","pool","rest","filter","name","includes","candidates","candidate","beside","Boolean","get","set","photo","width","height","aiLayoutPlacePictures","photos","next","lead","findIndex","_","intrinsicWidth","intrinsicHeight","loading","aiResolveLayoutPictures","sectionIds","sectionNames","found","source","error","console","warn","starters","_slot"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,sCAAqC;AA2DzE,uEAAuE,GACvE,MAAMC,SACJ;AAEF;;;;;CAKC,GACD,SAASC,SAASC,KAAc;IAC9B,IAAIA,SAAS,OAAOA,UAAU,UAAU;QACtC,MAAMC,eAAeD;QACrB,KAAK,MAAME,cAAc;YAAC;YAAM;YAAM;YAAM;YAAM;SAAK,CAAE;YACvD,MAAMC,QAAQJ,SAASE,YAAY,CAACC,WAAW;YAC/C,IAAIC,UAAU,MAAM,OAAOA;QAC7B;QACA,OAAO;IACT;IACA,MAAMC,QAAQ,iDAAiDC,IAAI,CAACC,OAAON,gBAAAA,QAAS;IACpF,IAAI,CAACI,OAAO,OAAO;IACnB,MAAMD,QAAQI,OAAOH,KAAK,CAAC,EAAE,IAAIG,OAAOH,KAAK,CAAC,EAAE;IAChD,OAAOG,OAAOC,QAAQ,CAACL,UAAUA,QAAQ,IAAIA,QAAQ;AACvD;AAEA,gFAAgF,GAChF,MAAMM,eAAe,KAAK;AAE1B;;;;;CAKC,GACD,SAASC,WAAWC,KAAmD,EAAEC,KAAmD;QAC9Gb;QAASY,WAAwCC;IA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QAC1B,IAAI0F,QAAoD,EAAE;QAC1D,IAAIhG,MAAMiG,MAAM,EAAE;YAChB,IAAI;gBACFD,QAAQ,MAAMhG,MAAMiG,MAAM,CAACvF;YAC7B,EAAE,OAAOwF,OAAO;gBACdC,QAAQC,IAAI,CAAC,6EAA6E;oBAAEF;gBAAM;gBAClGF,QAAQ,EAAE;YACZ;QACF;QACA,MAAMK,WAAW5C,sBAAsB/C,OAAOV,MAAM8C,IAAI;QACxD,OAAOsC,sBACL9E,OACAI,OACAA,MAAMD,GAAG,CAAC,CAAC6F,OAAOnF;gBAAU6E;oBAAAA,eAAAA,KAAK,CAAC7E,MAAM,YAAZ6E,eAAgBK,QAAQ,CAAClF,MAAM;;IAE/D,EAAE,OAAO+E,OAAO;QACdC,QAAQD,KAAK,CAAC,8DAA8D;YAAEA;QAAM;QACpF,OAAO5F;IACT;AACF"}
|
|
@@ -203,6 +203,8 @@ export declare function aiBuildDegradation(unit: AiBuildUnit, context: {
|
|
|
203
203
|
ledger: readonly AiJobItemLedger[];
|
|
204
204
|
ops?: AiBuildOps;
|
|
205
205
|
}): AiBuildDegradation;
|
|
206
|
+
/** The dataset a form unit writes to, by its `new:` name lowercased; `null` for any other unit (AGL-3616). */
|
|
207
|
+
export declare function aiBuildUnitWritesTo(unit: Pick<AiBuildUnit, 'creation'>): string | null;
|
|
206
208
|
/** What each creation is called in a note. */
|
|
207
209
|
export declare function aiBuildCreationNoun(kind: AiBuildPlanCreateKind): string;
|
|
208
210
|
/**
|
|
@@ -107,15 +107,18 @@ import { AI_CREDIT_RANGE_ZERO, AI_MEASURED_PASS_CREDITS, aiCreditRangeAdd, aiCre
|
|
|
107
107
|
};
|
|
108
108
|
const units = [];
|
|
109
109
|
plan.create.forEach((creation, index)=>{
|
|
110
|
+
var _creation_writesTo;
|
|
110
111
|
if (!AI_BUILD_CREATE_KINDS.includes(creation.kind)) return;
|
|
111
112
|
const slot = `c${index}`;
|
|
113
|
+
// A form is built after the dataset it writes to (AGL-3616).
|
|
112
114
|
units.push({
|
|
113
115
|
slot,
|
|
114
116
|
op: creationOp(creation),
|
|
115
117
|
label: creation.name,
|
|
116
118
|
creation,
|
|
117
119
|
deps: depsOf([
|
|
118
|
-
creation.duplicateOf
|
|
120
|
+
creation.duplicateOf,
|
|
121
|
+
creation.kind === 'form' ? (_creation_writesTo = creation.writesTo) != null ? _creation_writesTo : null : null
|
|
119
122
|
], slot)
|
|
120
123
|
});
|
|
121
124
|
});
|
|
@@ -435,6 +438,13 @@ const OPEN = [
|
|
|
435
438
|
const noun = dep.creation ? aiBuildCreationNoun(dep.creation.kind) : (_ref = (_context_ops = context.ops) == null ? void 0 : (_context_ops_get = _context_ops.get(dep.op)) == null ? void 0 : _context_ops_get.noun) != null ? _ref : dep.op;
|
|
436
439
|
const capability = dep.item ? (_context_ops1 = context.ops) == null ? void 0 : _context_ops1.get(dep.op) : undefined;
|
|
437
440
|
const degrade = (_ref1 = (_ref2 = (_dep_item = dep.item) == null ? void 0 : _dep_item.degrade) != null ? _ref2 : capability == null ? void 0 : capability.degrade) != null ? _ref1 : ((_dep_creation = dep.creation) == null ? void 0 : _dep_creation.kind) === 'layout' ? 'fallback' : 'omit';
|
|
441
|
+
// A form whose dataset could not be made is built without it (AGL-3616):
|
|
442
|
+
// its submissions reach the Inbox, as any form's do.
|
|
443
|
+
if (aiBuildUnitWritesTo(unit) === dep.label.toLowerCase()) {
|
|
444
|
+
result.degradedBy.push(slot);
|
|
445
|
+
result.notes.push(`Its submissions arrive in the Inbox only: the dataset “${dep.label}” could not be created.`);
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
438
448
|
if (!unit.screen && degrade === 'omit') {
|
|
439
449
|
result.skip = `Not built: the ${noun} “${dep.label}” it needs could not be created.`;
|
|
440
450
|
result.degradedBy.push(slot);
|
|
@@ -458,6 +468,11 @@ const OPEN = [
|
|
|
458
468
|
}
|
|
459
469
|
return result;
|
|
460
470
|
}
|
|
471
|
+
/** The dataset a form unit writes to, by its `new:` name lowercased; `null` for any other unit (AGL-3616). */ export function aiBuildUnitWritesTo(unit) {
|
|
472
|
+
var _unit_creation;
|
|
473
|
+
const ref = ((_unit_creation = unit.creation) == null ? void 0 : _unit_creation.kind) === 'form' ? unit.creation.writesTo : null;
|
|
474
|
+
return isAiPlanNewRef(ref) ? aiBuildRefName(ref) : null;
|
|
475
|
+
}
|
|
461
476
|
/** What each creation is called in a note. */ export function aiBuildCreationNoun(kind) {
|
|
462
477
|
return kind === 'email' ? 'email design' : kind === 'theme-change' ? 'theme change' : kind;
|
|
463
478
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-build-job.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 {\n pluginAiCapabilityArgsProblems,\n type PluginAiCapability,\n} from '@aglyn/aglyn/plugin-manager/plugin-ai-capabilities'\nimport {\n AI_PLAN_NEW_REF_PREFIX,\n isAiPlanNewRef,\n type AiBuildItem,\n type AiBuildPlan,\n type AiBuildPlanCreate,\n type AiBuildPlanCreateKind,\n type AiBuildPlanScreen,\n} from './ai-build-plan'\nimport type { AiJobItemLedger, AiJobItemStatus } from './ai-jobs.types'\nimport {\n AI_SITE_HOME_FIRST_LABEL,\n AI_SITE_MAX_SECTIONS,\n AI_SITE_PASS_CREDITS,\n aiCreationMeasuredCredits,\n aiJobPlanCreditEstimate,\n aiJobPlanCreditRange,\n aiSitePlanIsHome,\n aiStandaloneScreenCreditRange,\n} from './ai-site-job'\nimport {\n AI_CREDIT_RANGE_ZERO,\n AI_MEASURED_PASS_CREDITS,\n aiCreditRangeAdd,\n aiCreditRangeOf,\n aiCreditRangeOrdered,\n type AiCreditRange,\n type AiCreditsSmaller,\n} from './ai-credit-estimate'\n\n/**\n * What a `build` job is (AGL-3616): one request — \"a few pages, a contact\n * form and a way to book me\" — planned as creations, pages and items, built\n * one UNIT a pass in dependency order, and settled ITEM BY ITEM.\n *\n * A build is a generalized site scaffold. Every unit is handed to what\n * already builds that kind of thing — a page to the page step, a form to the\n * form step, another plugin's resource to that plugin's draft writer — so a\n * build cannot drift from what it builds. What is new is the settlement: one\n * failed unit does not end the job. It gives back its own spend, the units\n * that depended on it are built without it (or skipped, when they cannot\n * stand without it), and the job is `done` when anything was delivered.\n *\n * This module is the build's MODEL — its units, their order, how a failure\n * travels to what depends on it, what it is estimated to cost, and the\n * ledger arithmetic — and does no I/O, so the step, the machine, the doors\n * and the console read one vocabulary.\n */\n\n/** How much one build holds: what one proposal can describe and one person can read. */\nexport const AI_BUILD_LIMITS = {\n /** Creations, pages and items together. */\n units: 16,\n pages: 8,\n /** A Free workspace's pages. */\n freePages: 2,\n} as const\n\n/**\n * What a Free build's plan card says when it holds as many pages as a Free\n * build makes (AGL-3722): the plan is told the cap and plans the first pages\n * a request asks for, so a request for three — \"About us, Custom cakes and\n * Catering\", 2026-10-10 — came back as two with nothing saying why. `null`\n * when the plan holds fewer, or on a paid workspace.\n */\nexport function aiBuildFreePageCapNote(plan: Pick<AiBuildPlan, 'screens'>, freeTaste: boolean): string | null {\n const cap = AI_BUILD_LIMITS.freePages\n if (!freeTaste || plan.screens.length < cap) return null\n return `A Free workspace’s build makes up to ${cap} pages at a time. If you asked for more, ask Assist for the rest once this build is done.`\n}\n\n/** What a build creates through its `create` list; everything else beyond pages is an item. */\nexport const AI_BUILD_CREATE_KINDS: readonly AiBuildPlanCreateKind[] = ['layout', 'form', 'component', 'email']\n\n/**\n * The operations a build plans through `create` and `screens` rather than\n * `items`: an item naming one is a plan that put it in the wrong list.\n */\nexport const AI_BUILD_STRUCTURAL_OPS: readonly string[] = ['page', ...AI_BUILD_CREATE_KINDS]\n\n/** The job input a build's Assist proposal sets when the brief asked to publish. */\nexport const AI_BUILD_PUBLISH_INPUT = 'publish'\n\n/** A unit of a build: a creation, a page, or an item. */\nexport interface AiBuildUnit {\n slot: string\n /** The capability operation that builds it. */\n op: string\n label: string\n creation?: AiBuildPlanCreate\n screen?: AiBuildPlanScreen\n item?: AiBuildItem\n /** The slots it is built after, in plan order. */\n deps: string[]\n}\n\n/** The operation a creation is built as. */\nfunction creationOp(creation: AiBuildPlanCreate): string {\n return creation.kind\n}\n\n/** A plan's `new:<name>` names, each to the slot that builds it. */\nfunction namedSlots(plan: AiBuildPlan): Map<string, string> {\n const slots = new Map<string, string>()\n plan.create.forEach((creation, index) => {\n if (AI_BUILD_CREATE_KINDS.includes(creation.kind)) slots.set(creation.name.toLowerCase(), `c${index}`)\n })\n for (const item of plan.items ?? []) slots.set(item.name.toLowerCase(), item.slot)\n return slots\n}\n\n/** The name a `new:<name>` reference gives, lowercased. */\nexport function aiBuildRefName(ref: string): string {\n return ref.slice(AI_PLAN_NEW_REF_PREFIX.length).trim().toLowerCase()\n}\n\n/** Every reference a page makes: its layout, template, starting page and what its sections place. */\nexport function aiBuildScreenRefs(screen: AiBuildPlanScreen): string[] {\n return [\n screen.layout,\n screen.template,\n screen.duplicateOf,\n ...screen.sections.flatMap((section) => section.uses),\n ].filter((ref): ref is string => typeof ref === 'string' && ref.length > 0)\n}\n\n/**\n * The units a plan implies, in plan order: creations, then items, then\n * pages — the order a member reads them in, and the one a page that places\n * a creation or an item is built after anyway. `aiBuildOrder` sorts them on\n * their dependencies.\n */\nexport function aiBuildUnits(plan: AiBuildPlan): AiBuildUnit[] {\n const slots = namedSlots(plan)\n const depsOf = (refs: readonly (string | null)[], self: string): string[] => {\n const deps: string[] = []\n for (const ref of refs) {\n if (!isAiPlanNewRef(ref)) continue\n const slot = slots.get(aiBuildRefName(ref))\n if (slot && slot !== self && !deps.includes(slot)) deps.push(slot)\n }\n return deps\n }\n const units: AiBuildUnit[] = []\n plan.create.forEach((creation, index) => {\n if (!AI_BUILD_CREATE_KINDS.includes(creation.kind)) return\n const slot = `c${index}`\n units.push({ slot, op: creationOp(creation), label: creation.name, creation, deps: depsOf([creation.duplicateOf], slot) })\n })\n for (const item of plan.items ?? []) {\n units.push({ slot: item.slot, op: item.op, label: item.name, item, deps: depsOf(item.dependsOn, item.slot) })\n }\n plan.screens.forEach((screen, index) => {\n const slot = `p${index}`\n units.push({ slot, op: 'page', label: screen.title, screen, deps: depsOf(aiBuildScreenRefs(screen), slot) })\n })\n return units\n}\n\n/**\n * The units in an order that builds every dependency before what depends on\n * it, plan order otherwise; `null` when the dependencies hold a cycle.\n */\nexport function aiBuildOrder(units: readonly AiBuildUnit[]): AiBuildUnit[] | null {\n const ordered: AiBuildUnit[] = []\n const placed = new Set<string>()\n const known = new Set(units.map((unit) => unit.slot))\n while (ordered.length < units.length) {\n const next = units.find(\n (unit) => !placed.has(unit.slot) && unit.deps.every((dep) => placed.has(dep) || !known.has(dep)),\n )\n if (!next) return null\n ordered.push(next)\n placed.add(next.slot)\n }\n return ordered\n}\n\n/**\n * What is wrong with a plan's references as a build reads them: a\n * `new:<name>` an item depends on that nothing in the plan makes, and a\n * cycle. Each is a sentence the plan's one re-ask carries.\n */\nexport function aiBuildGraphProblems(plan: AiBuildPlan): string[] {\n const problems: string[] = []\n const slots = namedSlots(plan)\n for (const item of plan.items ?? []) {\n for (const ref of item.dependsOn) {\n if (!isAiPlanNewRef(ref)) continue\n if (!slots.has(aiBuildRefName(ref))) {\n problems.push(`The item \"${item.name}\" depends on ${ref}, which the plan never makes. Declare it, or take it out of dependsOn.`)\n } else if (aiBuildRefName(ref) === item.name.toLowerCase()) {\n problems.push(`The item \"${item.name}\" depends on itself. Take it out of its own dependsOn.`)\n }\n }\n }\n if (!aiBuildOrder(aiBuildUnits(plan))) {\n problems.push('The plan’s dependencies go round in a circle, so nothing in the circle can be built first. Make one of them depend on nothing.')\n }\n return problems\n}\n\n/** The operations a build may plan, as the registry and the gates left them, by op. */\nexport type AiBuildOps = ReadonlyMap<string, PluginAiCapability>\n\n/** How many pages a build may hold on this workspace. */\nexport function aiBuildPageLimit(freeTaste: boolean | null | undefined): number {\n return freeTaste ? AI_BUILD_LIMITS.freePages : AI_BUILD_LIMITS.pages\n}\n\n/**\n * Why a build cannot build a plan of this shape, in a sentence a member\n * reads; `null` when it can. Held to the plan with the one re-ask (the plan\n * step's scope), and again by the doors before a confirmed plan runs.\n * `ops` is what may be planned on this site; absent, items are not judged\n * against the registry (a console reading a kept plan).\n */\nexport function aiBuildPlanShapeRefusal(\n plan: AiBuildPlan,\n options: { freeTaste?: boolean; ops?: AiBuildOps } = {},\n): string | null {\n const units = aiBuildUnits(plan)\n if (!units.length) return 'This plan builds nothing. Describe what to build again.'\n if (units.length > AI_BUILD_LIMITS.units) {\n return `This plan builds ${units.length} things, and one build holds ${AI_BUILD_LIMITS.units}. Ask for the rest in a second request.`\n }\n const pages = aiBuildPageLimit(options.freeTaste)\n if (plan.screens.length > pages) {\n return options.freeTaste\n ? `This plan builds ${plan.screens.length} pages, and a Free workspace's build makes at most ${pages}. Paid plans can build more.`\n : `This plan builds ${plan.screens.length} pages, and one build makes at most ${pages}.`\n }\n const slugs = new Set<string>()\n for (const screen of plan.screens) {\n if (!screen.sections.length) return `The page “${screen.title}” has no sections to build.`\n if (screen.sections.length > AI_SITE_MAX_SECTIONS) {\n return `The page “${screen.title}” has ${screen.sections.length} sections, and a built page holds ${AI_SITE_MAX_SECTIONS}.`\n }\n const slug = screen.slug.trim().toLowerCase()\n if (slugs.has(slug)) return `Two pages in this plan share the address ${screen.slug}.`\n slugs.add(slug)\n }\n for (const creation of plan.create) {\n if (!AI_BUILD_CREATE_KINDS.includes(creation.kind)) {\n return `A build does not create ${creation.kind === 'theme-change' ? 'theme changes' : `${creation.kind}s`} (“${creation.name}”). Take it out of create.`\n }\n }\n const graph = aiBuildGraphProblems(plan)\n if (graph.length) return graph[0]\n const ops = options.ops\n const counts = new Map<string, number>()\n for (const unit of units) counts.set(unit.op, (counts.get(unit.op) ?? 0) + 1)\n for (const item of plan.items ?? []) {\n if (AI_BUILD_STRUCTURAL_OPS.includes(item.op)) {\n return item.op === 'page'\n ? `“${item.name}” is a page: plan it in screens, not items.`\n : `“${item.name}” is ${item.op === 'email' ? 'an' : 'a'} ${item.op}: plan it in create, not items.`\n }\n if (!ops) continue\n const capability = ops.get(item.op)\n if (!capability) return `Nothing on this site can make “${item.name}” (${item.op}). Take it out of items.`\n if (options.freeTaste && !capability.freeAllowed) {\n return `A Free workspace cannot have ${aiArticle(capability.noun)} made (“${item.name}”). Take it out of items.`\n }\n const problems = pluginAiCapabilityArgsProblems(capability.argsSchema, item.args)\n if (problems.length) return `The arguments of “${item.name}” do not read: ${problems.join('; ')}.`\n }\n if (ops) {\n for (const [op, count] of counts) {\n const capability = ops.get(op)\n if (capability && count > capability.maxPerPlan) {\n return `This plan makes ${count} of “${capability.noun}”, and one build makes at most ${capability.maxPerPlan}.`\n }\n }\n }\n return null\n}\n\n/** \"a booking service\", \"an email design\". */\nexport function aiArticle(noun: string): string {\n return `${/^[aeiou]/i.test(noun) ? 'an' : 'a'} ${noun}`\n}\n\n/** The passes one unit is estimated at: a page's sections and its listing, one for a creation. */\nfunction unitPasses(unit: AiBuildUnit): number {\n if (unit.screen) return unit.screen.sections.length + 1\n return 1\n}\n\n/**\n * About what one unit costs, in credits: a page or a creation by the passes\n * it implies at the nominal credits a pass is held against, as a site's are;\n * an item by its capability's own estimate, recorded on the plan when it was\n * kept.\n */\nexport function aiBuildUnitCreditEstimate(unit: AiBuildUnit, ops?: AiBuildOps): number {\n if (unit.item) {\n if (typeof unit.item.credits === 'number') return unit.item.credits\n const capability = ops?.get(unit.item.op)\n if (capability) return Math.max(0, Math.floor(capability.estimateCredits(unit.item.args)))\n return AI_SITE_PASS_CREDITS\n }\n return unitPasses(unit) * AI_SITE_PASS_CREDITS\n}\n\n/**\n * About what a build costs, in credits: every unit's estimate, or only the\n * units named in `slots` — what Try again shows. The ceiling a member\n * confirms; the meter charges what actually runs.\n */\nexport function aiBuildCreditEstimate(\n plan: AiBuildPlan,\n options: { ops?: AiBuildOps; slots?: ReadonlySet<string> } = {},\n): number {\n return aiBuildUnits(plan)\n .filter((unit) => !options.slots || options.slots.has(unit.slot))\n .reduce((total, unit) => total + aiBuildUnitCreditEstimate(unit, options.ops), 0)\n}\n\n/**\n * About what a job of this kind costs to build from its plan: a build's\n * units, every other planned kind as `aiJobPlanCreditEstimate` counts it.\n */\nexport function aiJobCreditEstimate(kind: string, plan: AiBuildPlan): number {\n return kind === 'build' ? aiBuildCreditEstimate(plan) : aiJobPlanCreditEstimate(kind, plan)\n}\n\n/**\n * What one unit is likely to cost, its p90 and its ceiling (AGL-3722): a page\n * as a page written on its own measured (a fixed cost and one per section), a creation at what its kind\n * measured, an item at the measured pass times the passes its capability\n * estimates (none for a draft another plugin writes, which asks no model).\n * The ceiling is `aiBuildUnitCreditEstimate`, unchanged.\n */\nexport function aiBuildUnitCreditRange(unit: AiBuildUnit, ops?: AiBuildOps): AiCreditRange {\n const ceiling = aiBuildUnitCreditEstimate(unit, ops)\n // A build writes each page on its own, never in a site start's warm run (AGL-3722).\n if (unit.screen) return aiStandaloneScreenCreditRange(unit.screen.sections.length)\n if (unit.creation) return aiCreditRangeOf(aiCreationMeasuredCredits(unit.creation.kind, { standalone: true }), ceiling)\n const passes = Math.ceil(ceiling / AI_SITE_PASS_CREDITS)\n return aiCreditRangeOf(\n { median: passes * AI_MEASURED_PASS_CREDITS.median, p90: passes * AI_MEASURED_PASS_CREDITS.p90 },\n ceiling,\n )\n}\n\n/**\n * What a build is likely to cost, its p90 and its ceiling (AGL-3722): every\n * unit's range, or only the units named in `slots` — what Try again runs.\n * The plan card, Try again and the Free admission all read this; the meter\n * charges what actually runs.\n */\nexport function aiBuildCreditRange(\n plan: AiBuildPlan,\n options: { ops?: AiBuildOps; slots?: ReadonlySet<string> } = {},\n): AiCreditRange {\n return aiCreditRangeOrdered(\n aiBuildUnits(plan)\n .filter((unit) => !options.slots || options.slots.has(unit.slot))\n .reduce((total, unit) => aiCreditRangeAdd(total, aiBuildUnitCreditRange(unit, options.ops)), AI_CREDIT_RANGE_ZERO),\n )\n}\n\n/** `aiJobCreditEstimate` as a range (AGL-3722). */\nexport function aiJobCreditRange(kind: string, plan: AiBuildPlan): AiCreditRange {\n return kind === 'build' ? aiBuildCreditRange(plan) : aiJobPlanCreditRange(kind, plan)\n}\n\n/**\n * A smaller first build (AGL-3722): the plan's home page — its first page\n * where it has no home — and only what that page needs, transitively: the\n * layout it is drawn in, the form and anything else its sections place.\n * Every other page, and what only they needed, waits for a later request.\n * `null` when the plan has no page, or when the smaller plan is the whole one.\n */\nexport function aiBuildFirstPagePlan<T extends AiBuildPlan>(plan: T): T | null {\n if (!plan.screens.length) return null\n const index = Math.max(0, plan.screens.findIndex(aiSitePlanIsHome))\n const units = aiBuildUnits(plan)\n const bySlot = new Map(units.map((unit) => [unit.slot, unit]))\n const keep = new Set<string>()\n const queue = [`p${index}`]\n while (queue.length) {\n const slot = queue.shift() as string\n if (keep.has(slot)) continue\n keep.add(slot)\n for (const dep of bySlot.get(slot)?.deps ?? []) queue.push(dep)\n }\n if (keep.size === units.length) return null\n const screen = plan.screens[index]\n const create = plan.create.filter((creation, at) => !AI_BUILD_CREATE_KINDS.includes(creation.kind) || keep.has(`c${at}`))\n const items = (plan.items ?? []).filter((item) => keep.has(item.slot))\n const kept = new Set([screen.slug, ...create.map((entry) => `${AI_PLAN_NEW_REF_PREFIX}${entry.name}`)])\n return {\n ...plan,\n create,\n screens: [screen],\n ...(plan.items ? { items } : {}),\n ...(plan.embeds ? { embeds: plan.embeds.filter((embed) => kept.has(embed.where)) } : {}),\n }\n}\n\n/** The smaller first build a build that does not fit is offered (AGL-3722), with its range; `null` when there is none. */\nexport function aiBuildSmaller(plan: AiBuildPlan, ops?: AiBuildOps): AiCreditsSmaller | null {\n const smaller = aiBuildFirstPagePlan(plan)\n if (!smaller) return null\n const screen = smaller.screens[0]\n const label = aiSitePlanIsHome(screen) ? AI_SITE_HOME_FIRST_LABEL : `Build the ${screen.title} page first`\n return { label, ...aiBuildCreditRange(smaller, { ops }) }\n}\n\n/** A fresh ledger: one pending row per unit, first attempt. */\nexport function aiBuildInitialLedger(units: readonly AiBuildUnit[]): AiJobItemLedger[] {\n return units.map((unit) => ({\n slot: unit.slot,\n op: unit.op,\n label: unit.label,\n status: 'pending',\n attempt: 1,\n creditsSpent: 0,\n attemptCredits: 0,\n creditsRefunded: 0,\n failure: null,\n outputs: [],\n }))\n}\n\nconst OPEN: readonly AiJobItemStatus[] = ['pending', 'running']\n\n/** Whether an item is still to be built. */\nexport function aiBuildItemOpen(row: Pick<AiJobItemLedger, 'status'>): boolean {\n return OPEN.includes(row.status)\n}\n\n/** Whether an item delivered: built as planned, or built without something that failed. */\nexport function aiBuildItemDelivered(row: Pick<AiJobItemLedger, 'status'>): boolean {\n return row.status === 'succeeded' || row.status === 'degraded'\n}\n\n/**\n * The next unit to build: the first in build order whose row is still open.\n * Its dependencies come before it, so by then each is settled one way or the\n * other. `null` when nothing is left.\n */\nexport function aiBuildNextUnit(\n ordered: readonly AiBuildUnit[],\n ledger: readonly AiJobItemLedger[],\n): AiBuildUnit | null {\n const rows = new Map(ledger.map((row) => [row.slot, row]))\n return ordered.find((unit) => {\n const row = rows.get(unit.slot)\n return !row || aiBuildItemOpen(row)\n }) ?? null\n}\n\n/** How a unit is built given what its dependencies came to. */\nexport interface AiBuildDegradation {\n /** The unit is not built at all, with the sentence why; nothing is spent. */\n skip: string | null\n /** The failed dependencies that change how it is built. */\n degradedBy: string[]\n /** What the person reads about the change; one per failed dependency. */\n notes: string[]\n /** `new:<name>` references (lowercased names) to leave out. */\n dropped: Set<string>\n /** Brief lines for the unit's own job: what to leave out, and what to place. */\n briefLines: string[]\n}\n\n/**\n * How a unit is built when some of what it depends on failed (AGL-3616).\n *\n * A PAGE is always built: a failed layout falls back to the site's own, a\n * failed form or component is left out of its section, and a failed item a\n * section places (a booking service) takes its block out of the page — each\n * with a note. Any OTHER unit whose dependency failed is skipped when that\n * dependency's capability says `omit` (a campaign whose email design failed\n * has nothing to send), and built without it when it says `fallback`.\n */\nexport function aiBuildDegradation(\n unit: AiBuildUnit,\n context: {\n units: readonly AiBuildUnit[]\n ledger: readonly AiJobItemLedger[]\n ops?: AiBuildOps\n },\n): AiBuildDegradation {\n const rows = new Map(context.ledger.map((row) => [row.slot, row]))\n const bySlot = new Map(context.units.map((one) => [one.slot, one]))\n const result: AiBuildDegradation = { skip: null, degradedBy: [], notes: [], dropped: new Set(), briefLines: [] }\n for (const slot of unit.deps) {\n const dep = bySlot.get(slot)\n const row = rows.get(slot)\n if (!dep || !row || aiBuildItemDelivered(row)) continue\n const noun = dep.creation\n ? aiBuildCreationNoun(dep.creation.kind)\n : (context.ops?.get(dep.op)?.noun ?? dep.op)\n const capability = dep.item ? context.ops?.get(dep.op) : undefined\n const degrade = dep.item?.degrade ?? capability?.degrade ?? (dep.creation?.kind === 'layout' ? 'fallback' : 'omit')\n if (!unit.screen && degrade === 'omit') {\n result.skip = `Not built: the ${noun} “${dep.label}” it needs could not be created.`\n result.degradedBy.push(slot)\n return result\n }\n result.degradedBy.push(slot)\n result.dropped.add(dep.label.toLowerCase())\n if (dep.creation?.kind === 'layout') {\n result.notes.push(`Built inside the site’s own layout: the layout “${dep.label}” could not be created.`)\n continue\n }\n if (unit.screen) {\n const section = unit.screen.sections.find((one) =>\n one.uses.some((ref) => isAiPlanNewRef(ref) && aiBuildRefName(ref) === dep.label.toLowerCase()),\n )\n const blocks = capability?.pageBlocks?.length ? ` the ${capability.pageBlocks.join(' or ')} block` : ''\n result.notes.push(\n `Built without${blocks || ` the ${noun}`}: the ${noun} “${dep.label}” could not be created.`,\n )\n result.briefLines.push(\n `${section ? `Build the “${section.name}” section` : 'Build the page'} without the ${noun} “${dep.label}”${blocks ? ` and without${blocks}` : ''}: it could not be created.`,\n )\n } else {\n result.notes.push(`Built without the ${noun} “${dep.label}”: it could not be created.`)\n }\n }\n return result\n}\n\n/** What each creation is called in a note. */\nexport function aiBuildCreationNoun(kind: AiBuildPlanCreateKind): string {\n return kind === 'email' ? 'email design' : kind === 'theme-change' ? 'theme change' : kind\n}\n\n/**\n * The brief lines a page is told about the items its sections place and\n * that were built: the block to put there, in the owner's words.\n */\nexport function aiBuildPlacedItemLines(\n unit: AiBuildUnit,\n context: { units: readonly AiBuildUnit[]; ledger: readonly AiJobItemLedger[]; ops?: AiBuildOps },\n): string[] {\n if (!unit.screen) return []\n const rows = new Map(context.ledger.map((row) => [row.slot, row]))\n const lines: string[] = []\n for (const section of unit.screen.sections) {\n for (const ref of section.uses) {\n if (!isAiPlanNewRef(ref)) continue\n const dep = context.units.find((one) => one.item && one.item.name.toLowerCase() === aiBuildRefName(ref))\n if (!dep?.item) continue\n const row = rows.get(dep.slot)\n if (!row || !aiBuildItemDelivered(row)) continue\n const capability = context.ops?.get(dep.op)\n const blocks = capability?.pageBlocks ?? []\n if (!blocks.length) continue\n lines.push(\n `In the “${section.name}” section, place the ${blocks.join(' or ')} block for the ${capability?.noun ?? dep.op} “${dep.label}”.`,\n )\n }\n }\n return lines\n}\n\n/** What a build came to: whether anything was delivered, and whether anything is left. */\nexport function aiBuildSettlement(ledger: readonly AiJobItemLedger[]): {\n delivered: boolean\n open: boolean\n failed: number\n} {\n return {\n delivered: ledger.some(aiBuildItemDelivered),\n open: ledger.some(aiBuildItemOpen),\n failed: ledger.filter((row) => row.status === 'failed').length,\n }\n}\n\n/**\n * The ledger Try again runs (AGL-3616): every failed item back to `pending`\n * on its next attempt, with the items left unbuilt because of it — skipped,\n * or degraded with no draft — and every item the build never reached. An\n * item that succeeded is never run again, and a degraded page that has its\n * draft keeps it, with a note that the page needs an edit. `retried` names\n * the slots that will run, which is what the estimate is shown for.\n */\nexport function aiBuildRetryLedger(\n ledger: readonly AiJobItemLedger[],\n units: readonly AiBuildUnit[],\n): { ledger: AiJobItemLedger[]; retried: string[] } {\n const failed = new Set(ledger.filter((row) => row.status === 'failed').map((row) => row.slot))\n const dependents = new Map<string, string[]>()\n for (const unit of units) {\n for (const dep of unit.deps) dependents.set(dep, [...(dependents.get(dep) ?? []), unit.slot])\n }\n // Everything downstream of a failed item, transitively.\n const downstream = new Set<string>()\n const queue = [...failed]\n while (queue.length) {\n const slot = queue.shift() as string\n for (const next of dependents.get(slot) ?? []) {\n if (downstream.has(next)) continue\n downstream.add(next)\n queue.push(next)\n }\n }\n const retried: string[] = []\n const next = ledger.map((row): AiJobItemLedger => {\n const again =\n row.status === 'failed' ||\n (row.status === 'skipped' && (downstream.has(row.slot) || !(row.degradedBy ?? []).length)) ||\n (row.status === 'degraded' && downstream.has(row.slot) && !row.outputs.length)\n if (again) {\n retried.push(row.slot)\n return {\n ...row,\n status: 'pending',\n attempt: row.attempt + 1,\n attemptCredits: 0,\n failure: null,\n note: null,\n degradedBy: [],\n settledAt: null,\n }\n }\n if (row.status === 'degraded' && downstream.has(row.slot) && row.outputs.length) {\n return {\n ...row,\n note: `${row.note ? `${row.note} ` : ''}It keeps its draft: once the rest is built, edit this page to add what it is missing.`,\n }\n }\n return row\n })\n return { ledger: next, retried }\n}\n\n/**\n * Units read back off a ledger alone (AGL-3616), for a job whose units are\n * not a build plan's — a site scaffold's: each row as its unit, and every\n * page built after the layouts and forms the ledger holds.\n */\nexport function aiLedgerUnits(ledger: readonly AiJobItemLedger[]): AiBuildUnit[] {\n const creations = ledger.filter((row) => row.op === 'layout' || row.op === 'form').map((row) => row.slot)\n return ledger.map((row) => ({\n slot: row.slot,\n op: row.op,\n label: row.label,\n deps: row.op === 'page' ? creations : [],\n }))\n}\n"],"names":["pluginAiCapabilityArgsProblems","AI_PLAN_NEW_REF_PREFIX","isAiPlanNewRef","AI_SITE_HOME_FIRST_LABEL","AI_SITE_MAX_SECTIONS","AI_SITE_PASS_CREDITS","aiCreationMeasuredCredits","aiJobPlanCreditEstimate","aiJobPlanCreditRange","aiSitePlanIsHome","aiStandaloneScreenCreditRange","AI_CREDIT_RANGE_ZERO","AI_MEASURED_PASS_CREDITS","aiCreditRangeAdd","aiCreditRangeOf","aiCreditRangeOrdered","AI_BUILD_LIMITS","units","pages","freePages","aiBuildFreePageCapNote","plan","freeTaste","cap","screens","length","AI_BUILD_CREATE_KINDS","AI_BUILD_STRUCTURAL_OPS","AI_BUILD_PUBLISH_INPUT","creationOp","creation","kind","namedSlots","slots","Map","create","forEach","index","includes","set","name","toLowerCase","item","items","slot","aiBuildRefName","ref","slice","trim","aiBuildScreenRefs","screen","layout","template","duplicateOf","sections","flatMap","section","uses","filter","aiBuildUnits","depsOf","refs","self","deps","get","push","op","label","dependsOn","title","aiBuildOrder","ordered","placed","Set","known","map","unit","next","find","has","every","dep","add","aiBuildGraphProblems","problems","aiBuildPageLimit","aiBuildPlanShapeRefusal","options","counts","slugs","slug","graph","ops","capability","freeAllowed","aiArticle","noun","argsSchema","args","join","count","maxPerPlan","test","unitPasses","aiBuildUnitCreditEstimate","credits","Math","max","floor","estimateCredits","aiBuildCreditEstimate","reduce","total","aiJobCreditEstimate","aiBuildUnitCreditRange","ceiling","standalone","passes","ceil","median","p90","aiBuildCreditRange","aiJobCreditRange","aiBuildFirstPagePlan","findIndex","bySlot","keep","queue","shift","size","at","kept","entry","embeds","embed","where","aiBuildSmaller","smaller","aiBuildInitialLedger","status","attempt","creditsSpent","attemptCredits","creditsRefunded","failure","outputs","OPEN","aiBuildItemOpen","row","aiBuildItemDelivered","aiBuildNextUnit","ledger","rows","aiBuildDegradation","context","one","result","skip","degradedBy","notes","dropped","briefLines","aiBuildCreationNoun","undefined","degrade","some","blocks","pageBlocks","aiBuildPlacedItemLines","lines","aiBuildSettlement","delivered","open","failed","aiBuildRetryLedger","dependents","downstream","retried","again","note","settledAt","aiLedgerUnits","creations"],"mappings":";AAAA;;;;;;;;;;;;;;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AAO/B;IACT;IACA,OAAO;QAAEG,QAAQ1E;QAAMoG;IAAQ;AACjC;AAEA;;;;CAIC,GACD,OAAO,SAASI,cAAc9B,MAAkC;IAC9D,MAAM+B,YAAY/B,OAAO7F,MAAM,CAAC,CAAC0F,MAAQA,IAAIlF,EAAE,KAAK,YAAYkF,IAAIlF,EAAE,KAAK,QAAQS,GAAG,CAAC,CAACyE,MAAQA,IAAIxG,IAAI;IACxG,OAAO2G,OAAO5E,GAAG,CAAC,CAACyE,MAAS,CAAA;YAC1BxG,MAAMwG,IAAIxG,IAAI;YACdsB,IAAIkF,IAAIlF,EAAE;YACVC,OAAOiF,IAAIjF,KAAK;YAChBJ,MAAMqF,IAAIlF,EAAE,KAAK,SAASoH,YAAY,EAAE;QAC1C,CAAA;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-build-job.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 {\n pluginAiCapabilityArgsProblems,\n type PluginAiCapability,\n} from '@aglyn/aglyn/plugin-manager/plugin-ai-capabilities'\nimport {\n AI_PLAN_NEW_REF_PREFIX,\n isAiPlanNewRef,\n type AiBuildItem,\n type AiBuildPlan,\n type AiBuildPlanCreate,\n type AiBuildPlanCreateKind,\n type AiBuildPlanScreen,\n} from './ai-build-plan'\nimport type { AiJobItemLedger, AiJobItemStatus } from './ai-jobs.types'\nimport {\n AI_SITE_HOME_FIRST_LABEL,\n AI_SITE_MAX_SECTIONS,\n AI_SITE_PASS_CREDITS,\n aiCreationMeasuredCredits,\n aiJobPlanCreditEstimate,\n aiJobPlanCreditRange,\n aiSitePlanIsHome,\n aiStandaloneScreenCreditRange,\n} from './ai-site-job'\nimport {\n AI_CREDIT_RANGE_ZERO,\n AI_MEASURED_PASS_CREDITS,\n aiCreditRangeAdd,\n aiCreditRangeOf,\n aiCreditRangeOrdered,\n type AiCreditRange,\n type AiCreditsSmaller,\n} from './ai-credit-estimate'\n\n/**\n * What a `build` job is (AGL-3616): one request — \"a few pages, a contact\n * form and a way to book me\" — planned as creations, pages and items, built\n * one UNIT a pass in dependency order, and settled ITEM BY ITEM.\n *\n * A build is a generalized site scaffold. Every unit is handed to what\n * already builds that kind of thing — a page to the page step, a form to the\n * form step, another plugin's resource to that plugin's draft writer — so a\n * build cannot drift from what it builds. What is new is the settlement: one\n * failed unit does not end the job. It gives back its own spend, the units\n * that depended on it are built without it (or skipped, when they cannot\n * stand without it), and the job is `done` when anything was delivered.\n *\n * This module is the build's MODEL — its units, their order, how a failure\n * travels to what depends on it, what it is estimated to cost, and the\n * ledger arithmetic — and does no I/O, so the step, the machine, the doors\n * and the console read one vocabulary.\n */\n\n/** How much one build holds: what one proposal can describe and one person can read. */\nexport const AI_BUILD_LIMITS = {\n /** Creations, pages and items together. */\n units: 16,\n pages: 8,\n /** A Free workspace's pages. */\n freePages: 2,\n} as const\n\n/**\n * What a Free build's plan card says when it holds as many pages as a Free\n * build makes (AGL-3722): the plan is told the cap and plans the first pages\n * a request asks for, so a request for three — \"About us, Custom cakes and\n * Catering\", 2026-10-10 — came back as two with nothing saying why. `null`\n * when the plan holds fewer, or on a paid workspace.\n */\nexport function aiBuildFreePageCapNote(plan: Pick<AiBuildPlan, 'screens'>, freeTaste: boolean): string | null {\n const cap = AI_BUILD_LIMITS.freePages\n if (!freeTaste || plan.screens.length < cap) return null\n return `A Free workspace’s build makes up to ${cap} pages at a time. If you asked for more, ask Assist for the rest once this build is done.`\n}\n\n/** What a build creates through its `create` list; everything else beyond pages is an item. */\nexport const AI_BUILD_CREATE_KINDS: readonly AiBuildPlanCreateKind[] = ['layout', 'form', 'component', 'email']\n\n/**\n * The operations a build plans through `create` and `screens` rather than\n * `items`: an item naming one is a plan that put it in the wrong list.\n */\nexport const AI_BUILD_STRUCTURAL_OPS: readonly string[] = ['page', ...AI_BUILD_CREATE_KINDS]\n\n/** The job input a build's Assist proposal sets when the brief asked to publish. */\nexport const AI_BUILD_PUBLISH_INPUT = 'publish'\n\n/** A unit of a build: a creation, a page, or an item. */\nexport interface AiBuildUnit {\n slot: string\n /** The capability operation that builds it. */\n op: string\n label: string\n creation?: AiBuildPlanCreate\n screen?: AiBuildPlanScreen\n item?: AiBuildItem\n /** The slots it is built after, in plan order. */\n deps: string[]\n}\n\n/** The operation a creation is built as. */\nfunction creationOp(creation: AiBuildPlanCreate): string {\n return creation.kind\n}\n\n/** A plan's `new:<name>` names, each to the slot that builds it. */\nfunction namedSlots(plan: AiBuildPlan): Map<string, string> {\n const slots = new Map<string, string>()\n plan.create.forEach((creation, index) => {\n if (AI_BUILD_CREATE_KINDS.includes(creation.kind)) slots.set(creation.name.toLowerCase(), `c${index}`)\n })\n for (const item of plan.items ?? []) slots.set(item.name.toLowerCase(), item.slot)\n return slots\n}\n\n/** The name a `new:<name>` reference gives, lowercased. */\nexport function aiBuildRefName(ref: string): string {\n return ref.slice(AI_PLAN_NEW_REF_PREFIX.length).trim().toLowerCase()\n}\n\n/** Every reference a page makes: its layout, template, starting page and what its sections place. */\nexport function aiBuildScreenRefs(screen: AiBuildPlanScreen): string[] {\n return [\n screen.layout,\n screen.template,\n screen.duplicateOf,\n ...screen.sections.flatMap((section) => section.uses),\n ].filter((ref): ref is string => typeof ref === 'string' && ref.length > 0)\n}\n\n/**\n * The units a plan implies, in plan order: creations, then items, then\n * pages — the order a member reads them in, and the one a page that places\n * a creation or an item is built after anyway. `aiBuildOrder` sorts them on\n * their dependencies.\n */\nexport function aiBuildUnits(plan: AiBuildPlan): AiBuildUnit[] {\n const slots = namedSlots(plan)\n const depsOf = (refs: readonly (string | null)[], self: string): string[] => {\n const deps: string[] = []\n for (const ref of refs) {\n if (!isAiPlanNewRef(ref)) continue\n const slot = slots.get(aiBuildRefName(ref))\n if (slot && slot !== self && !deps.includes(slot)) deps.push(slot)\n }\n return deps\n }\n const units: AiBuildUnit[] = []\n plan.create.forEach((creation, index) => {\n if (!AI_BUILD_CREATE_KINDS.includes(creation.kind)) return\n const slot = `c${index}`\n // A form is built after the dataset it writes to (AGL-3616).\n units.push({\n slot,\n op: creationOp(creation),\n label: creation.name,\n creation,\n deps: depsOf([creation.duplicateOf, creation.kind === 'form' ? (creation.writesTo ?? null) : null], slot),\n })\n })\n for (const item of plan.items ?? []) {\n units.push({ slot: item.slot, op: item.op, label: item.name, item, deps: depsOf(item.dependsOn, item.slot) })\n }\n plan.screens.forEach((screen, index) => {\n const slot = `p${index}`\n units.push({ slot, op: 'page', label: screen.title, screen, deps: depsOf(aiBuildScreenRefs(screen), slot) })\n })\n return units\n}\n\n/**\n * The units in an order that builds every dependency before what depends on\n * it, plan order otherwise; `null` when the dependencies hold a cycle.\n */\nexport function aiBuildOrder(units: readonly AiBuildUnit[]): AiBuildUnit[] | null {\n const ordered: AiBuildUnit[] = []\n const placed = new Set<string>()\n const known = new Set(units.map((unit) => unit.slot))\n while (ordered.length < units.length) {\n const next = units.find(\n (unit) => !placed.has(unit.slot) && unit.deps.every((dep) => placed.has(dep) || !known.has(dep)),\n )\n if (!next) return null\n ordered.push(next)\n placed.add(next.slot)\n }\n return ordered\n}\n\n/**\n * What is wrong with a plan's references as a build reads them: a\n * `new:<name>` an item depends on that nothing in the plan makes, and a\n * cycle. Each is a sentence the plan's one re-ask carries.\n */\nexport function aiBuildGraphProblems(plan: AiBuildPlan): string[] {\n const problems: string[] = []\n const slots = namedSlots(plan)\n for (const item of plan.items ?? []) {\n for (const ref of item.dependsOn) {\n if (!isAiPlanNewRef(ref)) continue\n if (!slots.has(aiBuildRefName(ref))) {\n problems.push(`The item \"${item.name}\" depends on ${ref}, which the plan never makes. Declare it, or take it out of dependsOn.`)\n } else if (aiBuildRefName(ref) === item.name.toLowerCase()) {\n problems.push(`The item \"${item.name}\" depends on itself. Take it out of its own dependsOn.`)\n }\n }\n }\n if (!aiBuildOrder(aiBuildUnits(plan))) {\n problems.push('The plan’s dependencies go round in a circle, so nothing in the circle can be built first. Make one of them depend on nothing.')\n }\n return problems\n}\n\n/** The operations a build may plan, as the registry and the gates left them, by op. */\nexport type AiBuildOps = ReadonlyMap<string, PluginAiCapability>\n\n/** How many pages a build may hold on this workspace. */\nexport function aiBuildPageLimit(freeTaste: boolean | null | undefined): number {\n return freeTaste ? AI_BUILD_LIMITS.freePages : AI_BUILD_LIMITS.pages\n}\n\n/**\n * Why a build cannot build a plan of this shape, in a sentence a member\n * reads; `null` when it can. Held to the plan with the one re-ask (the plan\n * step's scope), and again by the doors before a confirmed plan runs.\n * `ops` is what may be planned on this site; absent, items are not judged\n * against the registry (a console reading a kept plan).\n */\nexport function aiBuildPlanShapeRefusal(\n plan: AiBuildPlan,\n options: { freeTaste?: boolean; ops?: AiBuildOps } = {},\n): string | null {\n const units = aiBuildUnits(plan)\n if (!units.length) return 'This plan builds nothing. Describe what to build again.'\n if (units.length > AI_BUILD_LIMITS.units) {\n return `This plan builds ${units.length} things, and one build holds ${AI_BUILD_LIMITS.units}. Ask for the rest in a second request.`\n }\n const pages = aiBuildPageLimit(options.freeTaste)\n if (plan.screens.length > pages) {\n return options.freeTaste\n ? `This plan builds ${plan.screens.length} pages, and a Free workspace's build makes at most ${pages}. Paid plans can build more.`\n : `This plan builds ${plan.screens.length} pages, and one build makes at most ${pages}.`\n }\n const slugs = new Set<string>()\n for (const screen of plan.screens) {\n if (!screen.sections.length) return `The page “${screen.title}” has no sections to build.`\n if (screen.sections.length > AI_SITE_MAX_SECTIONS) {\n return `The page “${screen.title}” has ${screen.sections.length} sections, and a built page holds ${AI_SITE_MAX_SECTIONS}.`\n }\n const slug = screen.slug.trim().toLowerCase()\n if (slugs.has(slug)) return `Two pages in this plan share the address ${screen.slug}.`\n slugs.add(slug)\n }\n for (const creation of plan.create) {\n if (!AI_BUILD_CREATE_KINDS.includes(creation.kind)) {\n return `A build does not create ${creation.kind === 'theme-change' ? 'theme changes' : `${creation.kind}s`} (“${creation.name}”). Take it out of create.`\n }\n }\n const graph = aiBuildGraphProblems(plan)\n if (graph.length) return graph[0]\n const ops = options.ops\n const counts = new Map<string, number>()\n for (const unit of units) counts.set(unit.op, (counts.get(unit.op) ?? 0) + 1)\n for (const item of plan.items ?? []) {\n if (AI_BUILD_STRUCTURAL_OPS.includes(item.op)) {\n return item.op === 'page'\n ? `“${item.name}” is a page: plan it in screens, not items.`\n : `“${item.name}” is ${item.op === 'email' ? 'an' : 'a'} ${item.op}: plan it in create, not items.`\n }\n if (!ops) continue\n const capability = ops.get(item.op)\n if (!capability) return `Nothing on this site can make “${item.name}” (${item.op}). Take it out of items.`\n if (options.freeTaste && !capability.freeAllowed) {\n return `A Free workspace cannot have ${aiArticle(capability.noun)} made (“${item.name}”). Take it out of items.`\n }\n const problems = pluginAiCapabilityArgsProblems(capability.argsSchema, item.args)\n if (problems.length) return `The arguments of “${item.name}” do not read: ${problems.join('; ')}.`\n }\n if (ops) {\n for (const [op, count] of counts) {\n const capability = ops.get(op)\n if (capability && count > capability.maxPerPlan) {\n return `This plan makes ${count} of “${capability.noun}”, and one build makes at most ${capability.maxPerPlan}.`\n }\n }\n }\n return null\n}\n\n/** \"a booking service\", \"an email design\". */\nexport function aiArticle(noun: string): string {\n return `${/^[aeiou]/i.test(noun) ? 'an' : 'a'} ${noun}`\n}\n\n/** The passes one unit is estimated at: a page's sections and its listing, one for a creation. */\nfunction unitPasses(unit: AiBuildUnit): number {\n if (unit.screen) return unit.screen.sections.length + 1\n return 1\n}\n\n/**\n * About what one unit costs, in credits: a page or a creation by the passes\n * it implies at the nominal credits a pass is held against, as a site's are;\n * an item by its capability's own estimate, recorded on the plan when it was\n * kept.\n */\nexport function aiBuildUnitCreditEstimate(unit: AiBuildUnit, ops?: AiBuildOps): number {\n if (unit.item) {\n if (typeof unit.item.credits === 'number') return unit.item.credits\n const capability = ops?.get(unit.item.op)\n if (capability) return Math.max(0, Math.floor(capability.estimateCredits(unit.item.args)))\n return AI_SITE_PASS_CREDITS\n }\n return unitPasses(unit) * AI_SITE_PASS_CREDITS\n}\n\n/**\n * About what a build costs, in credits: every unit's estimate, or only the\n * units named in `slots` — what Try again shows. The ceiling a member\n * confirms; the meter charges what actually runs.\n */\nexport function aiBuildCreditEstimate(\n plan: AiBuildPlan,\n options: { ops?: AiBuildOps; slots?: ReadonlySet<string> } = {},\n): number {\n return aiBuildUnits(plan)\n .filter((unit) => !options.slots || options.slots.has(unit.slot))\n .reduce((total, unit) => total + aiBuildUnitCreditEstimate(unit, options.ops), 0)\n}\n\n/**\n * About what a job of this kind costs to build from its plan: a build's\n * units, every other planned kind as `aiJobPlanCreditEstimate` counts it.\n */\nexport function aiJobCreditEstimate(kind: string, plan: AiBuildPlan): number {\n return kind === 'build' ? aiBuildCreditEstimate(plan) : aiJobPlanCreditEstimate(kind, plan)\n}\n\n/**\n * What one unit is likely to cost, its p90 and its ceiling (AGL-3722): a page\n * as a page written on its own measured (a fixed cost and one per section), a creation at what its kind\n * measured, an item at the measured pass times the passes its capability\n * estimates (none for a draft another plugin writes, which asks no model).\n * The ceiling is `aiBuildUnitCreditEstimate`, unchanged.\n */\nexport function aiBuildUnitCreditRange(unit: AiBuildUnit, ops?: AiBuildOps): AiCreditRange {\n const ceiling = aiBuildUnitCreditEstimate(unit, ops)\n // A build writes each page on its own, never in a site start's warm run (AGL-3722).\n if (unit.screen) return aiStandaloneScreenCreditRange(unit.screen.sections.length)\n if (unit.creation) return aiCreditRangeOf(aiCreationMeasuredCredits(unit.creation.kind, { standalone: true }), ceiling)\n const passes = Math.ceil(ceiling / AI_SITE_PASS_CREDITS)\n return aiCreditRangeOf(\n { median: passes * AI_MEASURED_PASS_CREDITS.median, p90: passes * AI_MEASURED_PASS_CREDITS.p90 },\n ceiling,\n )\n}\n\n/**\n * What a build is likely to cost, its p90 and its ceiling (AGL-3722): every\n * unit's range, or only the units named in `slots` — what Try again runs.\n * The plan card, Try again and the Free admission all read this; the meter\n * charges what actually runs.\n */\nexport function aiBuildCreditRange(\n plan: AiBuildPlan,\n options: { ops?: AiBuildOps; slots?: ReadonlySet<string> } = {},\n): AiCreditRange {\n return aiCreditRangeOrdered(\n aiBuildUnits(plan)\n .filter((unit) => !options.slots || options.slots.has(unit.slot))\n .reduce((total, unit) => aiCreditRangeAdd(total, aiBuildUnitCreditRange(unit, options.ops)), AI_CREDIT_RANGE_ZERO),\n )\n}\n\n/** `aiJobCreditEstimate` as a range (AGL-3722). */\nexport function aiJobCreditRange(kind: string, plan: AiBuildPlan): AiCreditRange {\n return kind === 'build' ? aiBuildCreditRange(plan) : aiJobPlanCreditRange(kind, plan)\n}\n\n/**\n * A smaller first build (AGL-3722): the plan's home page — its first page\n * where it has no home — and only what that page needs, transitively: the\n * layout it is drawn in, the form and anything else its sections place.\n * Every other page, and what only they needed, waits for a later request.\n * `null` when the plan has no page, or when the smaller plan is the whole one.\n */\nexport function aiBuildFirstPagePlan<T extends AiBuildPlan>(plan: T): T | null {\n if (!plan.screens.length) return null\n const index = Math.max(0, plan.screens.findIndex(aiSitePlanIsHome))\n const units = aiBuildUnits(plan)\n const bySlot = new Map(units.map((unit) => [unit.slot, unit]))\n const keep = new Set<string>()\n const queue = [`p${index}`]\n while (queue.length) {\n const slot = queue.shift() as string\n if (keep.has(slot)) continue\n keep.add(slot)\n for (const dep of bySlot.get(slot)?.deps ?? []) queue.push(dep)\n }\n if (keep.size === units.length) return null\n const screen = plan.screens[index]\n const create = plan.create.filter((creation, at) => !AI_BUILD_CREATE_KINDS.includes(creation.kind) || keep.has(`c${at}`))\n const items = (plan.items ?? []).filter((item) => keep.has(item.slot))\n const kept = new Set([screen.slug, ...create.map((entry) => `${AI_PLAN_NEW_REF_PREFIX}${entry.name}`)])\n return {\n ...plan,\n create,\n screens: [screen],\n ...(plan.items ? { items } : {}),\n ...(plan.embeds ? { embeds: plan.embeds.filter((embed) => kept.has(embed.where)) } : {}),\n }\n}\n\n/** The smaller first build a build that does not fit is offered (AGL-3722), with its range; `null` when there is none. */\nexport function aiBuildSmaller(plan: AiBuildPlan, ops?: AiBuildOps): AiCreditsSmaller | null {\n const smaller = aiBuildFirstPagePlan(plan)\n if (!smaller) return null\n const screen = smaller.screens[0]\n const label = aiSitePlanIsHome(screen) ? AI_SITE_HOME_FIRST_LABEL : `Build the ${screen.title} page first`\n return { label, ...aiBuildCreditRange(smaller, { ops }) }\n}\n\n/** A fresh ledger: one pending row per unit, first attempt. */\nexport function aiBuildInitialLedger(units: readonly AiBuildUnit[]): AiJobItemLedger[] {\n return units.map((unit) => ({\n slot: unit.slot,\n op: unit.op,\n label: unit.label,\n status: 'pending',\n attempt: 1,\n creditsSpent: 0,\n attemptCredits: 0,\n creditsRefunded: 0,\n failure: null,\n outputs: [],\n }))\n}\n\nconst OPEN: readonly AiJobItemStatus[] = ['pending', 'running']\n\n/** Whether an item is still to be built. */\nexport function aiBuildItemOpen(row: Pick<AiJobItemLedger, 'status'>): boolean {\n return OPEN.includes(row.status)\n}\n\n/** Whether an item delivered: built as planned, or built without something that failed. */\nexport function aiBuildItemDelivered(row: Pick<AiJobItemLedger, 'status'>): boolean {\n return row.status === 'succeeded' || row.status === 'degraded'\n}\n\n/**\n * The next unit to build: the first in build order whose row is still open.\n * Its dependencies come before it, so by then each is settled one way or the\n * other. `null` when nothing is left.\n */\nexport function aiBuildNextUnit(\n ordered: readonly AiBuildUnit[],\n ledger: readonly AiJobItemLedger[],\n): AiBuildUnit | null {\n const rows = new Map(ledger.map((row) => [row.slot, row]))\n return ordered.find((unit) => {\n const row = rows.get(unit.slot)\n return !row || aiBuildItemOpen(row)\n }) ?? null\n}\n\n/** How a unit is built given what its dependencies came to. */\nexport interface AiBuildDegradation {\n /** The unit is not built at all, with the sentence why; nothing is spent. */\n skip: string | null\n /** The failed dependencies that change how it is built. */\n degradedBy: string[]\n /** What the person reads about the change; one per failed dependency. */\n notes: string[]\n /** `new:<name>` references (lowercased names) to leave out. */\n dropped: Set<string>\n /** Brief lines for the unit's own job: what to leave out, and what to place. */\n briefLines: string[]\n}\n\n/**\n * How a unit is built when some of what it depends on failed (AGL-3616).\n *\n * A PAGE is always built: a failed layout falls back to the site's own, a\n * failed form or component is left out of its section, and a failed item a\n * section places (a booking service) takes its block out of the page — each\n * with a note. Any OTHER unit whose dependency failed is skipped when that\n * dependency's capability says `omit` (a campaign whose email design failed\n * has nothing to send), and built without it when it says `fallback`.\n */\nexport function aiBuildDegradation(\n unit: AiBuildUnit,\n context: {\n units: readonly AiBuildUnit[]\n ledger: readonly AiJobItemLedger[]\n ops?: AiBuildOps\n },\n): AiBuildDegradation {\n const rows = new Map(context.ledger.map((row) => [row.slot, row]))\n const bySlot = new Map(context.units.map((one) => [one.slot, one]))\n const result: AiBuildDegradation = { skip: null, degradedBy: [], notes: [], dropped: new Set(), briefLines: [] }\n for (const slot of unit.deps) {\n const dep = bySlot.get(slot)\n const row = rows.get(slot)\n if (!dep || !row || aiBuildItemDelivered(row)) continue\n const noun = dep.creation\n ? aiBuildCreationNoun(dep.creation.kind)\n : (context.ops?.get(dep.op)?.noun ?? dep.op)\n const capability = dep.item ? context.ops?.get(dep.op) : undefined\n const degrade = dep.item?.degrade ?? capability?.degrade ?? (dep.creation?.kind === 'layout' ? 'fallback' : 'omit')\n // A form whose dataset could not be made is built without it (AGL-3616):\n // its submissions reach the Inbox, as any form's do.\n if (aiBuildUnitWritesTo(unit) === dep.label.toLowerCase()) {\n result.degradedBy.push(slot)\n result.notes.push(`Its submissions arrive in the Inbox only: the dataset “${dep.label}” could not be created.`)\n continue\n }\n if (!unit.screen && degrade === 'omit') {\n result.skip = `Not built: the ${noun} “${dep.label}” it needs could not be created.`\n result.degradedBy.push(slot)\n return result\n }\n result.degradedBy.push(slot)\n result.dropped.add(dep.label.toLowerCase())\n if (dep.creation?.kind === 'layout') {\n result.notes.push(`Built inside the site’s own layout: the layout “${dep.label}” could not be created.`)\n continue\n }\n if (unit.screen) {\n const section = unit.screen.sections.find((one) =>\n one.uses.some((ref) => isAiPlanNewRef(ref) && aiBuildRefName(ref) === dep.label.toLowerCase()),\n )\n const blocks = capability?.pageBlocks?.length ? ` the ${capability.pageBlocks.join(' or ')} block` : ''\n result.notes.push(\n `Built without${blocks || ` the ${noun}`}: the ${noun} “${dep.label}” could not be created.`,\n )\n result.briefLines.push(\n `${section ? `Build the “${section.name}” section` : 'Build the page'} without the ${noun} “${dep.label}”${blocks ? ` and without${blocks}` : ''}: it could not be created.`,\n )\n } else {\n result.notes.push(`Built without the ${noun} “${dep.label}”: it could not be created.`)\n }\n }\n return result\n}\n\n/** The dataset a form unit writes to, by its `new:` name lowercased; `null` for any other unit (AGL-3616). */\nexport function aiBuildUnitWritesTo(unit: Pick<AiBuildUnit, 'creation'>): string | null {\n const ref = unit.creation?.kind === 'form' ? unit.creation.writesTo : null\n return isAiPlanNewRef(ref) ? aiBuildRefName(ref) : null\n}\n\n/** What each creation is called in a note. */\nexport function aiBuildCreationNoun(kind: AiBuildPlanCreateKind): string {\n return kind === 'email' ? 'email design' : kind === 'theme-change' ? 'theme change' : kind\n}\n\n/**\n * The brief lines a page is told about the items its sections place and\n * that were built: the block to put there, in the owner's words.\n */\nexport function aiBuildPlacedItemLines(\n unit: AiBuildUnit,\n context: { units: readonly AiBuildUnit[]; ledger: readonly AiJobItemLedger[]; ops?: AiBuildOps },\n): string[] {\n if (!unit.screen) return []\n const rows = new Map(context.ledger.map((row) => [row.slot, row]))\n const lines: string[] = []\n for (const section of unit.screen.sections) {\n for (const ref of section.uses) {\n if (!isAiPlanNewRef(ref)) continue\n const dep = context.units.find((one) => one.item && one.item.name.toLowerCase() === aiBuildRefName(ref))\n if (!dep?.item) continue\n const row = rows.get(dep.slot)\n if (!row || !aiBuildItemDelivered(row)) continue\n const capability = context.ops?.get(dep.op)\n const blocks = capability?.pageBlocks ?? []\n if (!blocks.length) continue\n lines.push(\n `In the “${section.name}” section, place the ${blocks.join(' or ')} block for the ${capability?.noun ?? dep.op} “${dep.label}”.`,\n )\n }\n }\n return lines\n}\n\n/** What a build came to: whether anything was delivered, and whether anything is left. */\nexport function aiBuildSettlement(ledger: readonly AiJobItemLedger[]): {\n delivered: boolean\n open: boolean\n failed: number\n} {\n return {\n delivered: ledger.some(aiBuildItemDelivered),\n open: ledger.some(aiBuildItemOpen),\n failed: ledger.filter((row) => row.status === 'failed').length,\n }\n}\n\n/**\n * The ledger Try again runs (AGL-3616): every failed item back to `pending`\n * on its next attempt, with the items left unbuilt because of it — skipped,\n * or degraded with no draft — and every item the build never reached. An\n * item that succeeded is never run again, and a degraded page that has its\n * draft keeps it, with a note that the page needs an edit. `retried` names\n * the slots that will run, which is what the estimate is shown for.\n */\nexport function aiBuildRetryLedger(\n ledger: readonly AiJobItemLedger[],\n units: readonly AiBuildUnit[],\n): { ledger: AiJobItemLedger[]; retried: string[] } {\n const failed = new Set(ledger.filter((row) => row.status === 'failed').map((row) => row.slot))\n const dependents = new Map<string, string[]>()\n for (const unit of units) {\n for (const dep of unit.deps) dependents.set(dep, [...(dependents.get(dep) ?? []), unit.slot])\n }\n // Everything downstream of a failed item, transitively.\n const downstream = new Set<string>()\n const queue = [...failed]\n while (queue.length) {\n const slot = queue.shift() as string\n for (const next of dependents.get(slot) ?? []) {\n if (downstream.has(next)) continue\n downstream.add(next)\n queue.push(next)\n }\n }\n const retried: string[] = []\n const next = ledger.map((row): AiJobItemLedger => {\n const again =\n row.status === 'failed' ||\n (row.status === 'skipped' && (downstream.has(row.slot) || !(row.degradedBy ?? []).length)) ||\n (row.status === 'degraded' && downstream.has(row.slot) && !row.outputs.length)\n if (again) {\n retried.push(row.slot)\n return {\n ...row,\n status: 'pending',\n attempt: row.attempt + 1,\n attemptCredits: 0,\n failure: null,\n note: null,\n degradedBy: [],\n settledAt: null,\n }\n }\n if (row.status === 'degraded' && downstream.has(row.slot) && row.outputs.length) {\n return {\n ...row,\n note: `${row.note ? `${row.note} ` : ''}It keeps its draft: once the rest is built, edit this page to add what it is missing.`,\n }\n }\n return row\n })\n return { ledger: next, retried }\n}\n\n/**\n * Units read back off a ledger alone (AGL-3616), for a job whose units are\n * not a build plan's — a site scaffold's: each row as its unit, and every\n * page built after the layouts and forms the ledger holds.\n */\nexport function aiLedgerUnits(ledger: readonly AiJobItemLedger[]): AiBuildUnit[] {\n const creations = ledger.filter((row) => row.op === 'layout' || row.op === 'form').map((row) => row.slot)\n return ledger.map((row) => ({\n slot: row.slot,\n op: row.op,\n label: row.label,\n deps: row.op === 'page' ? creations : [],\n }))\n}\n"],"names":["pluginAiCapabilityArgsProblems","AI_PLAN_NEW_REF_PREFIX","isAiPlanNewRef","AI_SITE_HOME_FIRST_LABEL","AI_SITE_MAX_SECTIONS","AI_SITE_PASS_CREDITS","aiCreationMeasuredCredits","aiJobPlanCreditEstimate","aiJobPlanCreditRange","aiSitePlanIsHome","aiStandaloneScreenCreditRange","AI_CREDIT_RANGE_ZERO","AI_MEASURED_PASS_CREDITS","aiCreditRangeAdd","aiCreditRangeOf","aiCreditRangeOrdered","AI_BUILD_LIMITS","units","pages","freePages","aiBuildFreePageCapNote","plan","freeTaste","cap","screens","length","AI_BUILD_CREATE_KINDS","AI_BUILD_STRUCTURAL_OPS","AI_BUILD_PUBLISH_INPUT","creationOp","creation","kind","namedSlots","slots","Map","create","forEach","index","includes","set","name","toLowerCase","item","items","slot","aiBuildRefName","ref","slice","trim","aiBuildScreenRefs","screen","layout","template","duplicateOf","sections","flatMap","section","uses","filter","aiBuildUnits","depsOf","refs","self","deps","get","push","op","label","writesTo","dependsOn","title","aiBuildOrder","ordered","placed","Set","known","map","unit","next","find","has","every","dep","add","aiBuildGraphProblems","problems","aiBuildPageLimit","aiBuildPlanShapeRefusal","options","counts","slugs","slug","graph","ops","capability","freeAllowed","aiArticle","noun","argsSchema","args","join","count","maxPerPlan","test","unitPasses","aiBuildUnitCreditEstimate","credits","Math","max","floor","estimateCredits","aiBuildCreditEstimate","reduce","total","aiJobCreditEstimate","aiBuildUnitCreditRange","ceiling","standalone","passes","ceil","median","p90","aiBuildCreditRange","aiJobCreditRange","aiBuildFirstPagePlan","findIndex","bySlot","keep","queue","shift","size","at","kept","entry","embeds","embed","where","aiBuildSmaller","smaller","aiBuildInitialLedger","status","attempt","creditsSpent","attemptCredits","creditsRefunded","failure","outputs","OPEN","aiBuildItemOpen","row","aiBuildItemDelivered","aiBuildNextUnit","ledger","rows","aiBuildDegradation","context","one","result","skip","degradedBy","notes","dropped","briefLines","aiBuildCreationNoun","undefined","degrade","aiBuildUnitWritesTo","some","blocks","pageBlocks","aiBuildPlacedItemLines","lines","aiBuildSettlement","delivered","open","failed","aiBuildRetryLedger","dependents","downstream","retried","again","note","settledAt","aiLedgerUnits","creations"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,8BAA8B,QAEzB,qDAAoD;AAC3D,SACEC,sBAAsB,EACtBC,cAAc,QAMT,qBAAiB;AAExB,SACEC,wBAAwB,EACxBC,oBAAoB,EACpBC,oBAAoB,EACpBC,yBAAyB,EACzBC,uBAAuB,EACvBC,oBAAoB,EACpBC,gBAAgB,EAChBC,6BAA6B,QACxB,mBAAe;AACtB,SACEC,oBAAoB,EACpBC,wBAAwB,EACxBC,gBAAgB,EAChBC,eAAe,EACfC,oBAAoB,QAGf,0BAAsB;AAE7B;;;;;;;;;;;;;;;;;CAiBC,GAED,sFAAsF,GACtF,OAAO,MAAMC,kBAAkB;IAC7B,yCAAyC,GACzCC,OAAO;IACPC,OAAO;IACP,8BAA8B,GAC9BC,WAAW;AACb,EAAU;AAEV;;;;;;CAMC,GACD,OAAO,SAASC,uBAAuBC,IAAkC,EAAEC,SAAkB;IAC3F,MAAMC,MAAMP,gBAAgBG,SAAS;IACrC,IAAI,CAACG,aAAaD,KAAKG,OAAO,CAACC,MAAM,GA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G,QAAQ1E;QAAMqG;IAAQ;AACjC;AAEA;;;;CAIC,GACD,OAAO,SAASI,cAAc/B,MAAkC;IAC9D,MAAMgC,YAAYhC,OAAO9F,MAAM,CAAC,CAAC2F,MAAQA,IAAInF,EAAE,KAAK,YAAYmF,IAAInF,EAAE,KAAK,QAAQU,GAAG,CAAC,CAACyE,MAAQA,IAAIzG,IAAI;IACxG,OAAO4G,OAAO5E,GAAG,CAAC,CAACyE,MAAS,CAAA;YAC1BzG,MAAMyG,IAAIzG,IAAI;YACdsB,IAAImF,IAAInF,EAAE;YACVC,OAAOkF,IAAIlF,KAAK;YAChBJ,MAAMsF,IAAInF,EAAE,KAAK,SAASsH,YAAY,EAAE;QAC1C,CAAA;AACF"}
|
|
@@ -79,6 +79,15 @@ export interface AiBuildPlanCreate {
|
|
|
79
79
|
* palette paths it adds or changes.
|
|
80
80
|
*/
|
|
81
81
|
fields: string[];
|
|
82
|
+
/**
|
|
83
|
+
* A form only: the dataset each of its submissions is also written to as a
|
|
84
|
+
* record (AGL-3616, Zach 2026-10-10: a volunteer sign-up writing to a
|
|
85
|
+
* Volunteers dataset) — `new:<name>` of a dataset this plan creates, or a
|
|
86
|
+
* dataset id from the inventory. Said by the plan, never inferred from a
|
|
87
|
+
* section's `uses`. Absent or null on every other creation, and on a form
|
|
88
|
+
* whose submissions only reach the Inbox.
|
|
89
|
+
*/
|
|
90
|
+
writesTo?: string | null;
|
|
82
91
|
/**
|
|
83
92
|
* The id the draft this creation becomes is written under, where a unit of
|
|
84
93
|
* the job builds it (AGL-3079). Minted when the job keeps the plan, never
|
|
@@ -248,9 +257,10 @@ export declare const AI_PLAN_ASKS_FOR_VIDEO: RegExp;
|
|
|
248
257
|
*/
|
|
249
258
|
export declare const AI_BUILD_PLAN_EMBEDS_TOOL: AiTool;
|
|
250
259
|
/**
|
|
251
|
-
* The plan tools with a record template on every screen (AGL-3475)
|
|
252
|
-
*
|
|
253
|
-
* may
|
|
260
|
+
* The plan tools with a record template on every screen (AGL-3475) and the
|
|
261
|
+
* dataset a form writes to on every creation (AGL-3616), offered only where
|
|
262
|
+
* the job may bind a dataset: a site with a dataset, or a job that may create
|
|
263
|
+
* one. Record pages are a Starter feature, and every other plan's
|
|
254
264
|
* request is the plain tool, byte for byte, so the field costs a Free taste
|
|
255
265
|
* nothing and a model planning a site with no dataset has none to bind.
|
|
256
266
|
*/
|
|
@@ -305,6 +315,16 @@ export declare function aiPlanRecordBase(base: string): string | null;
|
|
|
305
315
|
export declare function isAiPlanNewRef(ref: string | null | undefined): ref is string;
|
|
306
316
|
/** The creation a `new:<name>` reference names, case-insensitively. */
|
|
307
317
|
export declare function aiPlanCreateFor(plan: AiBuildPlan, ref: string): AiBuildPlanCreate | undefined;
|
|
318
|
+
/** The operation a build's dataset item is planned as (AGL-3616), owned by the data plugin. */
|
|
319
|
+
export declare const AI_PLAN_DATASET_ITEM_OP = "dataset";
|
|
320
|
+
/**
|
|
321
|
+
* The datasets this plan makes that one of its forms writes its submissions
|
|
322
|
+
* to (AGL-3616), by name lowercased: a dataset creation of a site start, or a
|
|
323
|
+
* build's dataset item. Such a dataset starts with no records — its records
|
|
324
|
+
* are the submissions — so a site start designs it from its planned fields
|
|
325
|
+
* with no model, and no page lists it.
|
|
326
|
+
*/
|
|
327
|
+
export declare function aiPlanFormDatasetNames(plan: Pick<AiBuildPlan, 'create'> & Partial<Pick<AiBuildPlan, 'items'>>): Set<string>;
|
|
308
328
|
/** The item a `new:<name>` reference names, case-insensitively (AGL-3616). */
|
|
309
329
|
export declare function aiPlanItemFor(plan: Pick<AiBuildPlan, 'items'>, ref: string): AiBuildItem | undefined;
|
|
310
330
|
/** A slug as two spellings of one path compare: lowercase, one leading slash, no trailing one. */
|
|
@@ -340,12 +340,29 @@ const RECORD_SCHEMA = {
|
|
|
340
340
|
],
|
|
341
341
|
description: "When this page is one dataset's record template, serving a page per record at /<base>/<record address> with its copy bound as {{item.<field>}}: the dataset and the base. Otherwise null."
|
|
342
342
|
};
|
|
343
|
-
|
|
343
|
+
const WRITES_TO_SCHEMA = nullableString('A form only, and only where each submission should also be kept as a record (a volunteer sign-up, an RSVP, an inquiry): the dataset it writes to, as new:<name> of a dataset this plan creates or a dataset id from the inventory. Otherwise null.');
|
|
344
|
+
/**
|
|
345
|
+
* A plan tool whose screens each name the dataset they are the record
|
|
346
|
+
* template of, or null, and whose creations each name the dataset a form
|
|
347
|
+
* writes its submissions to, or null (AGL-3616).
|
|
348
|
+
*/ function withRecords(tool) {
|
|
344
349
|
const properties = tool.inputSchema['properties'];
|
|
345
350
|
const screens = properties['screens'];
|
|
351
|
+
const create = properties['create'];
|
|
346
352
|
return _extends({}, tool, {
|
|
347
353
|
inputSchema: _extends({}, tool.inputSchema, {
|
|
348
354
|
properties: _extends({}, properties, {
|
|
355
|
+
create: _extends({}, create, {
|
|
356
|
+
items: _extends({}, create.items, {
|
|
357
|
+
required: [
|
|
358
|
+
...create.items['required'],
|
|
359
|
+
'writesTo'
|
|
360
|
+
],
|
|
361
|
+
properties: _extends({}, create.items['properties'], {
|
|
362
|
+
writesTo: WRITES_TO_SCHEMA
|
|
363
|
+
})
|
|
364
|
+
})
|
|
365
|
+
}),
|
|
349
366
|
screens: _extends({}, screens, {
|
|
350
367
|
items: _extends({}, screens.items, {
|
|
351
368
|
required: [
|
|
@@ -362,9 +379,10 @@ const RECORD_SCHEMA = {
|
|
|
362
379
|
});
|
|
363
380
|
}
|
|
364
381
|
/**
|
|
365
|
-
* The plan tools with a record template on every screen (AGL-3475)
|
|
366
|
-
*
|
|
367
|
-
* may
|
|
382
|
+
* The plan tools with a record template on every screen (AGL-3475) and the
|
|
383
|
+
* dataset a form writes to on every creation (AGL-3616), offered only where
|
|
384
|
+
* the job may bind a dataset: a site with a dataset, or a job that may create
|
|
385
|
+
* one. Record pages are a Starter feature, and every other plan's
|
|
368
386
|
* request is the plain tool, byte for byte, so the field costs a Free taste
|
|
369
387
|
* nothing and a model planning a site with no dataset has none to bind.
|
|
370
388
|
*/ export const AI_BUILD_PLAN_RECORDS_TOOL = withRecords(AI_BUILD_PLAN_TOOL);
|
|
@@ -565,13 +583,18 @@ export function parseAiBuildPlan(input) {
|
|
|
565
583
|
names.add(key);
|
|
566
584
|
const kind = oneOf(entry['kind'], AI_BUILD_PLAN_CREATE_KINDS, `create[${index}].kind`);
|
|
567
585
|
const fields = list((_entry_fields = entry['fields']) != null ? _entry_fields : [], `create[${index}].fields`, AI_BUILD_PLAN_LIMITS.fields).map((field, fieldIndex)=>text(field, `create[${index}].fields[${fieldIndex}]`)).filter(Boolean);
|
|
568
|
-
|
|
586
|
+
// Only a form writes its submissions to a dataset (AGL-3616); kept
|
|
587
|
+
// only where it says one, so a plan without one reads as it always did.
|
|
588
|
+
const writesTo = kind === 'form' ? nullable(entry['writesTo'], `create[${index}].writesTo`) : null;
|
|
589
|
+
return _extends({
|
|
569
590
|
kind,
|
|
570
591
|
name,
|
|
571
592
|
why: text(entry['why'], `create[${index}].why`),
|
|
572
593
|
duplicateOf: nullable(entry['duplicateOf'], `create[${index}].duplicateOf`),
|
|
573
594
|
fields: kind === 'layout' ? aiPlanLayoutRegionWords(fields) : fields
|
|
574
|
-
}
|
|
595
|
+
}, writesTo ? {
|
|
596
|
+
writesTo
|
|
597
|
+
} : {});
|
|
575
598
|
});
|
|
576
599
|
const screens = list(root['screens'], 'screens', AI_BUILD_PLAN_LIMITS.screens).map((raw, index)=>{
|
|
577
600
|
const entry = record(raw, `screens[${index}]`);
|
|
@@ -681,6 +704,24 @@ export function parseAiBuildPlan(input) {
|
|
|
681
704
|
const name = ref.slice(AI_PLAN_NEW_REF_PREFIX.length).trim().toLowerCase();
|
|
682
705
|
return plan.create.find((entry)=>entry.name.toLowerCase() === name);
|
|
683
706
|
}
|
|
707
|
+
/** The operation a build's dataset item is planned as (AGL-3616), owned by the data plugin. */ export const AI_PLAN_DATASET_ITEM_OP = 'dataset';
|
|
708
|
+
/**
|
|
709
|
+
* The datasets this plan makes that one of its forms writes its submissions
|
|
710
|
+
* to (AGL-3616), by name lowercased: a dataset creation of a site start, or a
|
|
711
|
+
* build's dataset item. Such a dataset starts with no records — its records
|
|
712
|
+
* are the submissions — so a site start designs it from its planned fields
|
|
713
|
+
* with no model, and no page lists it.
|
|
714
|
+
*/ export function aiPlanFormDatasetNames(plan) {
|
|
715
|
+
const names = new Set();
|
|
716
|
+
for (const entry of plan.create){
|
|
717
|
+
var _plan_items;
|
|
718
|
+
if (entry.kind !== 'form' || !isAiPlanNewRef(entry.writesTo)) continue;
|
|
719
|
+
const name = entry.writesTo.slice(AI_PLAN_NEW_REF_PREFIX.length).trim().toLowerCase();
|
|
720
|
+
const made = plan.create.some((one)=>one.kind === 'dataset' && one.name.trim().toLowerCase() === name) || ((_plan_items = plan.items) != null ? _plan_items : []).some((one)=>one.op === AI_PLAN_DATASET_ITEM_OP && one.name.trim().toLowerCase() === name);
|
|
721
|
+
if (made) names.add(name);
|
|
722
|
+
}
|
|
723
|
+
return names;
|
|
724
|
+
}
|
|
684
725
|
/** The item a `new:<name>` reference names, case-insensitively (AGL-3616). */ export function aiPlanItemFor(plan, ref) {
|
|
685
726
|
var _plan_items;
|
|
686
727
|
if (!isAiPlanNewRef(ref)) return undefined;
|