@aglyn/plugins-ai 1.16.0 → 1.18.0

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.
Files changed (39) hide show
  1. package/package.json +17 -17
  2. package/src/lib/jobs/ai-job-import-step.js +7 -4
  3. package/src/lib/jobs/ai-job-import-step.js.map +1 -1
  4. package/src/lib/jobs/ai-job-page-step.js +7 -4
  5. package/src/lib/jobs/ai-job-page-step.js.map +1 -1
  6. package/src/lib/jobs/ai-layout-stock-photos.d.ts +9 -0
  7. package/src/lib/jobs/ai-layout-stock-photos.js +4 -0
  8. package/src/lib/jobs/ai-layout-stock-photos.js.map +1 -1
  9. package/src/lib/jobs/ai-site-import-actions.d.ts +35 -0
  10. package/src/lib/jobs/ai-site-import-actions.js +215 -0
  11. package/src/lib/jobs/ai-site-import-actions.js.map +1 -0
  12. package/src/lib/jobs/ai-site-import-compile.d.ts +7 -0
  13. package/src/lib/jobs/ai-site-import-compile.js +34 -4
  14. package/src/lib/jobs/ai-site-import-compile.js.map +1 -1
  15. package/src/lib/jobs/ai-site-import-improve.d.ts +13 -1
  16. package/src/lib/jobs/ai-site-import-improve.js +153 -12
  17. package/src/lib/jobs/ai-site-import-improve.js.map +1 -1
  18. package/src/lib/jobs/ai-site-import-pictures.js +4 -2
  19. package/src/lib/jobs/ai-site-import-pictures.js.map +1 -1
  20. package/src/lib/jobs/ai-site-import-plan.d.ts +67 -1
  21. package/src/lib/jobs/ai-site-import-plan.js +173 -4
  22. package/src/lib/jobs/ai-site-import-plan.js.map +1 -1
  23. package/src/lib/layout-language/ai-layout-compiler.js +13 -15
  24. package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
  25. package/src/lib/model/ai-site-import-fidelity.d.ts +6 -0
  26. package/src/lib/model/ai-site-import-fidelity.js +88 -10
  27. package/src/lib/model/ai-site-import-fidelity.js.map +1 -1
  28. package/src/lib/model/ai-site-import-ledger.js +10 -2
  29. package/src/lib/model/ai-site-import-ledger.js.map +1 -1
  30. package/src/lib/model/ai-site-import-marks.d.ts +37 -0
  31. package/src/lib/model/ai-site-import-marks.js +53 -0
  32. package/src/lib/model/ai-site-import-marks.js.map +1 -0
  33. package/src/lib/model/ai-site-import.d.ts +11 -1
  34. package/src/lib/model/ai-site-import.js +14 -2
  35. package/src/lib/model/ai-site-import.js.map +1 -1
  36. package/src/lib/runtime/ai-node-tree.js +8 -0
  37. package/src/lib/runtime/ai-node-tree.js.map +1 -1
  38. package/src/lib/site-import/site-import-images.js +9 -6
  39. package/src/lib/site-import/site-import-images.js.map +1 -1
@@ -35,6 +35,7 @@
35
35
  import { aiLayoutPictureBandCells } from "../layout-language/ai-layout-pictures.js";
36
36
  import { AI_SITE_IMPORT_GENERATED_PICTURES_PER_PAGE } from "../model/ai-site-import.js";
37
37
  import { aiMediaCreditsPerPicture } from "../model/ai-media-credits.js";
38
+ import { aiSiteImportIsBrandMark } from "../model/ai-site-import-marks.js";
38
39
  import { estimateAiBilledUsd } from "../providers/catalog.js";
39
40
  import { AiImageSafetyRefusal } from "../providers/image-contract.js";
40
41
  import { aiImageAltText, aiImageFileName } from "../server/ai-media-image.js";
@@ -72,8 +73,9 @@ export function aiSiteImportPictureTally() {
72
73
  */ export function aiSiteImportPictureSource(input) {
73
74
  var _input_cap;
74
75
  const { next, make, tally } = input;
75
- // A photo the library holds no size for cannot be framed.
76
- const photos = input.photos.filter((photo)=>photo.width && photo.height);
76
+ // A photo the library holds no size for cannot be framed, and a brand's mark is no photo (AGL-4152): a slot is a
77
+ // photo's place, and a client's logo filled a page's cover.
78
+ const photos = input.photos.filter((photo)=>photo.width && photo.height && !aiSiteImportIsBrandMark(photo));
77
79
  if (!photos.length && !next && !make) return null;
78
80
  const froms = new Map(photos.map((photo)=>{
79
81
  var _photo_from;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-site-import-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\n/*==========================================\n * IMPROVE IT, GENERATIVE: A REDESIGNED PAGE'S PICTURES (AGL-4152).\n *\n * A redesign may ask for a picture where its own do not fit: a slot, which\n * `aiResolveLayoutPictures` fills or drops. This is the order it fills from,\n * first to last:\n *\n * 1. the page's own photos no `keep` placed;\n * 2. the source photos the site's earlier pages left off;\n * 3. what the site's own photo links hold, then the stock library\n * (`aiLayoutSitePhotoSource`): no credits, copied into the library, its\n * photographer kept, its brand-tag refusal held;\n * 4. only where the owner switched them on, and it is quoted, a generated\n * picture: a hero or a section's lead, never a person or a product, at most\n * `AI_SITE_IMPORT_GENERATED_PICTURES_PER_PAGE` a page.\n *\n * A slot nothing fills is dropped, and the row around it redraws without a gap\n * (`aiLayoutDropEmptyPictures`). The tally is what the page's row says.\n *=========================================*/\n\nimport type { PluginMediaIngest } from '@aglyn/aglyn/plugin-manager/plugin-media-ingest'\nimport { aiLayoutPictureBandCells, type AiLayoutPicturePhoto, type AiLayoutPictureSlot, type AiLayoutPictureSource } from '../layout-language/ai-layout-pictures'\nimport { AI_SITE_IMPORT_GENERATED_PICTURES_PER_PAGE, type AiSiteImportPagePictures, type AiSiteImportPhoto } from '../model/ai-site-import'\nimport { aiMediaCreditsPerPicture } from '../model/ai-media-credits'\nimport { estimateAiBilledUsd } from '../providers/catalog'\nimport { AiImageSafetyRefusal, type AiImageAspectRatio, type AiImageProvider } from '../providers/image-contract'\nimport { aiImageAltText, aiImageFileName } from '../server/ai-media-image'\nimport { aiMediaRasterPrompt } from '../server/ai-media-raster-prompt'\nimport { recordAssistCost } from '../usage/assist-usage'\nimport { aiAssignOwnerPhotos } from './ai-layout-owner-photos'\n\ntype NodesMap = Parameters<typeof aiLayoutPictureBandCells>[0]\n\n/** How long one generated picture is waited on: a picture is decoration, and a page never fails over one. */\nexport const AI_SITE_IMPORT_GENERATED_PICTURE_MS = 40_000\n\n/** What a slot's picture came from, as the page's row tells it. */\nexport interface AiSiteImportPictureTally {\n source: number\n stock: number\n generated: number\n /** What the generated pictures cost at the billed rates. */\n generatedUsd: number\n /** The addresses of the source's photos a slot took. */\n placed: string[]\n}\n\nexport function aiSiteImportPictureTally(): AiSiteImportPictureTally {\n return { source: 0, stock: 0, generated: 0, generatedUsd: 0, placed: [] }\n}\n\n/** A generated picture for a slot, stored and metered; `null` where it could not be made or kept. */\nexport type AiSiteImportPictureMaker = (slot: AiLayoutPictureSlot, tally: AiSiteImportPictureTally) => Promise<AiLayoutPicturePhoto | null>\n\n/** The words that say a picture shows a person: a generated one would show someone who does not exist as if they did. */\nconst SHOWS_PEOPLE = /\\b(?:team|staff|crew|owner|owners|founder|founders|person|people|portrait|headshot|family|families|customer|customers|client|clients|patient|patients|doctor|dentist|stylist|therapist|attorney|lawyer|accountant)\\b/i\n\n/**\n * Which slots may take a generated picture (AGL-4152): the page's hero, or the\n * first picture of a section that is no cell of a band, and none that shows a\n * person, a product or a record's own thing.\n */\nexport function aiSiteImportGeneratedSlots(nodes: NodesMap, slots: readonly AiLayoutPictureSlot[]): boolean[] {\n const cells = aiLayoutPictureBandCells(nodes, slots)\n const seen = new Set<number>()\n return slots.map((slot, index) => {\n const lead = !seen.has(slot.sectionIndex)\n seen.add(slot.sectionIndex)\n return lead && !cells[index] && !slot.product && !slot.people && !slot.record && !SHOWS_PEOPLE.test(slot.alt)\n })\n}\n\n/**\n * The source a redesigned page's slots fill from, in the order above. `next`\n * answers the slots the source's own photos leave and tallies its own stock\n * photos; a slot it leaves empty takes a generated picture where one is allowed.\n */\nexport function aiSiteImportPictureSource(input: {\n photos: readonly AiSiteImportPhoto[]\n next: AiLayoutPictureSource | null\n make?: AiSiteImportPictureMaker | null\n nodes: NodesMap\n tally: AiSiteImportPictureTally\n /** The most generated pictures this page may take. */\n cap?: number\n}): AiLayoutPictureSource | null {\n const { next, make, tally } = input\n // A photo the library holds no size for cannot be framed.\n const photos = input.photos.filter((photo) => photo.width && photo.height)\n if (!photos.length && !next && !make) return null\n const froms = new Map(photos.map((photo) => [photo.src, photo.from ?? '']))\n const cap = input.cap ?? AI_SITE_IMPORT_GENERATED_PICTURES_PER_PAGE\n return async (slots, report) => {\n const own = aiAssignOwnerPhotos(slots, photos)\n own.forEach((photo) => {\n if (!photo) return\n tally.source += 1\n const from = froms.get(photo.src)\n if (from) tally.placed.push(from)\n })\n const open = slots.filter((_slot, index) => !own[index])\n const found = next && open.length ? await next(open, report) : []\n let at = 0\n const answers = own.map((photo) => photo ?? found[at++] ?? null)\n if (!make) return answers\n const allowed = aiSiteImportGeneratedSlots(input.nodes, slots)\n let left = Math.max(0, cap)\n const out: Array<AiLayoutPicturePhoto | null> = [...answers]\n // One at a time, so the cap holds whatever each comes to: the hero first, the biggest seen first.\n const order = slots.map((slot, index) => ({ slot, index })).sort((a, b) => Number(b.slot.role === 'hero') - Number(a.slot.role === 'hero') || a.index - b.index)\n for (const { slot, index } of order) {\n if (left <= 0) break\n if (answers[index]?.src || !allowed[index]) continue\n const made = await make(slot, tally)\n if (made) {\n out[index] = made\n left -= 1\n }\n }\n return out\n }\n}\n\n/** The nearest shape the image models draw to a slot's frame. */\nexport function aiSiteImportPictureShape(aspect: number): AiImageAspectRatio {\n const shapes: ReadonlyArray<readonly [AiImageAspectRatio, number]> = [['16:9', 16 / 9], ['4:3', 4 / 3], ['1:1', 1], ['3:4', 3 / 4], ['9:16', 9 / 16]]\n const wanted = aspect > 0 && Number.isFinite(aspect) ? aspect : 4 / 3\n return [...shapes].sort((a, b) => Math.abs(a[1] - wanted) - Math.abs(b[1] - wanted))[0]?.[0] ?? '4:3'\n}\n\n/** What a generated picture is made through, and whether the workspace's meter has room for it. */\nexport interface AiSiteImportPictureMakerInput {\n provider: AiImageProvider | null\n ingest: PluginMediaIngest | null\n firestore: FirebaseFirestore.Firestore\n orgId: string\n hostId: string\n uid: string\n /** What the site is, which a picture's own words are read with. */\n about: string\n /** Whether the workspace's meter has room for a picture now. */\n roomFor?: (credits: number) => boolean\n record?: typeof recordAssistCost\n}\n\n/**\n * A generated picture through the Media door's own parts (AGL-4152): the image\n * provider at a paid plan's size, the fixed style wording, the media library's\n * ingest as an upload this member made, the same provenance on the asset, and the\n * same meter, charged only once it is stored. `null` where it cannot run here.\n */\nexport function aiSiteImportPictureMaker(input: AiSiteImportPictureMakerInput): AiSiteImportPictureMaker | null {\n const { provider, ingest } = input\n if (!provider?.configured() || !ingest) return null\n const size = '1K' as const\n return async (slot, tally) => {\n const model = provider.defaultModel()\n if (input.roomFor && !input.roomFor(aiMediaCreditsPerPicture('photo', model, size))) return null\n const words = `${slot.alt}. For a website about: ${input.about}`.replace(/\\s+/g, ' ').trim()\n const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), AI_SITE_IMPORT_GENERATED_PICTURE_MS))\n try {\n const result = await Promise.race([\n provider.generate({ model, prompt: aiMediaRasterPrompt(words, 'natural'), aspectRatio: aiSiteImportPictureShape(slot.aspect), size, count: 1 }),\n timeout,\n ])\n const image = result?.images[0]\n if (!result || !image) return null\n const alt = aiImageAltText(slot.alt)\n const stored = await ingest.ingest({\n hostId: input.hostId,\n uid: input.uid,\n fileName: aiImageFileName(slot.alt, 0, image.mimeType),\n contentType: image.mimeType,\n bytes: Buffer.from(image.base64, 'base64'),\n alt,\n description: 'Created with AI from a description.',\n })\n if (!stored.ok) return null\n const usage = { ...result.usage, images: 1, imageSize: size }\n let signalId: string | null = null\n try {\n signalId = await (input.record ?? recordAssistCost)(input.firestore, input.orgId, {\n route: 'ai/jobs',\n hostId: input.hostId,\n model,\n tier: 'entitled',\n usage,\n docsPaths: [],\n stopReason: 'end_turn',\n free: null,\n uid: input.uid,\n kind: 'image',\n })\n } catch (error) {\n console.error('ai site import: a generated picture’s usage was not recorded', { orgId: input.orgId, error })\n }\n await input.firestore\n .collection('hosts')\n .doc(input.hostId)\n .collection('media')\n .doc(stored.mediaId)\n .update({ aiGenerated: { model, prompt: slot.alt, mode: 'photo', style: 'natural', aspectRatio: aiSiteImportPictureShape(slot.aspect), signalId, generatedBy: input.uid, createdAt: new Date() } })\n .catch((error: unknown) => console.error('ai site import: a generated picture’s record was not written', { mediaId: stored.mediaId, error }))\n tally.generated += 1\n tally.generatedUsd += estimateAiBilledUsd(usage, model)\n return { src: stored.src, width: stored.width ?? 1024, height: stored.height ?? 1024, alt }\n } catch (error) {\n if (!(error instanceof AiImageSafetyRefusal)) console.warn('ai site import: a generated picture failed; its slot is dropped', { error })\n return null\n }\n }\n}\n\n/** A page's pictures, as its row reads them once its slots are filled. */\nexport function aiSiteImportPagePicturesOf(pictures: AiSiteImportPagePictures, tally: AiSiteImportPictureTally): AiSiteImportPagePictures {\n const taken = new Set(tally.placed)\n return { source: pictures.source + tally.source, stock: tally.stock, generated: tally.generated, slots: 0, unplaced: pictures.unplaced.filter((url) => !taken.has(url)) }\n}\n"],"names":["aiLayoutPictureBandCells","AI_SITE_IMPORT_GENERATED_PICTURES_PER_PAGE","aiMediaCreditsPerPicture","estimateAiBilledUsd","AiImageSafetyRefusal","aiImageAltText","aiImageFileName","aiMediaRasterPrompt","recordAssistCost","aiAssignOwnerPhotos","AI_SITE_IMPORT_GENERATED_PICTURE_MS","aiSiteImportPictureTally","source","stock","generated","generatedUsd","placed","SHOWS_PEOPLE","aiSiteImportGeneratedSlots","nodes","slots","cells","seen","Set","map","slot","index","lead","has","sectionIndex","add","product","people","record","test","alt","aiSiteImportPictureSource","input","next","make","tally","photos","filter","photo","width","height","length","froms","Map","src","from","cap","report","own","forEach","get","push","open","_slot","found","at","answers","allowed","left","Math","max","out","order","sort","a","b","Number","role","made","aiSiteImportPictureShape","aspect","shapes","wanted","isFinite","abs","aiSiteImportPictureMaker","provider","ingest","configured","size","model","defaultModel","roomFor","words","about","replace","trim","timeout","Promise","resolve","setTimeout","stored","result","race","generate","prompt","aspectRatio","count","image","images","hostId","uid","fileName","mimeType","contentType","bytes","Buffer","base64","description","ok","usage","imageSize","signalId","firestore","orgId","route","tier","docsPaths","stopReason","free","kind","error","console","collection","doc","mediaId","update","aiGenerated","mode","style","generatedBy","createdAt","Date","catch","warn","aiSiteImportPagePicturesOf","pictures","taken","unplaced","url"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;2CAkB2C;AAG3C,SAASA,wBAAwB,QAAyF,2CAAuC;AACjK,SAASC,0CAA0C,QAA+D,6BAAyB;AAC3I,SAASC,wBAAwB,QAAQ,+BAA2B;AACpE,SAASC,mBAAmB,QAAQ,0BAAsB;AAC1D,SAASC,oBAAoB,QAAuD,iCAA6B;AACjH,SAASC,cAAc,EAAEC,eAAe,QAAQ,8BAA0B;AAC1E,SAASC,mBAAmB,QAAQ,sCAAkC;AACtE,SAASC,gBAAgB,QAAQ,2BAAuB;AACxD,SAASC,mBAAmB,QAAQ,8BAA0B;AAI9D,2GAA2G,GAC3G,OAAO,MAAMC,sCAAsC,MAAM;AAazD,OAAO,SAASC;IACd,OAAO;QAAEC,QAAQ;QAAGC,OAAO;QAAGC,WAAW;QAAGC,cAAc;QAAGC,QAAQ,EAAE;IAAC;AAC1E;AAKA,uHAAuH,GACvH,MAAMC,eAAe;AAErB;;;;CAIC,GACD,OAAO,SAASC,2BAA2BC,KAAe,EAAEC,KAAqC;IAC/F,MAAMC,QAAQrB,yBAAyBmB,OAAOC;IAC9C,MAAME,OAAO,IAAIC;IACjB,OAAOH,MAAMI,GAAG,CAAC,CAACC,MAAMC;QACtB,MAAMC,OAAO,CAACL,KAAKM,GAAG,CAACH,KAAKI,YAAY;QACxCP,KAAKQ,GAAG,CAACL,KAAKI,YAAY;QAC1B,OAAOF,QAAQ,CAACN,KAAK,CAACK,MAA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IZ,oBAAoBgH,OAAO9B;YACjD,OAAO;gBAAEpC,KAAK+C,OAAO/C,GAAG;gBAAEL,KAAK,GAAEoD,gBAAAA,OAAOpD,KAAK,YAAZoD,gBAAgB;gBAAMnD,MAAM,GAAEmD,iBAAAA,OAAOnD,MAAM,YAAbmD,iBAAiB;gBAAM7D;YAAI;QAC5F,EAAE,OAAO2F,OAAO;YACd,IAAI,CAAEA,CAAAA,iBAAiB1H,oBAAmB,GAAI2H,QAAQY,IAAI,CAAC,mEAAmE;gBAAEb;YAAM;YACtI,OAAO;QACT;IACF;AACF;AAEA,wEAAwE,GACxE,OAAO,SAASc,2BAA2BC,QAAkC,EAAErG,KAA+B;IAC5G,MAAMsG,QAAQ,IAAIvH,IAAIiB,MAAMxB,MAAM;IAClC,OAAO;QAAEJ,QAAQiI,SAASjI,MAAM,GAAG4B,MAAM5B,MAAM;QAAEC,OAAO2B,MAAM3B,KAAK;QAAEC,WAAW0B,MAAM1B,SAAS;QAAEM,OAAO;QAAG2H,UAAUF,SAASE,QAAQ,CAACrG,MAAM,CAAC,CAACsG,MAAQ,CAACF,MAAMlH,GAAG,CAACoH;IAAM;AAC1K"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-site-import-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\n/*==========================================\n * IMPROVE IT, GENERATIVE: A REDESIGNED PAGE'S PICTURES (AGL-4152).\n *\n * A redesign may ask for a picture where its own do not fit: a slot, which\n * `aiResolveLayoutPictures` fills or drops. This is the order it fills from,\n * first to last:\n *\n * 1. the page's own photos no `keep` placed;\n * 2. the source photos the site's earlier pages left off;\n * 3. what the site's own photo links hold, then the stock library\n * (`aiLayoutSitePhotoSource`): no credits, copied into the library, its\n * photographer kept, its brand-tag refusal held;\n * 4. only where the owner switched them on, and it is quoted, a generated\n * picture: a hero or a section's lead, never a person or a product, at most\n * `AI_SITE_IMPORT_GENERATED_PICTURES_PER_PAGE` a page.\n *\n * A slot nothing fills is dropped, and the row around it redraws without a gap\n * (`aiLayoutDropEmptyPictures`). The tally is what the page's row says.\n *=========================================*/\n\nimport type { PluginMediaIngest } from '@aglyn/aglyn/plugin-manager/plugin-media-ingest'\nimport { aiLayoutPictureBandCells, type AiLayoutPicturePhoto, type AiLayoutPictureSlot, type AiLayoutPictureSource } from '../layout-language/ai-layout-pictures'\nimport { AI_SITE_IMPORT_GENERATED_PICTURES_PER_PAGE, type AiSiteImportPagePictures, type AiSiteImportPhoto } from '../model/ai-site-import'\nimport { aiMediaCreditsPerPicture } from '../model/ai-media-credits'\nimport { aiSiteImportIsBrandMark } from '../model/ai-site-import-marks'\nimport { estimateAiBilledUsd } from '../providers/catalog'\nimport { AiImageSafetyRefusal, type AiImageAspectRatio, type AiImageProvider } from '../providers/image-contract'\nimport { aiImageAltText, aiImageFileName } from '../server/ai-media-image'\nimport { aiMediaRasterPrompt } from '../server/ai-media-raster-prompt'\nimport { recordAssistCost } from '../usage/assist-usage'\nimport { aiAssignOwnerPhotos } from './ai-layout-owner-photos'\n\ntype NodesMap = Parameters<typeof aiLayoutPictureBandCells>[0]\n\n/** How long one generated picture is waited on: a picture is decoration, and a page never fails over one. */\nexport const AI_SITE_IMPORT_GENERATED_PICTURE_MS = 40_000\n\n/** What a slot's picture came from, as the page's row tells it. */\nexport interface AiSiteImportPictureTally {\n source: number\n stock: number\n generated: number\n /** What the generated pictures cost at the billed rates. */\n generatedUsd: number\n /** The addresses of the source's photos a slot took. */\n placed: string[]\n}\n\nexport function aiSiteImportPictureTally(): AiSiteImportPictureTally {\n return { source: 0, stock: 0, generated: 0, generatedUsd: 0, placed: [] }\n}\n\n/** A generated picture for a slot, stored and metered; `null` where it could not be made or kept. */\nexport type AiSiteImportPictureMaker = (slot: AiLayoutPictureSlot, tally: AiSiteImportPictureTally) => Promise<AiLayoutPicturePhoto | null>\n\n/** The words that say a picture shows a person: a generated one would show someone who does not exist as if they did. */\nconst SHOWS_PEOPLE = /\\b(?:team|staff|crew|owner|owners|founder|founders|person|people|portrait|headshot|family|families|customer|customers|client|clients|patient|patients|doctor|dentist|stylist|therapist|attorney|lawyer|accountant)\\b/i\n\n/**\n * Which slots may take a generated picture (AGL-4152): the page's hero, or the\n * first picture of a section that is no cell of a band, and none that shows a\n * person, a product or a record's own thing.\n */\nexport function aiSiteImportGeneratedSlots(nodes: NodesMap, slots: readonly AiLayoutPictureSlot[]): boolean[] {\n const cells = aiLayoutPictureBandCells(nodes, slots)\n const seen = new Set<number>()\n return slots.map((slot, index) => {\n const lead = !seen.has(slot.sectionIndex)\n seen.add(slot.sectionIndex)\n return lead && !cells[index] && !slot.product && !slot.people && !slot.record && !SHOWS_PEOPLE.test(slot.alt)\n })\n}\n\n/**\n * The source a redesigned page's slots fill from, in the order above. `next`\n * answers the slots the source's own photos leave and tallies its own stock\n * photos; a slot it leaves empty takes a generated picture where one is allowed.\n */\nexport function aiSiteImportPictureSource(input: {\n photos: readonly AiSiteImportPhoto[]\n next: AiLayoutPictureSource | null\n make?: AiSiteImportPictureMaker | null\n nodes: NodesMap\n tally: AiSiteImportPictureTally\n /** The most generated pictures this page may take. */\n cap?: number\n}): AiLayoutPictureSource | null {\n const { next, make, tally } = input\n // A photo the library holds no size for cannot be framed, and a brand's mark is no photo (AGL-4152): a slot is a\n // photo's place, and a client's logo filled a page's cover.\n const photos = input.photos.filter((photo) => photo.width && photo.height && !aiSiteImportIsBrandMark(photo))\n if (!photos.length && !next && !make) return null\n const froms = new Map(photos.map((photo) => [photo.src, photo.from ?? '']))\n const cap = input.cap ?? AI_SITE_IMPORT_GENERATED_PICTURES_PER_PAGE\n return async (slots, report) => {\n const own = aiAssignOwnerPhotos(slots, photos)\n own.forEach((photo) => {\n if (!photo) return\n tally.source += 1\n const from = froms.get(photo.src)\n if (from) tally.placed.push(from)\n })\n const open = slots.filter((_slot, index) => !own[index])\n const found = next && open.length ? await next(open, report) : []\n let at = 0\n const answers = own.map((photo) => photo ?? found[at++] ?? null)\n if (!make) return answers\n const allowed = aiSiteImportGeneratedSlots(input.nodes, slots)\n let left = Math.max(0, cap)\n const out: Array<AiLayoutPicturePhoto | null> = [...answers]\n // One at a time, so the cap holds whatever each comes to: the hero first, the biggest seen first.\n const order = slots.map((slot, index) => ({ slot, index })).sort((a, b) => Number(b.slot.role === 'hero') - Number(a.slot.role === 'hero') || a.index - b.index)\n for (const { slot, index } of order) {\n if (left <= 0) break\n if (answers[index]?.src || !allowed[index]) continue\n const made = await make(slot, tally)\n if (made) {\n out[index] = made\n left -= 1\n }\n }\n return out\n }\n}\n\n/** The nearest shape the image models draw to a slot's frame. */\nexport function aiSiteImportPictureShape(aspect: number): AiImageAspectRatio {\n const shapes: ReadonlyArray<readonly [AiImageAspectRatio, number]> = [['16:9', 16 / 9], ['4:3', 4 / 3], ['1:1', 1], ['3:4', 3 / 4], ['9:16', 9 / 16]]\n const wanted = aspect > 0 && Number.isFinite(aspect) ? aspect : 4 / 3\n return [...shapes].sort((a, b) => Math.abs(a[1] - wanted) - Math.abs(b[1] - wanted))[0]?.[0] ?? '4:3'\n}\n\n/** What a generated picture is made through, and whether the workspace's meter has room for it. */\nexport interface AiSiteImportPictureMakerInput {\n provider: AiImageProvider | null\n ingest: PluginMediaIngest | null\n firestore: FirebaseFirestore.Firestore\n orgId: string\n hostId: string\n uid: string\n /** What the site is, which a picture's own words are read with. */\n about: string\n /** Whether the workspace's meter has room for a picture now. */\n roomFor?: (credits: number) => boolean\n record?: typeof recordAssistCost\n}\n\n/**\n * A generated picture through the Media door's own parts (AGL-4152): the image\n * provider at a paid plan's size, the fixed style wording, the media library's\n * ingest as an upload this member made, the same provenance on the asset, and the\n * same meter, charged only once it is stored. `null` where it cannot run here.\n */\nexport function aiSiteImportPictureMaker(input: AiSiteImportPictureMakerInput): AiSiteImportPictureMaker | null {\n const { provider, ingest } = input\n if (!provider?.configured() || !ingest) return null\n const size = '1K' as const\n return async (slot, tally) => {\n const model = provider.defaultModel()\n if (input.roomFor && !input.roomFor(aiMediaCreditsPerPicture('photo', model, size))) return null\n const words = `${slot.alt}. For a website about: ${input.about}`.replace(/\\s+/g, ' ').trim()\n const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), AI_SITE_IMPORT_GENERATED_PICTURE_MS))\n try {\n const result = await Promise.race([\n provider.generate({ model, prompt: aiMediaRasterPrompt(words, 'natural'), aspectRatio: aiSiteImportPictureShape(slot.aspect), size, count: 1 }),\n timeout,\n ])\n const image = result?.images[0]\n if (!result || !image) return null\n const alt = aiImageAltText(slot.alt)\n const stored = await ingest.ingest({\n hostId: input.hostId,\n uid: input.uid,\n fileName: aiImageFileName(slot.alt, 0, image.mimeType),\n contentType: image.mimeType,\n bytes: Buffer.from(image.base64, 'base64'),\n alt,\n description: 'Created with AI from a description.',\n })\n if (!stored.ok) return null\n const usage = { ...result.usage, images: 1, imageSize: size }\n let signalId: string | null = null\n try {\n signalId = await (input.record ?? recordAssistCost)(input.firestore, input.orgId, {\n route: 'ai/jobs',\n hostId: input.hostId,\n model,\n tier: 'entitled',\n usage,\n docsPaths: [],\n stopReason: 'end_turn',\n free: null,\n uid: input.uid,\n kind: 'image',\n })\n } catch (error) {\n console.error('ai site import: a generated picture’s usage was not recorded', { orgId: input.orgId, error })\n }\n await input.firestore\n .collection('hosts')\n .doc(input.hostId)\n .collection('media')\n .doc(stored.mediaId)\n .update({ aiGenerated: { model, prompt: slot.alt, mode: 'photo', style: 'natural', aspectRatio: aiSiteImportPictureShape(slot.aspect), signalId, generatedBy: input.uid, createdAt: new Date() } })\n .catch((error: unknown) => console.error('ai site import: a generated picture’s record was not written', { mediaId: stored.mediaId, error }))\n tally.generated += 1\n tally.generatedUsd += estimateAiBilledUsd(usage, model)\n return { src: stored.src, width: stored.width ?? 1024, height: stored.height ?? 1024, alt }\n } catch (error) {\n if (!(error instanceof AiImageSafetyRefusal)) console.warn('ai site import: a generated picture failed; its slot is dropped', { error })\n return null\n }\n }\n}\n\n/** A page's pictures, as its row reads them once its slots are filled. */\nexport function aiSiteImportPagePicturesOf(pictures: AiSiteImportPagePictures, tally: AiSiteImportPictureTally): AiSiteImportPagePictures {\n const taken = new Set(tally.placed)\n return { source: pictures.source + tally.source, stock: tally.stock, generated: tally.generated, slots: 0, unplaced: pictures.unplaced.filter((url) => !taken.has(url)) }\n}\n"],"names":["aiLayoutPictureBandCells","AI_SITE_IMPORT_GENERATED_PICTURES_PER_PAGE","aiMediaCreditsPerPicture","aiSiteImportIsBrandMark","estimateAiBilledUsd","AiImageSafetyRefusal","aiImageAltText","aiImageFileName","aiMediaRasterPrompt","recordAssistCost","aiAssignOwnerPhotos","AI_SITE_IMPORT_GENERATED_PICTURE_MS","aiSiteImportPictureTally","source","stock","generated","generatedUsd","placed","SHOWS_PEOPLE","aiSiteImportGeneratedSlots","nodes","slots","cells","seen","Set","map","slot","index","lead","has","sectionIndex","add","product","people","record","test","alt","aiSiteImportPictureSource","input","next","make","tally","photos","filter","photo","width","height","length","froms","Map","src","from","cap","report","own","forEach","get","push","open","_slot","found","at","answers","allowed","left","Math","max","out","order","sort","a","b","Number","role","made","aiSiteImportPictureShape","aspect","shapes","wanted","isFinite","abs","aiSiteImportPictureMaker","provider","ingest","configured","size","model","defaultModel","roomFor","words","about","replace","trim","timeout","Promise","resolve","setTimeout","stored","result","race","generate","prompt","aspectRatio","count","image","images","hostId","uid","fileName","mimeType","contentType","bytes","Buffer","base64","description","ok","usage","imageSize","signalId","firestore","orgId","route","tier","docsPaths","stopReason","free","kind","error","console","collection","doc","mediaId","update","aiGenerated","mode","style","generatedBy","createdAt","Date","catch","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BAAiB;gBAAM7D;YAAI;QAC5F,EAAE,OAAO2F,OAAO;YACd,IAAI,CAAEA,CAAAA,iBAAiB1H,oBAAmB,GAAI2H,QAAQY,IAAI,CAAC,mEAAmE;gBAAEb;YAAM;YACtI,OAAO;QACT;IACF;AACF;AAEA,wEAAwE,GACxE,OAAO,SAASc,2BAA2BC,QAAkC,EAAErG,KAA+B;IAC5G,MAAMsG,QAAQ,IAAIvH,IAAIiB,MAAMxB,MAAM;IAClC,OAAO;QAAEJ,QAAQiI,SAASjI,MAAM,GAAG4B,MAAM5B,MAAM;QAAEC,OAAO2B,MAAM3B,KAAK;QAAEC,WAAW0B,MAAM1B,SAAS;QAAEM,OAAO;QAAG2H,UAAUF,SAASE,QAAQ,CAACrG,MAAM,CAAC,CAACsG,MAAQ,CAACF,MAAMlH,GAAG,CAACoH;IAAM;AAC1K"}
@@ -14,7 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
- import { type AiSiteImportPage, type AiSiteImportPlan, type AiSiteImportState } from '../model/ai-site-import';
17
+ import { type AiSiteImportPage, type AiSiteImportPageRole, type AiSiteImportPlan, type AiSiteImportState } from '../model/ai-site-import';
18
18
  import type { AiSystemBlock, AiTool } from '../providers/contract';
19
19
  import type { AiGenerationCheck, AiValidatedGeneration } from '../runtime/ai-doctrine';
20
20
  import type { AiDoctrineViolation } from '../runtime/ai-doctrine-validators';
@@ -42,6 +42,57 @@ export declare function aiSiteImportPlanPrompt(input: {
42
42
  required: readonly string[];
43
43
  roomForPage: boolean;
44
44
  }): string;
45
+ type AiSiteImportPlanGroup = {
46
+ label: string;
47
+ pages: string[];
48
+ };
49
+ /**
50
+ * An entry as a page's id (AGL-4152): an id, or `new`, as written; else the
51
+ * one page whose address or exact title it is. One that names no page, or
52
+ * several, stays as written for the check to name.
53
+ */
54
+ export declare function aiSiteImportPlanPageIdOf(pages: readonly AiSiteImportPage[]): (entry: string) => string;
55
+ /** What a plan's menu and footer are mended against. */
56
+ export interface AiSiteImportPlanMendScope {
57
+ pages: readonly AiSiteImportPage[];
58
+ /** The pages the old menu reached, which must stay reachable. */
59
+ required: readonly string[];
60
+ /** Whether the answer proposes a new page. */
61
+ proposes: boolean;
62
+ home: AiSiteImportState['home'];
63
+ siteName: string;
64
+ }
65
+ /**
66
+ * A plan's menu and footer mended where the mend is mechanical and cannot
67
+ * change what the answer meant (AGL-4152), before it is held, so an answer
68
+ * that needs only these costs no re-ask:
69
+ *
70
+ * - an entry written as a page's address or exact title reads as its id;
71
+ * - a page named twice in one entry is named once;
72
+ * - the home page leaves the menu (the logo goes home), and the new page
73
+ * leaves every entry where none is proposed;
74
+ * - an entry that then links no page is dropped;
75
+ * - a page of the old menu, or the new page, that the answer left
76
+ * unreachable joins the footer (`placeInFooter`).
77
+ *
78
+ * Nothing is mended in what the answer says: a label, a line, a button, or a
79
+ * page that is none of the site's stands as written, for the check to name.
80
+ */
81
+ export declare function aiSiteImportPlanMended(nav: {
82
+ groups: readonly AiSiteImportPlanGroup[];
83
+ footer: readonly AiSiteImportPlanGroup[];
84
+ }, input: AiSiteImportPlanMendScope): {
85
+ groups: AiSiteImportPlanGroup[];
86
+ footer: AiSiteImportPlanGroup[];
87
+ };
88
+ /**
89
+ * Why a plan did not pass, line by line (AGL-4152): each miss's code and the
90
+ * line it names, as a redesign's (`aiSiteImportRedesignWhy`), for the job's
91
+ * record (`planMissedWhy`). The log names its codes alone.
92
+ */
93
+ export declare function aiSiteImportPlanWhy(violations: readonly AiDoctrineViolation[]): string[];
94
+ /** What the job's record says of a plan the model declined: there are no lines to name. */
95
+ export declare const AI_SITE_IMPORT_PLAN_REFUSED_WHY = "refused: the model declined to plan the site.";
45
96
  /** What a plan is held to. */
46
97
  export interface AiSiteImportPlanScope {
47
98
  state: Pick<AiSiteImportState, 'pages' | 'home' | 'siteName'>;
@@ -62,6 +113,20 @@ export declare function aiSiteImportPlanRead(raw: unknown, input: AiSiteImportPl
62
113
  plan: AiSiteImportPlan | null;
63
114
  violations: AiDoctrineViolation[];
64
115
  };
116
+ /** Whether a button's words ask to be contacted. */
117
+ export declare function aiSiteImportAsksContact(label: string): boolean;
118
+ /**
119
+ * Where the header's button goes (AGL-4152): where the answer sends it, except
120
+ * that a button whose words ask to be contacted, sent to a page whose role is
121
+ * not `contact` while a page of that role exists, goes to that page. A
122
+ * "Contact us" to the About page took the visitor somewhere else than its
123
+ * words said, and the menu, leaving a lone entry to the button's page, then
124
+ * lost About altogether. The phone and the form are contact already.
125
+ */
126
+ export declare function aiSiteImportCtaTarget(cta: {
127
+ label: string;
128
+ target: string;
129
+ }, roles: Readonly<Record<string, AiSiteImportPageRole>>): string;
65
130
  /** A plan's check, answer by answer, for the one re-ask. */
66
131
  export declare function aiSiteImportPlanCheck(input: AiSiteImportPlanScope): AiGenerationCheck<AiSiteImportPlan>;
67
132
  /** The most tokens a plan's answer asks, with its thinking. */
@@ -76,3 +141,4 @@ export declare function aiRunSiteImportPlan(input: AiSiteImportPlanScope & {
76
141
  model: string;
77
142
  signal?: AbortSignal;
78
143
  }): Promise<AiValidatedGeneration<AiSiteImportPlan>>;
144
+ export {};
@@ -44,6 +44,7 @@ import { runValidatedGeneration } from "../runtime/ai-doctrine.js";
44
44
  import { aiGenerationMaxTokensWithin, aiJobStepBudget } from "./ai-job-budget.js";
45
45
  import { AI_LAYOUT_LANGUAGE_THINKING } from "./ai-job-page-language.js";
46
46
  import { AI_SITE_IMPORT_DROPPED_ITEM_CODE, AI_SITE_IMPORT_INVENTED_FACT_CODE, aiSiteImportHonestyFacts, aiSiteImportInventedIn } from "./ai-site-import-honesty.js";
47
+ import { aiSiteImportRedesignWhy } from "./ai-site-import-improve.js";
47
48
  const clean = (text)=>typeof text === 'string' ? text.replace(/\s+/g, ' ').trim() : '';
48
49
  /** The answer's kind of generation: the name its re-ask and its doctrine scope go by. */ export const AI_SITE_IMPORT_PLAN_KIND = 'site-import-plan';
49
50
  /** The heroes a plan may choose: those a page brought in can draw from one picture. */ export const AI_SITE_IMPORT_PLAN_HEROES = [
@@ -353,6 +354,137 @@ const record = (value)=>value && typeof value === 'object' ? value : {};
353
354
  };
354
355
  });
355
356
  }
357
+ const trimSlashes = (path)=>path.replace(/^\/+|\/+$/g, '');
358
+ /**
359
+ * An entry as a page's id (AGL-4152): an id, or `new`, as written; else the
360
+ * one page whose address or exact title it is. One that names no page, or
361
+ * several, stays as written for the check to name.
362
+ */ export function aiSiteImportPlanPageIdOf(pages) {
363
+ return (entry)=>{
364
+ if (entry === AI_SITE_IMPORT_PROPOSED_PAGE || pages.some((page)=>page.draftId === entry)) return entry;
365
+ const address = trimSlashes(entry).toLowerCase();
366
+ const title = entry.toLowerCase();
367
+ const hits = pages.filter((page)=>trimSlashes(page.slug).toLowerCase() === address || trimSlashes(page.path).toLowerCase() === address || clean(page.title).toLowerCase() === title);
368
+ return hits.length === 1 && hits[0] ? hits[0].draftId : entry;
369
+ };
370
+ }
371
+ /** Whether a link of the old menu goes to this page: its host (www or not) and its path. */ function linksTo(href, page) {
372
+ if (!href) return false;
373
+ try {
374
+ const own = new URL(page.url);
375
+ const url = new URL(href, own);
376
+ const host = (value)=>value.toLowerCase().replace(/^www\./, '');
377
+ return host(url.host) === host(own.host) && trimSlashes(decodeURIComponent(url.pathname)) === trimSlashes(page.path);
378
+ } catch (unused) {
379
+ return false;
380
+ }
381
+ }
382
+ /** The heading of the old menu's dropdown that held a page, in the site's own words, or `''`. */ function oldMenuHeadingOf(page, home) {
383
+ var _ref;
384
+ var _home_nav;
385
+ const group = ((_ref = home == null ? void 0 : (_home_nav = home.nav) == null ? void 0 : _home_nav.items) != null ? _ref : []).find((item)=>item.items.length > 0 && item.items.some((entry)=>linksTo(entry.href, page)));
386
+ return clean(group == null ? void 0 : group.label);
387
+ }
388
+ /** How alike two pages are, for the footer column a page joins: both policies, the same section of the site, the same group of the import. */ function likeness(page, other) {
389
+ if (!other) return 0;
390
+ const section = (entry)=>{
391
+ var _ref;
392
+ var _trimSlashes_split_;
393
+ return (_ref = (_trimSlashes_split_ = trimSlashes(entry.path).split('/')[0]) == null ? void 0 : _trimSlashes_split_.toLowerCase()) != null ? _ref : '';
394
+ };
395
+ return (aiSiteImportPageIsLegal(page) && aiSiteImportPageIsLegal(other) ? 2 : 0) + (section(page) && section(page) === section(other) ? 2 : 0) + (page.group !== 'main' && page.group === other.group ? 1 : 0);
396
+ }
397
+ /**
398
+ * A page the new menu left unreachable, put in the footer (AGL-4152): in the
399
+ * column whose pages are most like it, else a new column under the heading the
400
+ * old menu held it under, else the first column. A footer with no column takes
401
+ * one headed by the site's name. Every heading is the site's own words; none
402
+ * is made up, and one over the label's length is not taken.
403
+ */ function placeInFooter(footer, page, input) {
404
+ var _footer_best;
405
+ const of = (id)=>input.pages.find((entry)=>entry.draftId === id);
406
+ const self = of(page);
407
+ const heading = self ? oldMenuHeadingOf(self, input.home) : '';
408
+ let best = -1;
409
+ let bestScore = 0;
410
+ footer.forEach((column, index)=>{
411
+ const score = (heading && column.label.toLowerCase() === heading.toLowerCase() ? 3 : 0) + (self ? column.pages.reduce((sum, other)=>sum + likeness(self, of(other)), 0) : 0);
412
+ if (score > bestScore) {
413
+ best = index;
414
+ bestScore = score;
415
+ }
416
+ });
417
+ const fits = (label)=>!!label && label.length <= AI_SITE_IMPORT_PLAN_LABEL_MAX_CHARS;
418
+ if (best >= 0) (_footer_best = footer[best]) == null ? void 0 : _footer_best.pages.push(page);
419
+ else if (fits(heading)) footer.push({
420
+ label: heading,
421
+ pages: [
422
+ page
423
+ ]
424
+ });
425
+ else if (footer[0]) footer[0].pages.push(page);
426
+ else {
427
+ var _input_home;
428
+ const name = clean((_input_home = input.home) == null ? void 0 : _input_home.siteName) || clean(input.siteName);
429
+ if (fits(name)) footer.push({
430
+ label: name,
431
+ pages: [
432
+ page
433
+ ]
434
+ });
435
+ }
436
+ }
437
+ /**
438
+ * A plan's menu and footer mended where the mend is mechanical and cannot
439
+ * change what the answer meant (AGL-4152), before it is held, so an answer
440
+ * that needs only these costs no re-ask:
441
+ *
442
+ * - an entry written as a page's address or exact title reads as its id;
443
+ * - a page named twice in one entry is named once;
444
+ * - the home page leaves the menu (the logo goes home), and the new page
445
+ * leaves every entry where none is proposed;
446
+ * - an entry that then links no page is dropped;
447
+ * - a page of the old menu, or the new page, that the answer left
448
+ * unreachable joins the footer (`placeInFooter`).
449
+ *
450
+ * Nothing is mended in what the answer says: a label, a line, a button, or a
451
+ * page that is none of the site's stands as written, for the check to name.
452
+ */ export function aiSiteImportPlanMended(nav, input) {
453
+ const ids = new Set(input.pages.map((page)=>page.draftId));
454
+ const homeIds = new Set(input.pages.filter((page)=>page.slug === '/').map((page)=>page.draftId));
455
+ const idOf = aiSiteImportPlanPageIdOf(input.pages);
456
+ const tidy = (list, menu)=>list.map((group)=>({
457
+ label: group.label,
458
+ pages: [
459
+ ...new Set(group.pages.map(idOf))
460
+ ].filter((page)=>(page !== AI_SITE_IMPORT_PROPOSED_PAGE || input.proposes) && !(menu && homeIds.has(page)))
461
+ })).filter((group)=>group.pages.length > 0);
462
+ const groups = tidy(nav.groups, true);
463
+ const footer = tidy(nav.footer, false);
464
+ const placed = new Set([
465
+ ...groups,
466
+ ...footer
467
+ ].flatMap((group)=>group.pages));
468
+ const missing = [
469
+ ...new Set(input.required.filter((page)=>ids.has(page) && !homeIds.has(page) && !placed.has(page))),
470
+ ...input.proposes && !placed.has(AI_SITE_IMPORT_PROPOSED_PAGE) ? [
471
+ AI_SITE_IMPORT_PROPOSED_PAGE
472
+ ] : []
473
+ ];
474
+ for (const page of missing)placeInFooter(footer, page, input);
475
+ return {
476
+ groups,
477
+ footer
478
+ };
479
+ }
480
+ /**
481
+ * Why a plan did not pass, line by line (AGL-4152): each miss's code and the
482
+ * line it names, as a redesign's (`aiSiteImportRedesignWhy`), for the job's
483
+ * record (`planMissedWhy`). The log names its codes alone.
484
+ */ export function aiSiteImportPlanWhy(violations) {
485
+ return aiSiteImportRedesignWhy(violations);
486
+ }
487
+ /** What the job's record says of a plan the model declined: there are no lines to name. */ export const AI_SITE_IMPORT_PLAN_REFUSED_WHY = 'refused: the model declined to plan the site.';
356
488
  /** Every line of a site's first wave a plan's words are held to, with the page's own titles. */ export function aiSiteImportPlanScopeLines(state, siteLines) {
357
489
  const read = state.pages.flatMap((page)=>{
358
490
  var _ref;
@@ -380,8 +512,6 @@ const record = (value)=>value && typeof value === 'object' ? value : {};
380
512
  const cta = record(nav['cta']);
381
513
  const design = record(answer['design']);
382
514
  const proposedRaw = record(answer['proposed']);
383
- const groups = groupsOf(nav['groups']);
384
- const footer = groupsOf(nav['footer']);
385
515
  const out = [];
386
516
  const pages = aiSiteImportPlanPages(input.state);
387
517
  const ids = new Set(pages.map((page)=>page.draftId));
@@ -390,6 +520,17 @@ const record = (value)=>value && typeof value === 'object' ? value : {};
390
520
  const slug = clean(proposedRaw['slug']);
391
521
  const purpose = clean(proposedRaw['purpose']);
392
522
  const proposes = !!(title || slug || purpose);
523
+ // Mended first, where the mend is mechanical: an answer that needs only that is no re-ask.
524
+ const { groups, footer } = aiSiteImportPlanMended({
525
+ groups: groupsOf(nav['groups']),
526
+ footer: groupsOf(nav['footer'])
527
+ }, {
528
+ pages,
529
+ required: input.required,
530
+ proposes,
531
+ home: input.state.home,
532
+ siteName: input.state.siteName
533
+ });
393
534
  if (proposes) {
394
535
  if (!input.roomForPage) out.push(unusable('proposed: there is no room for a new page on this plan. Write title, slug and purpose as "".'));
395
536
  if (!title || !purpose) out.push(unusable('proposed: a new page needs its title and its purpose, or all three written as "".'));
@@ -441,7 +582,9 @@ const record = (value)=>value && typeof value === 'object' ? value : {};
441
582
  if (proposes && !placed.has(AI_SITE_IMPORT_PROPOSED_PAGE)) out.push(dropped('The new page is linked from nowhere. Put new in the menu or the footer.'));
442
583
  // The header's one filled button goes somewhere real.
443
584
  const ctaLabel = clean(cta['label']);
444
- const target = clean(cta['target']);
585
+ const written = clean(cta['target']);
586
+ // A page written by its address or title is that page, as in the menu.
587
+ const target = written === 'form' || written === 'phone' || !written ? written : aiSiteImportPlanPageIdOf(pages)(written);
445
588
  let ctaPage;
446
589
  if (!ctaLabel || !target) out.push(unusable('nav.cta: the header needs its main button, with its words and where it goes.'));
447
590
  else {
@@ -533,6 +676,11 @@ const record = (value)=>value && typeof value === 'object' ? value : {};
533
676
  const role = AI_SITE_IMPORT_PAGE_ROLES.find((value)=>value === named['role']);
534
677
  if (role && (ids.has(page) || page === AI_SITE_IMPORT_PROPOSED_PAGE && proposes)) roles[page] = role;
535
678
  }
679
+ // A button that asks to be contacted goes to the page for that, whatever page the answer named (AGL-4152).
680
+ const ctaTarget = aiSiteImportCtaTarget({
681
+ label: ctaLabel,
682
+ target
683
+ }, roles);
536
684
  return {
537
685
  plan: _extends({
538
686
  site: {
@@ -545,7 +693,7 @@ const record = (value)=>value && typeof value === 'object' ? value : {};
545
693
  groups,
546
694
  primaryCta: _extends({
547
695
  label: ctaLabel,
548
- target
696
+ target: ctaTarget
549
697
  }, ctaPage ? {
550
698
  page: ctaPage
551
699
  } : {}),
@@ -569,6 +717,27 @@ const record = (value)=>value && typeof value === 'object' ? value : {};
569
717
  violations: []
570
718
  };
571
719
  }
720
+ /**
721
+ * Words on a button that ask a visitor to reach the business (AGL-4152):
722
+ * contact, get in touch, a quote or estimate, a booking or appointment, a
723
+ * call, a talk, a consultation, an enquiry, a message.
724
+ */ const CONTACT_WORDS = /\b(?:contact|get in touch|in touch|reach (?:us|out)|quotes?|estimates?|book(?:ing)?|schedule|appointments?|call|talk|consult(?:ation)?s?|enquir(?:e|y|ies)|inquir(?:e|y|ies)|message|write to us|email us)\b/i;
725
+ /** Whether a button's words ask to be contacted. */ export function aiSiteImportAsksContact(label) {
726
+ return CONTACT_WORDS.test(label);
727
+ }
728
+ /**
729
+ * Where the header's button goes (AGL-4152): where the answer sends it, except
730
+ * that a button whose words ask to be contacted, sent to a page whose role is
731
+ * not `contact` while a page of that role exists, goes to that page. A
732
+ * "Contact us" to the About page took the visitor somewhere else than its
733
+ * words said, and the menu, leaving a lone entry to the button's page, then
734
+ * lost About altogether. The phone and the form are contact already.
735
+ */ export function aiSiteImportCtaTarget(cta, roles) {
736
+ if (cta.target === 'phone' || cta.target === 'form' || !aiSiteImportAsksContact(cta.label)) return cta.target;
737
+ if (roles[cta.target] === 'contact') return cta.target;
738
+ const contact = Object.keys(roles).find((page)=>roles[page] === 'contact');
739
+ return contact != null ? contact : cta.target;
740
+ }
572
741
  /** A plan's check, answer by answer, for the one re-ask. */ export function aiSiteImportPlanCheck(input) {
573
742
  return (answer)=>{
574
743
  const { plan, violations } = aiSiteImportPlanRead(answer, input);