@aglyn/plugins-ai 1.15.2 → 1.17.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 (46) hide show
  1. package/package.json +17 -17
  2. package/src/lib/components/ai-site-import-plan.component.js +1 -1
  3. package/src/lib/components/ai-site-import-plan.component.js.map +1 -1
  4. package/src/lib/jobs/ai-job-import-step.js +6 -4
  5. package/src/lib/jobs/ai-job-import-step.js.map +1 -1
  6. package/src/lib/jobs/ai-job-page-language.d.ts +2 -0
  7. package/src/lib/jobs/ai-job-page-language.js +29 -14
  8. package/src/lib/jobs/ai-job-page-language.js.map +1 -1
  9. package/src/lib/jobs/ai-job-page-step.js +3 -1
  10. package/src/lib/jobs/ai-job-page-step.js.map +1 -1
  11. package/src/lib/jobs/ai-job-text-step.d.ts +1 -0
  12. package/src/lib/jobs/ai-job-text-step.js.map +1 -1
  13. package/src/lib/jobs/ai-site-import-compile.d.ts +9 -1
  14. package/src/lib/jobs/ai-site-import-compile.js +67 -1
  15. package/src/lib/jobs/ai-site-import-compile.js.map +1 -1
  16. package/src/lib/jobs/ai-site-import-honesty.d.ts +6 -2
  17. package/src/lib/jobs/ai-site-import-honesty.js +5 -5
  18. package/src/lib/jobs/ai-site-import-honesty.js.map +1 -1
  19. package/src/lib/jobs/ai-site-import-improve.d.ts +93 -4
  20. package/src/lib/jobs/ai-site-import-improve.js +465 -24
  21. package/src/lib/jobs/ai-site-import-improve.js.map +1 -1
  22. package/src/lib/jobs/ai-site-import-pictures.js +4 -2
  23. package/src/lib/jobs/ai-site-import-pictures.js.map +1 -1
  24. package/src/lib/jobs/ai-site-import-plan.d.ts +15 -1
  25. package/src/lib/jobs/ai-site-import-plan.js +27 -1
  26. package/src/lib/jobs/ai-site-import-plan.js.map +1 -1
  27. package/src/lib/layout-language/ai-layout-compiler.d.ts +6 -1
  28. package/src/lib/layout-language/ai-layout-compiler.js +20 -4
  29. package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
  30. package/src/lib/model/ai-site-import-fidelity.d.ts +18 -2
  31. package/src/lib/model/ai-site-import-fidelity.js +35 -11
  32. package/src/lib/model/ai-site-import-fidelity.js.map +1 -1
  33. package/src/lib/model/ai-site-import-ledger.js +10 -2
  34. package/src/lib/model/ai-site-import-ledger.js.map +1 -1
  35. package/src/lib/model/ai-site-import-marks.d.ts +30 -0
  36. package/src/lib/model/ai-site-import-marks.js +39 -0
  37. package/src/lib/model/ai-site-import-marks.js.map +1 -0
  38. package/src/lib/model/ai-site-import-view.js +6 -1
  39. package/src/lib/model/ai-site-import-view.js.map +1 -1
  40. package/src/lib/model/ai-site-import.d.ts +8 -1
  41. package/src/lib/model/ai-site-import.js +12 -4
  42. package/src/lib/model/ai-site-import.js.map +1 -1
  43. package/src/lib/runtime/ai-node-tree.js +8 -0
  44. package/src/lib/runtime/ai-node-tree.js.map +1 -1
  45. package/src/lib/runtime/ai-palette.generated.js +36 -5
  46. package/src/lib/runtime/ai-palette.generated.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,EA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BAAyBjD,KAAKkD,MAAM;oBAAG0C;oBAAUkB,aAAalG,MAAMqE,GAAG;oBAAE8B,WAAW,IAAIC;gBAAO;YAAE,GAChMC,KAAK,CAAC,CAACZ,QAAmBC,QAAQD,KAAK,CAAC,gEAAgE;oBAAEI,SAASlC,OAAOkC,OAAO;oBAAEJ;gBAAM;YAC5ItF,MAAM1B,SAAS,IAAI;YACnB0B,MAAMzB,YAAY,IAAIZ,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","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,uBAAuB,QAAQ,mCAA+B;AACvE,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,QAAQtB,yBAAyBoB,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;Q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OAAO;oBAAEJ;gBAAM;YAC5ItF,MAAM1B,SAAS,IAAI;YACnB0B,MAAMzB,YAAY,IAAIZ,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"}
@@ -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';
@@ -62,6 +62,20 @@ export declare function aiSiteImportPlanRead(raw: unknown, input: AiSiteImportPl
62
62
  plan: AiSiteImportPlan | null;
63
63
  violations: AiDoctrineViolation[];
64
64
  };
65
+ /** Whether a button's words ask to be contacted. */
66
+ export declare function aiSiteImportAsksContact(label: string): boolean;
67
+ /**
68
+ * Where the header's button goes (AGL-4152): where the answer sends it, except
69
+ * that a button whose words ask to be contacted, sent to a page whose role is
70
+ * not `contact` while a page of that role exists, goes to that page. A
71
+ * "Contact us" to the About page took the visitor somewhere else than its
72
+ * words said, and the menu, leaving a lone entry to the button's page, then
73
+ * lost About altogether. The phone and the form are contact already.
74
+ */
75
+ export declare function aiSiteImportCtaTarget(cta: {
76
+ label: string;
77
+ target: string;
78
+ }, roles: Readonly<Record<string, AiSiteImportPageRole>>): string;
65
79
  /** A plan's check, answer by answer, for the one re-ask. */
66
80
  export declare function aiSiteImportPlanCheck(input: AiSiteImportPlanScope): AiGenerationCheck<AiSiteImportPlan>;
67
81
  /** The most tokens a plan's answer asks, with its thinking. */
@@ -533,6 +533,11 @@ const record = (value)=>value && typeof value === 'object' ? value : {};
533
533
  const role = AI_SITE_IMPORT_PAGE_ROLES.find((value)=>value === named['role']);
534
534
  if (role && (ids.has(page) || page === AI_SITE_IMPORT_PROPOSED_PAGE && proposes)) roles[page] = role;
535
535
  }
536
+ // A button that asks to be contacted goes to the page for that, whatever page the answer named (AGL-4152).
537
+ const ctaTarget = aiSiteImportCtaTarget({
538
+ label: ctaLabel,
539
+ target
540
+ }, roles);
536
541
  return {
537
542
  plan: _extends({
538
543
  site: {
@@ -545,7 +550,7 @@ const record = (value)=>value && typeof value === 'object' ? value : {};
545
550
  groups,
546
551
  primaryCta: _extends({
547
552
  label: ctaLabel,
548
- target
553
+ target: ctaTarget
549
554
  }, ctaPage ? {
550
555
  page: ctaPage
551
556
  } : {}),
@@ -569,6 +574,27 @@ const record = (value)=>value && typeof value === 'object' ? value : {};
569
574
  violations: []
570
575
  };
571
576
  }
577
+ /**
578
+ * Words on a button that ask a visitor to reach the business (AGL-4152):
579
+ * contact, get in touch, a quote or estimate, a booking or appointment, a
580
+ * call, a talk, a consultation, an enquiry, a message.
581
+ */ 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;
582
+ /** Whether a button's words ask to be contacted. */ export function aiSiteImportAsksContact(label) {
583
+ return CONTACT_WORDS.test(label);
584
+ }
585
+ /**
586
+ * Where the header's button goes (AGL-4152): where the answer sends it, except
587
+ * that a button whose words ask to be contacted, sent to a page whose role is
588
+ * not `contact` while a page of that role exists, goes to that page. A
589
+ * "Contact us" to the About page took the visitor somewhere else than its
590
+ * words said, and the menu, leaving a lone entry to the button's page, then
591
+ * lost About altogether. The phone and the form are contact already.
592
+ */ export function aiSiteImportCtaTarget(cta, roles) {
593
+ if (cta.target === 'phone' || cta.target === 'form' || !aiSiteImportAsksContact(cta.label)) return cta.target;
594
+ if (roles[cta.target] === 'contact') return cta.target;
595
+ const contact = Object.keys(roles).find((page)=>roles[page] === 'contact');
596
+ return contact != null ? contact : cta.target;
597
+ }
572
598
  /** A plan's check, answer by answer, for the one re-ask. */ export function aiSiteImportPlanCheck(input) {
573
599
  return (answer)=>{
574
600
  const { plan, violations } = aiSiteImportPlanRead(answer, input);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-site-import-plan.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: THE SITE PLANNED ONCE (AGL-4152).\n *\n * A page redesigned on its own cannot reorganize a site. So before anything of\n * it is built, one `submit_site_plan` answer reads what the first wave read and\n * says what the site is, how its menu and footer are organized, where the\n * header's main button goes, how the whole site is drawn, and at most one new\n * page. Every wave's pages are then drawn to it, by code:\n *\n * - the header and footer from `plan.nav`, with no model\n * (`aiSiteImportFrameSource`);\n * - each page's hero, groups, rhythm and closing band from `plan.design`\n * (`aiLayoutDesignChoices`), so the site reads as one design.\n *\n * The answer is held here: every page it names is a real page or the one it\n * proposes, its main button goes somewhere real, nothing the old menu reached\n * is left unreachable, and its words go through the honesty validator. An answer\n * that misses twice, or is refused, is no plan: the import's own frame and\n * design inputs stand, and its page says so.\n *\n * Nothing here runs with the flag off, or for Keep my site.\n *=========================================*/\n\nimport { fenceUntrustedText, UNTRUSTED_TEXT_RULE } from '@aglyn/shared-util-tools/untrusted-text'\nimport { aiLayoutGuardContacts } from '../layout-language/ai-layout-copy'\nimport { AI_SITE_IMPORT_PAGE_ROLES, AI_SITE_IMPORT_PROPOSED_PAGE, aiSiteImportPageIsLegal, type AiSiteImportPage, type AiSiteImportPageRole, type AiSiteImportPlan, type AiSiteImportPlanDesign, type AiSiteImportState } from '../model/ai-site-import'\nimport { AI_SITE_KINDS } from '../model/ai-site-kinds'\nimport type { AiSystemBlock, AiTool } from '../providers/contract'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport type { AiGenerationCheck, AiValidatedGeneration } from '../runtime/ai-doctrine'\nimport { runValidatedGeneration } from '../runtime/ai-doctrine'\nimport type { AiDoctrineViolation } from '../runtime/ai-doctrine-validators'\nimport { aiGenerationMaxTokensWithin, aiJobStepBudget } from './ai-job-budget'\nimport { AI_LAYOUT_LANGUAGE_THINKING } from './ai-job-page-language'\nimport { AI_SITE_IMPORT_DROPPED_ITEM_CODE, AI_SITE_IMPORT_INVENTED_FACT_CODE, aiSiteImportHonestyFacts, aiSiteImportInventedIn } from './ai-site-import-honesty'\n\nconst clean = (text: unknown): string => (typeof text === 'string' ? text.replace(/\\s+/g, ' ').trim() : '')\n\n/** The answer's kind of generation: the name its re-ask and its doctrine scope go by. */\nexport const AI_SITE_IMPORT_PLAN_KIND = 'site-import-plan'\n\n/** The heroes a plan may choose: those a page brought in can draw from one picture. */\nexport const AI_SITE_IMPORT_PLAN_HEROES = ['cover', 'poster', 'split', 'bleed', 'editorial', 'column', 'panel'] as const satisfies ReadonlyArray<AiSiteImportPlanDesign['hero']>\n\n/** The most top-level entries a planned menu holds: more reads as no plan at all. */\nexport const AI_SITE_IMPORT_PLAN_MAX_GROUPS = 6\n\n/** The most characters a menu's label holds, a heading of the footer, or the main button's. */\nexport const AI_SITE_IMPORT_PLAN_LABEL_MAX_CHARS = 28\n\n/** The most characters a proposed page's title holds: its search listing's ceiling. */\nexport const AI_SITE_IMPORT_PLAN_TITLE_MAX_CHARS = 60\n\nconst GROUP_SCHEMA = {\n type: 'object',\n additionalProperties: false,\n required: ['label', 'pages'],\n properties: { label: { type: 'string' }, pages: { type: 'array', items: { type: 'string' } } },\n} as const\n\n/** The plan's tool: strict, every field always written. */\nexport const AI_SITE_IMPORT_PLAN_TOOL: AiTool = {\n name: 'submit_site_plan',\n description: 'Submit the plan of the new site: what it is, its menu and footer, how it is drawn, and at most one new page.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['site', 'nav', 'design', 'proposed', 'roles'],\n properties: {\n site: {\n type: 'object',\n additionalProperties: false,\n required: ['what', 'audience', 'kind', 'voice'],\n properties: {\n what: { type: 'string' },\n audience: { type: 'string' },\n kind: { type: 'string', enum: AI_SITE_KINDS.map((kind) => kind.id) },\n voice: { type: 'string' },\n },\n },\n nav: {\n type: 'object',\n additionalProperties: false,\n required: ['groups', 'cta', 'footer'],\n properties: {\n groups: { type: 'array', items: GROUP_SCHEMA },\n cta: {\n type: 'object',\n additionalProperties: false,\n required: ['label', 'target'],\n properties: { label: { type: 'string' }, target: { type: 'string' } },\n },\n footer: { type: 'array', items: GROUP_SCHEMA },\n },\n },\n design: {\n type: 'object',\n additionalProperties: false,\n required: ['hero', 'group', 'rhythm', 'cta'],\n properties: {\n hero: { type: 'string', enum: [...AI_SITE_IMPORT_PLAN_HEROES] },\n group: { type: 'string', enum: ['cards', 'ruled', 'icons'] },\n rhythm: { type: 'string', enum: ['alternate', 'plain'] },\n cta: { type: 'string', enum: ['band', 'photo'] },\n },\n },\n proposed: {\n type: 'object',\n additionalProperties: false,\n required: ['title', 'slug', 'purpose'],\n properties: { title: { type: 'string' }, slug: { type: 'string' }, purpose: { type: 'string' } },\n },\n roles: {\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n required: ['page', 'role'],\n properties: { page: { type: 'string' }, role: { type: 'string', enum: [...AI_SITE_IMPORT_PAGE_ROLES] } },\n },\n },\n },\n },\n}\n\n/** What a plan is told, cached: every site shares these bytes. */\nexport const AI_SITE_IMPORT_PLAN_TEXT = [\n \"You plan the new website of a small business from what its existing website says. You are its information architect and art director: a visitor should find what they came for in one or two clicks, and the whole site should read as one confident design. The site's old menu is often just its pages in the order they were made. Reorganize it around what a visitor of this kind of business looks for. Answer with submit_site_plan.\",\n '',\n 'site: what is one plain sentence saying what the business does; audience is one short phrase saying who it serves; kind is the kind of site this is; voice is a few plain words on how its writing sounds.',\n '',\n 'nav: the menu, the header\\'s main button and the footer.',\n `- groups are the menu, at most ${AI_SITE_IMPORT_PLAN_MAX_GROUPS} top-level entries, in the order a visitor needs them. An entry with one page is a link under that label; an entry with several is a menu of them under the label. Pages are named by id, as the page list gives them. Group like pages under a clear label rather than listing them all; never put the home page in the menu, since the logo goes home.`,\n '- Every page the page list marks \"in the menu\" must stay reachable: in the menu or the footer. A policy page belongs in the footer.',\n '- cta is the header\\'s one filled button: the one thing a visitor of this business most wants to do. label is its words; target is a page by id, form for the page holding the site\\'s form, or phone for the phone number the site gives. Only what the page list says exists.',\n '- The page the main button goes to is never also a menu entry of its own: the button is its link. Put it in the footer.',\n '- footer is its columns, each a short heading over the pages it links: two to four where there are pages enough, and one where the site has two or three pages, so the footer is never empty.',\n `- Every label is short, at most ${AI_SITE_IMPORT_PLAN_LABEL_MAX_CHARS} characters, plain and in sentence case, so a capital reads as a name.`,\n '',\n 'design: how every page of the site is drawn, chosen once for the whole site from what it is and what it shows. hero: cover, a full-bleed photo with the words over it; poster, the same, taller and centered; split, the words beside a tall photo; bleed, half the band a photo; editorial, display type with a wide photo boxed under it; column, the words centered in a narrow column with a photo boxed under them; panel, the words on a card over a photo. Where the site opens on a wide photo of its work, its place or its people, lay the words over it (cover, poster, panel) or beside it (split, bleed); keep editorial and column for a site with no such photo. Choose a photo-led hero only where the site has photos worth it. group: how a set of services or reasons is drawn: cards, ruled columns, or icons. rhythm: alternate grounds between sections, or plain, one ground with space between. cta: the closing call to action on a strong band, or over a photo.',\n '',\n `roles: what each page of the list is for in the new site, by id, one of ${AI_SITE_IMPORT_PAGE_ROLES.join(', ')}: home for the home page; service for a page about what the business offers; contact for a page whose purpose is reaching it or booking; other where none fits. Every page redesigns to its role, so name each one.`,\n '',\n 'proposed: at most one new page the site lacks and a visitor of this kind of business looks for, such as common questions or how it works, named new in the menu or footer wherever it belongs. Propose one only where the request says there is room, and only what you can write without inventing a fact. title is at most 60 characters; slug is its address in lowercase words and hyphens; purpose is one sentence on what it tells a visitor. No page to propose: write all three as \"\".',\n '',\n 'Never write a name, number, price, date, testimonial, client, award, credential, address or guarantee the site does not give.',\n].join('\\n')\n\n/** A plan's system blocks: the platform's text, cached across sites. The site's own words ride the user turn. */\nexport function aiSiteImportPlanInstructions(): readonly AiSystemBlock[] {\n return [{ text: UNTRUSTED_TEXT_RULE }, { text: AI_SITE_IMPORT_PLAN_TEXT, cacheBreakpoint: true }]\n}\n\n/*------------------------------------------\n * What the answer is told\n *-----------------------------------------*/\n\n/** The most characters of a site's own words the answer is told, about the site and about its pages. */\nconst SITE_MAX_CHARS = 6_000\nconst PAGES_MAX_CHARS = 12_000\n/** The headings a page's line names. */\nconst HEADINGS_PER_PAGE = 8\n\n/** What one page tells the plan: its id, title, address, words and headings, and what it holds. */\nfunction pageLine(page: AiSiteImportPage, required: ReadonlySet<string>): string {\n const blocks = page.read?.blocks ?? []\n const headings = blocks.flatMap((block) => (block.kind === 'heading' && block.text.trim() ? [clean(block.text)] : [])).slice(0, HEADINGS_PER_PAGE)\n const marks = [\n ...(required.has(page.draftId) ? ['in the menu'] : []),\n ...(page.read?.forms?.length ? ['holds a form'] : []),\n ...(aiSiteImportPageIsLegal(page) ? ['a policy'] : []),\n ...(page.group !== 'main' ? [`in ${page.group}`] : []),\n ]\n return `${page.draftId} | ${page.slug === '/' ? 'home' : `/${page.slug}`} | ${clean(page.title)} | ${(page.read?.words ?? page.words).toLocaleString('en-US')} words${marks.length ? ` | ${marks.join(', ')}` : ''}${headings.length ? ` | headings: ${headings.join('; ')}` : ''}`\n}\n\n/** The pages a plan may name: every page the import brings in and can link. */\nexport function aiSiteImportPlanPages(state: Pick<AiSiteImportState, 'pages'>): AiSiteImportPage[] {\n return state.pages.filter((page) => !page.refused)\n}\n\n/** A plan's user turn: what the site says of itself and its pages, fenced as the owner's data, and whether there is room for a new page. */\nexport function aiSiteImportPlanPrompt(input: { state: Pick<AiSiteImportState, 'pages' | 'home' | 'siteName' | 'domain'>; required: readonly string[]; roomForPage: boolean }): string {\n const { state } = input\n const home = state.home ?? null\n const required = new Set(input.required)\n const phones = home?.facts.phones ?? []\n const said = [\n `Name: ${clean(home?.siteName) || clean(state.siteName)}`,\n home?.title ? `Title: ${clean(home.title)}` : '',\n home?.description ? `Description: ${clean(home.description)}` : '',\n ...(home?.facts.lines ?? []),\n phones.length ? `Phone: ${phones[0]}` : '',\n ].filter(Boolean)\n return [\n fenceUntrustedText(`What ${state.domain} says of itself`, said.join('\\n'), { maxChars: SITE_MAX_CHARS }),\n 'The page list, one a line: id | address | title | words | what it holds | headings.',\n fenceUntrustedText('The pages', aiSiteImportPlanPages(state).map((page) => pageLine(page, required)).join('\\n'), { maxChars: PAGES_MAX_CHARS }),\n input.roomForPage ? 'There is room for one new page.' : 'There is no room for a new page: write proposed as \"\".',\n phones.length ? 'The site gives a phone number.' : 'The site gives no phone number: target may not be phone.',\n ].join('\\n')\n}\n\n/*------------------------------------------\n * The answer held\n *-----------------------------------------*/\n\nconst SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\n\nconst invented = (message: string): AiDoctrineViolation => ({ rule: 14, code: AI_SITE_IMPORT_INVENTED_FACT_CODE, message })\nconst dropped = (message: string): AiDoctrineViolation => ({ rule: null, code: AI_SITE_IMPORT_DROPPED_ITEM_CODE, message })\nconst unusable = (message: string): AiDoctrineViolation => ({ rule: null, code: 'site-plan-unusable', message })\n\nconst record = (value: unknown): Record<string, unknown> => (value && typeof value === 'object' ? (value as Record<string, unknown>) : {})\n\n/** A list of groups, as an answer gives them. */\nfunction groupsOf(value: unknown): Array<{ label: string; pages: string[] }> {\n return (Array.isArray(value) ? value : []).map((entry) => {\n const group = record(entry)\n return { label: clean(group['label']), pages: (Array.isArray(group['pages']) ? group['pages'] : []).map(clean).filter(Boolean) }\n })\n}\n\n/** What a plan is held to. */\nexport interface AiSiteImportPlanScope {\n state: Pick<AiSiteImportState, 'pages' | 'home' | 'siteName'>\n /** Every line the import read of the site: what its words may say. */\n scope: readonly string[]\n /** The pages the old menu reached, which must stay reachable. */\n required: readonly string[]\n roomForPage: boolean\n}\n\n/** Every line of a site's first wave a plan's words are held to, with the page's own titles. */\nexport function aiSiteImportPlanScopeLines(state: Pick<AiSiteImportState, 'pages'>, siteLines: readonly string[]): string[] {\n const read = state.pages.flatMap((page) => [page.title, ...(page.read?.blocks ?? []).flatMap((block) => (block.kind === 'image' ? [] : block.text.trim() ? [block.text] : []))])\n return [...siteLines, ...read].map(clean).filter(Boolean)\n}\n\n/**\n * A plan's answer read and held (AGL-4152): a plan to store, or what it broke,\n * each named for the one re-ask. Its words are the honesty validator's: no name\n * or fact the site does not give, in any label or line.\n */\nexport function aiSiteImportPlanRead(raw: unknown, input: AiSiteImportPlanScope): { plan: AiSiteImportPlan | null; violations: AiDoctrineViolation[] } {\n const answer = record(raw)\n const site = record(answer['site'])\n const nav = record(answer['nav'])\n const cta = record(nav['cta'])\n const design = record(answer['design'])\n const proposedRaw = record(answer['proposed'])\n const groups = groupsOf(nav['groups'])\n const footer = groupsOf(nav['footer'])\n const out: AiDoctrineViolation[] = []\n const pages = aiSiteImportPlanPages(input.state)\n const ids = new Set(pages.map((page) => page.draftId))\n const homeIds = new Set(pages.filter((page) => page.slug === '/').map((page) => page.draftId))\n\n const title = clean(proposedRaw['title'])\n const slug = clean(proposedRaw['slug'])\n const purpose = clean(proposedRaw['purpose'])\n const proposes = !!(title || slug || purpose)\n if (proposes) {\n if (!input.roomForPage) out.push(unusable('proposed: there is no room for a new page on this plan. Write title, slug and purpose as \"\".'))\n if (!title || !purpose) out.push(unusable('proposed: a new page needs its title and its purpose, or all three written as \"\".'))\n if (title.length > AI_SITE_IMPORT_PLAN_TITLE_MAX_CHARS) out.push(unusable(`proposed: its title is over ${AI_SITE_IMPORT_PLAN_TITLE_MAX_CHARS} characters.`))\n if (!SLUG.test(slug)) out.push(unusable('proposed: its slug is lowercase words and hyphens only.'))\n else if (pages.some((page) => page.slug === slug || page.path.replace(/^\\/+|\\/+$/g, '') === slug)) out.push(unusable(`proposed: /${slug} is already a page of this site. Choose another address, or propose no page.`))\n if (pages.some((page) => clean(page.title).toLowerCase() === title.toLowerCase())) out.push(unusable(`proposed: \"${title.slice(0, 60)}\" is already a page of this site.`))\n }\n\n const entry = (name: string, page: string) => {\n if (page === AI_SITE_IMPORT_PROPOSED_PAGE) {\n if (!proposes) out.push(unusable(`${name}: it names the new page, and proposed is empty.`))\n } else if (!ids.has(page)) out.push(unusable(`${name}: \"${page.slice(0, 40)}\" is not a page of this site. Name pages by the ids the page list gives.`))\n }\n if (!groups.length) out.push(unusable('nav.groups: a menu needs at least one entry.'))\n if (groups.length > AI_SITE_IMPORT_PLAN_MAX_GROUPS) out.push(unusable(`nav.groups: at most ${AI_SITE_IMPORT_PLAN_MAX_GROUPS} top-level entries.`))\n for (const [where, list] of [['nav.groups', groups], ['nav.footer', footer]] as const) {\n list.forEach((group, index) => {\n const name = `${where}[${index}]`\n if (!group.label) out.push(unusable(`${name}: it needs a label.`))\n if (group.label.length > AI_SITE_IMPORT_PLAN_LABEL_MAX_CHARS) out.push(unusable(`${name}: \"${group.label.slice(0, 40)}\" is over ${AI_SITE_IMPORT_PLAN_LABEL_MAX_CHARS} characters.`))\n if (!group.pages.length) out.push(unusable(`${name}: it links no page.`))\n for (const page of group.pages) entry(name, page)\n })\n }\n groups.forEach((group, index) => {\n if (group.pages.some((page) => homeIds.has(page))) out.push(unusable(`nav.groups[${index}]: the home page is not in the menu: the logo goes home.`))\n })\n const placed = new Set([...groups, ...footer].flatMap((group) => group.pages))\n for (const page of input.required) {\n if (!placed.has(page) && !homeIds.has(page)) {\n const named = pages.find((other) => other.draftId === page)?.title ?? page\n out.push(dropped(`\"${named.slice(0, 60)}\" is in the old menu and nowhere in the new one. Put it in the menu or the footer.`))\n }\n }\n 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.'))\n\n // The header's one filled button goes somewhere real.\n const ctaLabel = clean(cta['label'])\n const target = clean(cta['target'])\n let ctaPage: string | undefined\n if (!ctaLabel || !target) out.push(unusable('nav.cta: the header needs its main button, with its words and where it goes.'))\n else {\n if (ctaLabel.length > AI_SITE_IMPORT_PLAN_LABEL_MAX_CHARS) out.push(unusable(`nav.cta: \"${ctaLabel.slice(0, 40)}\" is over ${AI_SITE_IMPORT_PLAN_LABEL_MAX_CHARS} characters.`))\n if (target === 'form') {\n ctaPage = pages.find((page) => page.read?.forms?.some((form) => form.fields.length))?.draftId\n if (!ctaPage) out.push(unusable('nav.cta: no page of this site holds a form. Send the button to a page, or to phone.'))\n } else if (target === 'phone') {\n if (!input.state.home?.facts.phones.length) out.push(unusable('nav.cta: the site gives no phone number. Send the button to a page.'))\n } else if (target !== AI_SITE_IMPORT_PROPOSED_PAGE || !proposes) entry('nav.cta', target)\n }\n\n const kind = clean(site['kind'])\n if (!AI_SITE_KINDS.some((entry) => entry.id === kind)) out.push(unusable('site.kind: one of the kinds the tool lists.'))\n const what = clean(site['what'])\n const audience = clean(site['audience'])\n if (!what || !audience) out.push(unusable('site: what and audience are each a line, never empty.'))\n const hero = AI_SITE_IMPORT_PLAN_HEROES.find((value) => value === design['hero'])\n const group = (['cards', 'ruled', 'icons'] as const).find((value) => value === design['group'])\n const rhythm = (['alternate', 'plain'] as const).find((value) => value === design['rhythm'])\n const closing = (['band', 'photo'] as const).find((value) => value === design['cta'])\n if (!hero || !group || !rhythm || !closing) out.push(unusable('design: hero, group, rhythm and cta are each one of the values the tool lists.'))\n\n // Every word held to what the site says.\n const held = aiSiteImportHonestyFacts(input.scope)\n const contacts = input.scope.join(' \\n ')\n const lines = [\n ['site.what', what],\n ['site.audience', audience],\n ['site.voice', clean(site['voice'])],\n ['nav.cta', ctaLabel],\n ...groups.map((entry, index) => [`nav.groups[${index}]`, entry.label] as const),\n ...footer.map((entry, index) => [`nav.footer[${index}]`, entry.label] as const),\n ['proposed.title', title],\n ['proposed.purpose', purpose],\n ] as const\n for (const [where, text] of lines) {\n if (!text) continue\n const reason = aiSiteImportInventedIn(text, held)\n if (reason) out.push(invented(`${where}, \"${text.slice(0, 80)}\": ${reason}`))\n else if (aiLayoutGuardContacts(text, contacts) !== text) out.push(invented(`${where}, \"${text.slice(0, 80)}\": it gives a phone number or email the site does not.`))\n }\n if (out.length || !hero || !group || !rhythm || !closing) return { plan: null, violations: out }\n // What each page is for (AGL-4152): a role it does not know, or a page that is none of the site's, is left to the page.\n const roles: Record<string, AiSiteImportPageRole> = {}\n for (const entry of Array.isArray(answer['roles']) ? answer['roles'] : []) {\n const named = record(entry)\n const page = clean(named['page'])\n const role = AI_SITE_IMPORT_PAGE_ROLES.find((value) => value === named['role'])\n if (role && (ids.has(page) || (page === AI_SITE_IMPORT_PROPOSED_PAGE && proposes))) roles[page] = role\n }\n return {\n plan: {\n site: { what, audience, kind, voice: clean(site['voice']) },\n nav: { groups, primaryCta: { label: ctaLabel, target, ...(ctaPage ? { page: ctaPage } : {}) }, footer },\n design: { hero, group, rhythm, cta: closing },\n proposed: proposes ? { title, slug, purpose, on: true } : null,\n ...(Object.keys(roles).length ? { roles } : {}),\n },\n violations: [],\n }\n}\n\n/** A plan's check, answer by answer, for the one re-ask. */\nexport function aiSiteImportPlanCheck(input: AiSiteImportPlanScope): AiGenerationCheck<AiSiteImportPlan> {\n return (answer) => {\n const { plan, violations } = aiSiteImportPlanRead(answer, input)\n return plan ? { value: plan, violations: [] } : { value: null, violations }\n }\n}\n\n/*------------------------------------------\n * The answer asked\n *-----------------------------------------*/\n\n/** The most tokens a plan's answer asks, with its thinking. */\nexport const AI_SITE_IMPORT_PLAN_MOST_TOKENS = 4_000\n\n/** The least time a plan's pass needs: its answer and its one re-ask on the page step's tier. */\nexport const AI_SITE_IMPORT_PLAN_BUDGET = aiJobStepBudget({ tier: AI_STEP_TIERS['job.page'], maxTokens: AI_SITE_IMPORT_PLAN_MOST_TOKENS })\n\n/** The ceiling a plan is asked at on this model. */\nexport function aiSiteImportPlanMaxTokens(model: string): number {\n return aiGenerationMaxTokensWithin({ model, budgetMs: AI_SITE_IMPORT_PLAN_BUDGET.minimumMs, cap: AI_SITE_IMPORT_PLAN_MOST_TOKENS, lookups: 0 })\n}\n\n/** The one plan a generative Improve it asks for, on the page step's tier. */\nexport async function aiRunSiteImportPlan(input: AiSiteImportPlanScope & { state: Pick<AiSiteImportState, 'pages' | 'home' | 'siteName' | 'domain'>; model: string; signal?: AbortSignal }): Promise<AiValidatedGeneration<AiSiteImportPlan>> {\n return runValidatedGeneration<AiSiteImportPlan>(AI_SITE_IMPORT_PLAN_KIND, {\n step: 'job.page',\n model: input.model,\n instructions: aiSiteImportPlanInstructions(),\n messages: [{ role: 'user', content: aiSiteImportPlanPrompt({ state: input.state, required: input.required, roomForPage: input.roomForPage }) }],\n tool: AI_SITE_IMPORT_PLAN_TOOL,\n maxTokens: aiSiteImportPlanMaxTokens(input.model),\n cutOff: { noun: 'plan', smaller: 'Write shorter lines.' },\n ...AI_LAYOUT_LANGUAGE_THINKING,\n check: aiSiteImportPlanCheck(input),\n ...(input.signal ? { signal: input.signal } : {}),\n })\n}\n"],"names":["fenceUntrustedText","UNTRUSTED_TEXT_RULE","aiLayoutGuardContacts","AI_SITE_IMPORT_PAGE_ROLES","AI_SITE_IMPORT_PROPOSED_PAGE","aiSiteImportPageIsLegal","AI_SITE_KINDS","AI_STEP_TIERS","runValidatedGeneration","aiGenerationMaxTokensWithin","aiJobStepBudget","AI_LAYOUT_LANGUAGE_THINKING","AI_SITE_IMPORT_DROPPED_ITEM_CODE","AI_SITE_IMPORT_INVENTED_FACT_CODE","aiSiteImportHonestyFacts","aiSiteImportInventedIn","clean","text","replace","trim","AI_SITE_IMPORT_PLAN_KIND","AI_SITE_IMPORT_PLAN_HEROES","AI_SITE_IMPORT_PLAN_MAX_GROUPS","AI_SITE_IMPORT_PLAN_LABEL_MAX_CHARS","AI_SITE_IMPORT_PLAN_TITLE_MAX_CHARS","GROUP_SCHEMA","type","additionalProperties","required","properties","label","pages","items","AI_SITE_IMPORT_PLAN_TOOL","name","description","strict","inputSchema","site","what","audience","kind","enum","map","id","voice","nav","groups","cta","target","footer","design","hero","group","rhythm","proposed","title","slug","purpose","roles","page","role","AI_SITE_IMPORT_PLAN_TEXT","join","aiSiteImportPlanInstructions","cacheBreakpoint","SITE_MAX_CHARS","PAGES_MAX_CHARS","HEADINGS_PER_PAGE","pageLine","blocks","read","headings","flatMap","block","slice","marks","has","draftId","forms","length","words","toLocaleString","aiSiteImportPlanPages","state","filter","refused","aiSiteImportPlanPrompt","input","home","Set","phones","facts","said","siteName","lines","Boolean","domain","maxChars","roomForPage","SLUG","invented","message","rule","code","dropped","unusable","record","value","groupsOf","Array","isArray","entry","aiSiteImportPlanScopeLines","siteLines","aiSiteImportPlanRead","raw","answer","proposedRaw","out","ids","homeIds","proposes","push","test","some","path","toLowerCase","where","list","forEach","index","placed","named","find","other","ctaLabel","ctaPage","form","fields","closing","held","scope","contacts","reason","plan","violations","primaryCta","on","Object","keys","aiSiteImportPlanCheck","AI_SITE_IMPORT_PLAN_MOST_TOKENS","AI_SITE_IMPORT_PLAN_BUDGET","tier","maxTokens","aiSiteImportPlanMaxTokens","model","budgetMs","minimumMs","cap","lookups","aiRunSiteImportPlan","step","instructions","messages","content","tool","cutOff","noun","smaller","check","signal"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;2CAqB2C,GAE3C,SAASA,kBAAkB,EAAEC,mBAAmB,QAAQ,0CAAyC;AACjG,SAASC,qBAAqB,QAAQ,uCAAmC;AACzE,SAASC,yBAAyB,EAAEC,4BAA4B,EAAEC,uBAAuB,QAAsI,6BAAyB;AACxP,SAASC,aAAa,QAAQ,4BAAwB;AAEtD,SAASC,aAAa,QAAQ,0BAAsB;AAEpD,SAASC,sBAAsB,QAAQ,4BAAwB;AAE/D,SAASC,2BAA2B,EAAEC,eAAe,QAAQ,qBAAiB;AAC9E,SAASC,2BAA2B,QAAQ,4BAAwB;AACpE,SAASC,gCAAgC,EAAEC,iCAAiC,EAAEC,wBAAwB,EAAEC,sBAAsB,QAAQ,8BAA0B;AAEhK,MAAMC,QAAQ,CAACC,OAA2B,OAAOA,SAAS,WAAWA,KAAKC,OAAO,CAAC,QAAQ,KAAKC,IAAI,KAAK;AAExG,uFAAuF,GACvF,OAAO,MAAMC,2BAA2B,mBAAkB;AAE1D,qFAAqF,GACrF,OAAO,MAAMC,6BAA6B;IAAC;IAAS;IAAU;IAAS;IAAS;IAAa;IAAU;CAAQ,CAAiE;AAEhL,mFAAmF,GACnF,OAAO,MAAMC,iCAAiC,EAAC;AAE/C,6FAA6F,GAC7F,OAAO,MAAMC,sCAAsC,GAAE;AAEr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AC;YAAG;SAAE;QAC/IoE,MAAMtI;QACN0H,WAAWC,0BAA0BpE,MAAMqE,KAAK;QAChDW,QAAQ;YAAEC,MAAM;YAAQC,SAAS;QAAuB;OACrD/J;QACHgK,OAAOpB,sBAAsB/D;OACzBA,MAAMoF,MAAM,GAAG;QAAEA,QAAQpF,MAAMoF,MAAM;IAAC,IAAI,CAAC;AAEnD"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-site-import-plan.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: THE SITE PLANNED ONCE (AGL-4152).\n *\n * A page redesigned on its own cannot reorganize a site. So before anything of\n * it is built, one `submit_site_plan` answer reads what the first wave read and\n * says what the site is, how its menu and footer are organized, where the\n * header's main button goes, how the whole site is drawn, and at most one new\n * page. Every wave's pages are then drawn to it, by code:\n *\n * - the header and footer from `plan.nav`, with no model\n * (`aiSiteImportFrameSource`);\n * - each page's hero, groups, rhythm and closing band from `plan.design`\n * (`aiLayoutDesignChoices`), so the site reads as one design.\n *\n * The answer is held here: every page it names is a real page or the one it\n * proposes, its main button goes somewhere real, nothing the old menu reached\n * is left unreachable, and its words go through the honesty validator. An answer\n * that misses twice, or is refused, is no plan: the import's own frame and\n * design inputs stand, and its page says so.\n *\n * Nothing here runs with the flag off, or for Keep my site.\n *=========================================*/\n\nimport { fenceUntrustedText, UNTRUSTED_TEXT_RULE } from '@aglyn/shared-util-tools/untrusted-text'\nimport { aiLayoutGuardContacts } from '../layout-language/ai-layout-copy'\nimport { AI_SITE_IMPORT_PAGE_ROLES, AI_SITE_IMPORT_PROPOSED_PAGE, aiSiteImportPageIsLegal, type AiSiteImportPage, type AiSiteImportPageRole, type AiSiteImportPlan, type AiSiteImportPlanDesign, type AiSiteImportState } from '../model/ai-site-import'\nimport { AI_SITE_KINDS } from '../model/ai-site-kinds'\nimport type { AiSystemBlock, AiTool } from '../providers/contract'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport type { AiGenerationCheck, AiValidatedGeneration } from '../runtime/ai-doctrine'\nimport { runValidatedGeneration } from '../runtime/ai-doctrine'\nimport type { AiDoctrineViolation } from '../runtime/ai-doctrine-validators'\nimport { aiGenerationMaxTokensWithin, aiJobStepBudget } from './ai-job-budget'\nimport { AI_LAYOUT_LANGUAGE_THINKING } from './ai-job-page-language'\nimport { AI_SITE_IMPORT_DROPPED_ITEM_CODE, AI_SITE_IMPORT_INVENTED_FACT_CODE, aiSiteImportHonestyFacts, aiSiteImportInventedIn } from './ai-site-import-honesty'\n\nconst clean = (text: unknown): string => (typeof text === 'string' ? text.replace(/\\s+/g, ' ').trim() : '')\n\n/** The answer's kind of generation: the name its re-ask and its doctrine scope go by. */\nexport const AI_SITE_IMPORT_PLAN_KIND = 'site-import-plan'\n\n/** The heroes a plan may choose: those a page brought in can draw from one picture. */\nexport const AI_SITE_IMPORT_PLAN_HEROES = ['cover', 'poster', 'split', 'bleed', 'editorial', 'column', 'panel'] as const satisfies ReadonlyArray<AiSiteImportPlanDesign['hero']>\n\n/** The most top-level entries a planned menu holds: more reads as no plan at all. */\nexport const AI_SITE_IMPORT_PLAN_MAX_GROUPS = 6\n\n/** The most characters a menu's label holds, a heading of the footer, or the main button's. */\nexport const AI_SITE_IMPORT_PLAN_LABEL_MAX_CHARS = 28\n\n/** The most characters a proposed page's title holds: its search listing's ceiling. */\nexport const AI_SITE_IMPORT_PLAN_TITLE_MAX_CHARS = 60\n\nconst GROUP_SCHEMA = {\n type: 'object',\n additionalProperties: false,\n required: ['label', 'pages'],\n properties: { label: { type: 'string' }, pages: { type: 'array', items: { type: 'string' } } },\n} as const\n\n/** The plan's tool: strict, every field always written. */\nexport const AI_SITE_IMPORT_PLAN_TOOL: AiTool = {\n name: 'submit_site_plan',\n description: 'Submit the plan of the new site: what it is, its menu and footer, how it is drawn, and at most one new page.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['site', 'nav', 'design', 'proposed', 'roles'],\n properties: {\n site: {\n type: 'object',\n additionalProperties: false,\n required: ['what', 'audience', 'kind', 'voice'],\n properties: {\n what: { type: 'string' },\n audience: { type: 'string' },\n kind: { type: 'string', enum: AI_SITE_KINDS.map((kind) => kind.id) },\n voice: { type: 'string' },\n },\n },\n nav: {\n type: 'object',\n additionalProperties: false,\n required: ['groups', 'cta', 'footer'],\n properties: {\n groups: { type: 'array', items: GROUP_SCHEMA },\n cta: {\n type: 'object',\n additionalProperties: false,\n required: ['label', 'target'],\n properties: { label: { type: 'string' }, target: { type: 'string' } },\n },\n footer: { type: 'array', items: GROUP_SCHEMA },\n },\n },\n design: {\n type: 'object',\n additionalProperties: false,\n required: ['hero', 'group', 'rhythm', 'cta'],\n properties: {\n hero: { type: 'string', enum: [...AI_SITE_IMPORT_PLAN_HEROES] },\n group: { type: 'string', enum: ['cards', 'ruled', 'icons'] },\n rhythm: { type: 'string', enum: ['alternate', 'plain'] },\n cta: { type: 'string', enum: ['band', 'photo'] },\n },\n },\n proposed: {\n type: 'object',\n additionalProperties: false,\n required: ['title', 'slug', 'purpose'],\n properties: { title: { type: 'string' }, slug: { type: 'string' }, purpose: { type: 'string' } },\n },\n roles: {\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n required: ['page', 'role'],\n properties: { page: { type: 'string' }, role: { type: 'string', enum: [...AI_SITE_IMPORT_PAGE_ROLES] } },\n },\n },\n },\n },\n}\n\n/** What a plan is told, cached: every site shares these bytes. */\nexport const AI_SITE_IMPORT_PLAN_TEXT = [\n \"You plan the new website of a small business from what its existing website says. You are its information architect and art director: a visitor should find what they came for in one or two clicks, and the whole site should read as one confident design. The site's old menu is often just its pages in the order they were made. Reorganize it around what a visitor of this kind of business looks for. Answer with submit_site_plan.\",\n '',\n 'site: what is one plain sentence saying what the business does; audience is one short phrase saying who it serves; kind is the kind of site this is; voice is a few plain words on how its writing sounds.',\n '',\n 'nav: the menu, the header\\'s main button and the footer.',\n `- groups are the menu, at most ${AI_SITE_IMPORT_PLAN_MAX_GROUPS} top-level entries, in the order a visitor needs them. An entry with one page is a link under that label; an entry with several is a menu of them under the label. Pages are named by id, as the page list gives them. Group like pages under a clear label rather than listing them all; never put the home page in the menu, since the logo goes home.`,\n '- Every page the page list marks \"in the menu\" must stay reachable: in the menu or the footer. A policy page belongs in the footer.',\n '- cta is the header\\'s one filled button: the one thing a visitor of this business most wants to do. label is its words; target is a page by id, form for the page holding the site\\'s form, or phone for the phone number the site gives. Only what the page list says exists.',\n '- The page the main button goes to is never also a menu entry of its own: the button is its link. Put it in the footer.',\n '- footer is its columns, each a short heading over the pages it links: two to four where there are pages enough, and one where the site has two or three pages, so the footer is never empty.',\n `- Every label is short, at most ${AI_SITE_IMPORT_PLAN_LABEL_MAX_CHARS} characters, plain and in sentence case, so a capital reads as a name.`,\n '',\n 'design: how every page of the site is drawn, chosen once for the whole site from what it is and what it shows. hero: cover, a full-bleed photo with the words over it; poster, the same, taller and centered; split, the words beside a tall photo; bleed, half the band a photo; editorial, display type with a wide photo boxed under it; column, the words centered in a narrow column with a photo boxed under them; panel, the words on a card over a photo. Where the site opens on a wide photo of its work, its place or its people, lay the words over it (cover, poster, panel) or beside it (split, bleed); keep editorial and column for a site with no such photo. Choose a photo-led hero only where the site has photos worth it. group: how a set of services or reasons is drawn: cards, ruled columns, or icons. rhythm: alternate grounds between sections, or plain, one ground with space between. cta: the closing call to action on a strong band, or over a photo.',\n '',\n `roles: what each page of the list is for in the new site, by id, one of ${AI_SITE_IMPORT_PAGE_ROLES.join(', ')}: home for the home page; service for a page about what the business offers; contact for a page whose purpose is reaching it or booking; other where none fits. Every page redesigns to its role, so name each one.`,\n '',\n 'proposed: at most one new page the site lacks and a visitor of this kind of business looks for, such as common questions or how it works, named new in the menu or footer wherever it belongs. Propose one only where the request says there is room, and only what you can write without inventing a fact. title is at most 60 characters; slug is its address in lowercase words and hyphens; purpose is one sentence on what it tells a visitor. No page to propose: write all three as \"\".',\n '',\n 'Never write a name, number, price, date, testimonial, client, award, credential, address or guarantee the site does not give.',\n].join('\\n')\n\n/** A plan's system blocks: the platform's text, cached across sites. The site's own words ride the user turn. */\nexport function aiSiteImportPlanInstructions(): readonly AiSystemBlock[] {\n return [{ text: UNTRUSTED_TEXT_RULE }, { text: AI_SITE_IMPORT_PLAN_TEXT, cacheBreakpoint: true }]\n}\n\n/*------------------------------------------\n * What the answer is told\n *-----------------------------------------*/\n\n/** The most characters of a site's own words the answer is told, about the site and about its pages. */\nconst SITE_MAX_CHARS = 6_000\nconst PAGES_MAX_CHARS = 12_000\n/** The headings a page's line names. */\nconst HEADINGS_PER_PAGE = 8\n\n/** What one page tells the plan: its id, title, address, words and headings, and what it holds. */\nfunction pageLine(page: AiSiteImportPage, required: ReadonlySet<string>): string {\n const blocks = page.read?.blocks ?? []\n const headings = blocks.flatMap((block) => (block.kind === 'heading' && block.text.trim() ? [clean(block.text)] : [])).slice(0, HEADINGS_PER_PAGE)\n const marks = [\n ...(required.has(page.draftId) ? ['in the menu'] : []),\n ...(page.read?.forms?.length ? ['holds a form'] : []),\n ...(aiSiteImportPageIsLegal(page) ? ['a policy'] : []),\n ...(page.group !== 'main' ? [`in ${page.group}`] : []),\n ]\n return `${page.draftId} | ${page.slug === '/' ? 'home' : `/${page.slug}`} | ${clean(page.title)} | ${(page.read?.words ?? page.words).toLocaleString('en-US')} words${marks.length ? ` | ${marks.join(', ')}` : ''}${headings.length ? ` | headings: ${headings.join('; ')}` : ''}`\n}\n\n/** The pages a plan may name: every page the import brings in and can link. */\nexport function aiSiteImportPlanPages(state: Pick<AiSiteImportState, 'pages'>): AiSiteImportPage[] {\n return state.pages.filter((page) => !page.refused)\n}\n\n/** A plan's user turn: what the site says of itself and its pages, fenced as the owner's data, and whether there is room for a new page. */\nexport function aiSiteImportPlanPrompt(input: { state: Pick<AiSiteImportState, 'pages' | 'home' | 'siteName' | 'domain'>; required: readonly string[]; roomForPage: boolean }): string {\n const { state } = input\n const home = state.home ?? null\n const required = new Set(input.required)\n const phones = home?.facts.phones ?? []\n const said = [\n `Name: ${clean(home?.siteName) || clean(state.siteName)}`,\n home?.title ? `Title: ${clean(home.title)}` : '',\n home?.description ? `Description: ${clean(home.description)}` : '',\n ...(home?.facts.lines ?? []),\n phones.length ? `Phone: ${phones[0]}` : '',\n ].filter(Boolean)\n return [\n fenceUntrustedText(`What ${state.domain} says of itself`, said.join('\\n'), { maxChars: SITE_MAX_CHARS }),\n 'The page list, one a line: id | address | title | words | what it holds | headings.',\n fenceUntrustedText('The pages', aiSiteImportPlanPages(state).map((page) => pageLine(page, required)).join('\\n'), { maxChars: PAGES_MAX_CHARS }),\n input.roomForPage ? 'There is room for one new page.' : 'There is no room for a new page: write proposed as \"\".',\n phones.length ? 'The site gives a phone number.' : 'The site gives no phone number: target may not be phone.',\n ].join('\\n')\n}\n\n/*------------------------------------------\n * The answer held\n *-----------------------------------------*/\n\nconst SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\n\nconst invented = (message: string): AiDoctrineViolation => ({ rule: 14, code: AI_SITE_IMPORT_INVENTED_FACT_CODE, message })\nconst dropped = (message: string): AiDoctrineViolation => ({ rule: null, code: AI_SITE_IMPORT_DROPPED_ITEM_CODE, message })\nconst unusable = (message: string): AiDoctrineViolation => ({ rule: null, code: 'site-plan-unusable', message })\n\nconst record = (value: unknown): Record<string, unknown> => (value && typeof value === 'object' ? (value as Record<string, unknown>) : {})\n\n/** A list of groups, as an answer gives them. */\nfunction groupsOf(value: unknown): Array<{ label: string; pages: string[] }> {\n return (Array.isArray(value) ? value : []).map((entry) => {\n const group = record(entry)\n return { label: clean(group['label']), pages: (Array.isArray(group['pages']) ? group['pages'] : []).map(clean).filter(Boolean) }\n })\n}\n\n/** What a plan is held to. */\nexport interface AiSiteImportPlanScope {\n state: Pick<AiSiteImportState, 'pages' | 'home' | 'siteName'>\n /** Every line the import read of the site: what its words may say. */\n scope: readonly string[]\n /** The pages the old menu reached, which must stay reachable. */\n required: readonly string[]\n roomForPage: boolean\n}\n\n/** Every line of a site's first wave a plan's words are held to, with the page's own titles. */\nexport function aiSiteImportPlanScopeLines(state: Pick<AiSiteImportState, 'pages'>, siteLines: readonly string[]): string[] {\n const read = state.pages.flatMap((page) => [page.title, ...(page.read?.blocks ?? []).flatMap((block) => (block.kind === 'image' ? [] : block.text.trim() ? [block.text] : []))])\n return [...siteLines, ...read].map(clean).filter(Boolean)\n}\n\n/**\n * A plan's answer read and held (AGL-4152): a plan to store, or what it broke,\n * each named for the one re-ask. Its words are the honesty validator's: no name\n * or fact the site does not give, in any label or line.\n */\nexport function aiSiteImportPlanRead(raw: unknown, input: AiSiteImportPlanScope): { plan: AiSiteImportPlan | null; violations: AiDoctrineViolation[] } {\n const answer = record(raw)\n const site = record(answer['site'])\n const nav = record(answer['nav'])\n const cta = record(nav['cta'])\n const design = record(answer['design'])\n const proposedRaw = record(answer['proposed'])\n const groups = groupsOf(nav['groups'])\n const footer = groupsOf(nav['footer'])\n const out: AiDoctrineViolation[] = []\n const pages = aiSiteImportPlanPages(input.state)\n const ids = new Set(pages.map((page) => page.draftId))\n const homeIds = new Set(pages.filter((page) => page.slug === '/').map((page) => page.draftId))\n\n const title = clean(proposedRaw['title'])\n const slug = clean(proposedRaw['slug'])\n const purpose = clean(proposedRaw['purpose'])\n const proposes = !!(title || slug || purpose)\n if (proposes) {\n if (!input.roomForPage) out.push(unusable('proposed: there is no room for a new page on this plan. Write title, slug and purpose as \"\".'))\n if (!title || !purpose) out.push(unusable('proposed: a new page needs its title and its purpose, or all three written as \"\".'))\n if (title.length > AI_SITE_IMPORT_PLAN_TITLE_MAX_CHARS) out.push(unusable(`proposed: its title is over ${AI_SITE_IMPORT_PLAN_TITLE_MAX_CHARS} characters.`))\n if (!SLUG.test(slug)) out.push(unusable('proposed: its slug is lowercase words and hyphens only.'))\n else if (pages.some((page) => page.slug === slug || page.path.replace(/^\\/+|\\/+$/g, '') === slug)) out.push(unusable(`proposed: /${slug} is already a page of this site. Choose another address, or propose no page.`))\n if (pages.some((page) => clean(page.title).toLowerCase() === title.toLowerCase())) out.push(unusable(`proposed: \"${title.slice(0, 60)}\" is already a page of this site.`))\n }\n\n const entry = (name: string, page: string) => {\n if (page === AI_SITE_IMPORT_PROPOSED_PAGE) {\n if (!proposes) out.push(unusable(`${name}: it names the new page, and proposed is empty.`))\n } else if (!ids.has(page)) out.push(unusable(`${name}: \"${page.slice(0, 40)}\" is not a page of this site. Name pages by the ids the page list gives.`))\n }\n if (!groups.length) out.push(unusable('nav.groups: a menu needs at least one entry.'))\n if (groups.length > AI_SITE_IMPORT_PLAN_MAX_GROUPS) out.push(unusable(`nav.groups: at most ${AI_SITE_IMPORT_PLAN_MAX_GROUPS} top-level entries.`))\n for (const [where, list] of [['nav.groups', groups], ['nav.footer', footer]] as const) {\n list.forEach((group, index) => {\n const name = `${where}[${index}]`\n if (!group.label) out.push(unusable(`${name}: it needs a label.`))\n if (group.label.length > AI_SITE_IMPORT_PLAN_LABEL_MAX_CHARS) out.push(unusable(`${name}: \"${group.label.slice(0, 40)}\" is over ${AI_SITE_IMPORT_PLAN_LABEL_MAX_CHARS} characters.`))\n if (!group.pages.length) out.push(unusable(`${name}: it links no page.`))\n for (const page of group.pages) entry(name, page)\n })\n }\n groups.forEach((group, index) => {\n if (group.pages.some((page) => homeIds.has(page))) out.push(unusable(`nav.groups[${index}]: the home page is not in the menu: the logo goes home.`))\n })\n const placed = new Set([...groups, ...footer].flatMap((group) => group.pages))\n for (const page of input.required) {\n if (!placed.has(page) && !homeIds.has(page)) {\n const named = pages.find((other) => other.draftId === page)?.title ?? page\n out.push(dropped(`\"${named.slice(0, 60)}\" is in the old menu and nowhere in the new one. Put it in the menu or the footer.`))\n }\n }\n 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.'))\n\n // The header's one filled button goes somewhere real.\n const ctaLabel = clean(cta['label'])\n const target = clean(cta['target'])\n let ctaPage: string | undefined\n if (!ctaLabel || !target) out.push(unusable('nav.cta: the header needs its main button, with its words and where it goes.'))\n else {\n if (ctaLabel.length > AI_SITE_IMPORT_PLAN_LABEL_MAX_CHARS) out.push(unusable(`nav.cta: \"${ctaLabel.slice(0, 40)}\" is over ${AI_SITE_IMPORT_PLAN_LABEL_MAX_CHARS} characters.`))\n if (target === 'form') {\n ctaPage = pages.find((page) => page.read?.forms?.some((form) => form.fields.length))?.draftId\n if (!ctaPage) out.push(unusable('nav.cta: no page of this site holds a form. Send the button to a page, or to phone.'))\n } else if (target === 'phone') {\n if (!input.state.home?.facts.phones.length) out.push(unusable('nav.cta: the site gives no phone number. Send the button to a page.'))\n } else if (target !== AI_SITE_IMPORT_PROPOSED_PAGE || !proposes) entry('nav.cta', target)\n }\n\n const kind = clean(site['kind'])\n if (!AI_SITE_KINDS.some((entry) => entry.id === kind)) out.push(unusable('site.kind: one of the kinds the tool lists.'))\n const what = clean(site['what'])\n const audience = clean(site['audience'])\n if (!what || !audience) out.push(unusable('site: what and audience are each a line, never empty.'))\n const hero = AI_SITE_IMPORT_PLAN_HEROES.find((value) => value === design['hero'])\n const group = (['cards', 'ruled', 'icons'] as const).find((value) => value === design['group'])\n const rhythm = (['alternate', 'plain'] as const).find((value) => value === design['rhythm'])\n const closing = (['band', 'photo'] as const).find((value) => value === design['cta'])\n if (!hero || !group || !rhythm || !closing) out.push(unusable('design: hero, group, rhythm and cta are each one of the values the tool lists.'))\n\n // Every word held to what the site says.\n const held = aiSiteImportHonestyFacts(input.scope)\n const contacts = input.scope.join(' \\n ')\n const lines = [\n ['site.what', what],\n ['site.audience', audience],\n ['site.voice', clean(site['voice'])],\n ['nav.cta', ctaLabel],\n ...groups.map((entry, index) => [`nav.groups[${index}]`, entry.label] as const),\n ...footer.map((entry, index) => [`nav.footer[${index}]`, entry.label] as const),\n ['proposed.title', title],\n ['proposed.purpose', purpose],\n ] as const\n for (const [where, text] of lines) {\n if (!text) continue\n const reason = aiSiteImportInventedIn(text, held)\n if (reason) out.push(invented(`${where}, \"${text.slice(0, 80)}\": ${reason}`))\n else if (aiLayoutGuardContacts(text, contacts) !== text) out.push(invented(`${where}, \"${text.slice(0, 80)}\": it gives a phone number or email the site does not.`))\n }\n if (out.length || !hero || !group || !rhythm || !closing) return { plan: null, violations: out }\n // What each page is for (AGL-4152): a role it does not know, or a page that is none of the site's, is left to the page.\n const roles: Record<string, AiSiteImportPageRole> = {}\n for (const entry of Array.isArray(answer['roles']) ? answer['roles'] : []) {\n const named = record(entry)\n const page = clean(named['page'])\n const role = AI_SITE_IMPORT_PAGE_ROLES.find((value) => value === named['role'])\n if (role && (ids.has(page) || (page === AI_SITE_IMPORT_PROPOSED_PAGE && proposes))) roles[page] = role\n }\n // A button that asks to be contacted goes to the page for that, whatever page the answer named (AGL-4152).\n const ctaTarget = aiSiteImportCtaTarget({ label: ctaLabel, target }, roles)\n return {\n plan: {\n site: { what, audience, kind, voice: clean(site['voice']) },\n nav: { groups, primaryCta: { label: ctaLabel, target: ctaTarget, ...(ctaPage ? { page: ctaPage } : {}) }, footer },\n design: { hero, group, rhythm, cta: closing },\n proposed: proposes ? { title, slug, purpose, on: true } : null,\n ...(Object.keys(roles).length ? { roles } : {}),\n },\n violations: [],\n }\n}\n\n/**\n * Words on a button that ask a visitor to reach the business (AGL-4152):\n * contact, get in touch, a quote or estimate, a booking or appointment, a\n * call, a talk, a consultation, an enquiry, a message.\n */\nconst CONTACT_WORDS =\n /\\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\n\n/** Whether a button's words ask to be contacted. */\nexport function aiSiteImportAsksContact(label: string): boolean {\n return CONTACT_WORDS.test(label)\n}\n\n/**\n * Where the header's button goes (AGL-4152): where the answer sends it, except\n * that a button whose words ask to be contacted, sent to a page whose role is\n * not `contact` while a page of that role exists, goes to that page. A\n * \"Contact us\" to the About page took the visitor somewhere else than its\n * words said, and the menu, leaving a lone entry to the button's page, then\n * lost About altogether. The phone and the form are contact already.\n */\nexport function aiSiteImportCtaTarget(cta: { label: string; target: string }, roles: Readonly<Record<string, AiSiteImportPageRole>>): string {\n if (cta.target === 'phone' || cta.target === 'form' || !aiSiteImportAsksContact(cta.label)) return cta.target\n if (roles[cta.target] === 'contact') return cta.target\n const contact = Object.keys(roles).find((page) => roles[page] === 'contact')\n return contact ?? cta.target\n}\n\n/** A plan's check, answer by answer, for the one re-ask. */\nexport function aiSiteImportPlanCheck(input: AiSiteImportPlanScope): AiGenerationCheck<AiSiteImportPlan> {\n return (answer) => {\n const { plan, violations } = aiSiteImportPlanRead(answer, input)\n return plan ? { value: plan, violations: [] } : { value: null, violations }\n }\n}\n\n/*------------------------------------------\n * The answer asked\n *-----------------------------------------*/\n\n/** The most tokens a plan's answer asks, with its thinking. */\nexport const AI_SITE_IMPORT_PLAN_MOST_TOKENS = 4_000\n\n/** The least time a plan's pass needs: its answer and its one re-ask on the page step's tier. */\nexport const AI_SITE_IMPORT_PLAN_BUDGET = aiJobStepBudget({ tier: AI_STEP_TIERS['job.page'], maxTokens: AI_SITE_IMPORT_PLAN_MOST_TOKENS })\n\n/** The ceiling a plan is asked at on this model. */\nexport function aiSiteImportPlanMaxTokens(model: string): number {\n return aiGenerationMaxTokensWithin({ model, budgetMs: AI_SITE_IMPORT_PLAN_BUDGET.minimumMs, cap: AI_SITE_IMPORT_PLAN_MOST_TOKENS, lookups: 0 })\n}\n\n/** The one plan a generative Improve it asks for, on the page step's tier. */\nexport async function aiRunSiteImportPlan(input: AiSiteImportPlanScope & { state: Pick<AiSiteImportState, 'pages' | 'home' | 'siteName' | 'domain'>; model: string; signal?: AbortSignal }): Promise<AiValidatedGeneration<AiSiteImportPlan>> {\n return runValidatedGeneration<AiSiteImportPlan>(AI_SITE_IMPORT_PLAN_KIND, {\n step: 'job.page',\n model: input.model,\n instructions: aiSiteImportPlanInstructions(),\n messages: [{ role: 'user', content: aiSiteImportPlanPrompt({ state: input.state, required: input.required, roomForPage: input.roomForPage }) }],\n tool: AI_SITE_IMPORT_PLAN_TOOL,\n maxTokens: aiSiteImportPlanMaxTokens(input.model),\n cutOff: { noun: 'plan', smaller: 'Write shorter lines.' },\n ...AI_LAYOUT_LANGUAGE_THINKING,\n check: aiSiteImportPlanCheck(input),\n ...(input.signal ? { signal: input.signal } : {}),\n })\n}\n"],"names":["fenceUntrustedText","UNTRUSTED_TEXT_RULE","aiLayoutGuardContacts","AI_SITE_IMPORT_PAGE_ROLES","AI_SITE_IMPORT_PROPOSED_PAGE","aiSiteImportPageIsLegal","AI_SITE_KINDS","AI_STEP_TIERS","runValidatedGeneration","aiGenerationMaxTokensWithin","aiJobStepBudget","AI_LAYOUT_LANGUAGE_THINKING","AI_SITE_IMPORT_DROPPED_ITEM_CODE","AI_SITE_IMPORT_INVENTED_FACT_CODE","aiSiteImportHonestyFacts","aiSiteImportInventedIn","clean","text","replace","trim","AI_SITE_IMPORT_PLAN_KIND","AI_SITE_IMPORT_PLAN_HEROES","AI_SITE_IMPORT_PLAN_MAX_GROUPS","AI_SITE_IMPORT_PLAN_LABEL_MAX_CHARS","AI_SITE_IMPORT_PLAN_TITLE_MAX_CHARS","GROUP_SCHEMA","type","additionalProperties","required","properties","label","pages","items","AI_SITE_IMPORT_PLAN_TOOL","name","description","strict","inputSchema","site","what","audience","kind","enum","map","id","voice","nav","groups","cta","target","footer","design","hero","group","rhythm","proposed","title","slug","purpose","roles","page","role","AI_SITE_IMPORT_PLAN_TEXT","join","aiSiteImportPlanInstructions","cacheBreakpoint","SITE_MAX_CHARS","PAGES_MAX_CHARS","HEADINGS_PER_PAGE","pageLine","blocks","read","headings","flatMap","block","slice","marks","has","draftId","forms","length","words","toLocaleString","aiSiteImportPlanPages","state","filter","refused","aiSiteImportPlanPrompt","input","home","Set","phones","facts","said","siteName","lines","Boolean","domain","maxChars","roomForPage","SLUG","invented","message","rule","code","dropped","unusable","record","value","groupsOf","Array","isArray","entry","aiSiteImportPlanScopeLines","siteLines","aiSiteImportPlanRead","raw","answer","proposedRaw","out","ids","homeIds","proposes","push","test","some","path","toLowerCase","where","list","forEach","index","placed","named","find","other","ctaLabel","ctaPage","form","fields","closing","held","scope","contacts","reason","plan","violations","ctaTarget","aiSiteImportCtaTarget","primaryCta","on","Object","keys","CONTACT_WORDS","aiSiteImportAsksContact","contact","aiSiteImportPlanCheck","AI_SITE_IMPORT_PLAN_MOST_TOKENS","AI_SITE_IMPORT_PLAN_BUDGET","tier","maxTokens","aiSiteImportPlanMaxTokens","model","budgetMs","minimumMs","cap","lookups","aiRunSiteImportPlan","step","instructions","messages","content","tool","cutOff","noun","smaller","check","signal"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;2CAqB2C,GAE3C,SAASA,kBAAkB,EAAEC,mBAAmB,QAAQ,0CAAyC;AACjG,SAASC,qBAAqB,QAAQ,uCAAmC;AACzE,SAASC,yBAAyB,EAAEC,4BAA4B,EAAEC,uBAAuB,QAAsI,6BAAyB;AACxP,SAASC,aAAa,QAAQ,4BAAwB;AAEtD,SAASC,aAAa,QAAQ,0BAAsB;AAEpD,SAASC,sBAAsB,QAAQ,4BAAwB;AAE/D,SAASC,2BAA2B,EAAEC,eAAe,QAAQ,qBAAiB;AAC9E,SAASC,2BAA2B,QAAQ,4BAAwB;AACpE,SAASC,gCAAgC,EAAEC,iCAAiC,EAAEC,wBAAwB,EAAEC,sBAAsB,QAAQ,8BAA0B;AAEhK,MAAMC,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D"}
@@ -240,7 +240,12 @@ export declare function compileRow(scope: SectionScope, columns: Array<{
240
240
  column: AiLayoutBlock[];
241
241
  weight: number;
242
242
  }>,
243
- /** How the columns sit against each other: centered on a page, top-aligned in a footer (AGL-3735). */
243
+ /**
244
+ * How the columns sit against each other: top-aligned in a footer (AGL-3735);
245
+ * on a page, centered where words stand beside a picture, else top-aligned
246
+ * (AGL-4152): words centered beside a tall form or a long column sit under a
247
+ * gap as tall as the difference, which reads as a missing block.
248
+ */
244
249
  alignItems?: 'center' | 'flex-start'): string;
245
250
  export type Room = 'full' | 'half' | 'narrow';
246
251
  /** A column of blocks, top to bottom, with buttons side by side; `null` when nothing in it compiles. */
@@ -16,6 +16,7 @@ import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_wi
16
16
  * See the License for the specific language governing permissions and
17
17
  * limitations under the License.
18
18
  */ import { REUSABLE_INSTANCE_COMPONENT_ID } from "@aglyn/aglyn/app-utils/reusable-component-keys";
19
+ import { ELEMENT_COLOR_SCHEME_VISITOR } from "@aglyn/aglyn/app-utils/element-color-scheme";
19
20
  import { CANVAS_ROOT_ELEMENT_ID } from "@aglyn/aglyn/foundation/constants/canvas";
20
21
  import { AI_ICON_COMPONENT_ID, aiIconOfWord, AI_ICON_LIBRARY } from "../runtime/ai-icon-library.js";
21
22
  import { AI_INSTANCE_REF_PROP } from "../runtime/ai-node-tree.js";
@@ -783,7 +784,14 @@ function drawSection(page, raw, index, scope) {
783
784
  // ── A row of columns ──────────────────────────────────────────────────────
784
785
  // Spans out of twelve live with the tree, so a frame's repair reads them without the compiler (AGL-3735).
785
786
  export { aiLayoutSpans };
786
- export function compileRow(scope, columns, /** How the columns sit against each other: centered on a page, top-aligned in a footer (AGL-3735). */ alignItems = 'center') {
787
+ export function compileRow(scope, columns, /**
788
+ * How the columns sit against each other: top-aligned in a footer (AGL-3735);
789
+ * on a page, centered where words stand beside a picture, else top-aligned
790
+ * (AGL-4152): words centered beside a tall form or a long column sit under a
791
+ * gap as tall as the difference, which reads as a missing block.
792
+ */ alignItems) {
793
+ const pictured = columns.some((entry)=>entry.column.length > 0 && entry.column.every((block)=>block.kind === 'image' || block.kind === 'video'));
794
+ const aligned = alignItems != null ? alignItems : pictured ? 'center' : 'flex-start';
787
795
  const tree = scope.page.tree;
788
796
  const spans = aiLayoutSpans(columns.map((entry)=>entry.weight));
789
797
  const items = columns.map((entry, position)=>{
@@ -800,7 +808,7 @@ export function compileRow(scope, columns, /** How the columns sit against each
800
808
  container: true,
801
809
  spacing: columns.length >= 3 ? '4' : '6'
802
810
  }, {
803
- alignItems
811
+ alignItems: aligned
804
812
  }, items, 'row');
805
813
  }
806
814
  /** A column of blocks, top to bottom, with buttons side by side; `null` when nothing in it compiles. */ export function compileFlow(scope, blocks, room) {
@@ -1030,11 +1038,17 @@ function compileButton(scope, block) {
1030
1038
  variant: 'contained',
1031
1039
  color: onBrand ? 'secondary' : 'primary'
1032
1040
  };
1041
+ // A filled button is the site's one primary (AGL-4152). A dark band and a cover photo pin the dark scheme, whose
1042
+ // primary is the light page's lighter twin; the button goes back to the scheme the visitor picked, so it wears
1043
+ // the primary its header's button and every other filled button wear, light or dark, and paints no ground.
1044
+ const oneFill = look.variant === 'contained' && look.color === 'primary' && (scope.band === 'dark' || !!scope.overPhoto);
1033
1045
  const id = scope.page.tree.add('muiButton', _extends({
1034
1046
  children: label
1035
1047
  }, look, {
1036
1048
  size: scope.index === 0 || block.style === 'large' ? 'large' : 'medium'
1037
- }, destination ? destinationProps(destination) : {}), // Sized to its words, never stretched across the column a Stack would
1049
+ }, destination ? destinationProps(destination) : {}, oneFill ? {
1050
+ colorScheme: ELEMENT_COLOR_SCHEME_VISITOR
1051
+ } : {}), // Sized to its words, never stretched across the column a Stack would
1038
1052
  // stretch it over (AGL-3660), and aligned with its section.
1039
1053
  {
1040
1054
  alignSelf: scope.centered ? 'center' : 'flex-start'
@@ -1733,7 +1747,9 @@ function instances(scope, placed, items, perRow) {
1733
1747
  // carries a style: a page of many pictures repeats no inline style (rule 16).
1734
1748
  // A source's own picture keeps the fit the source gives it (AGL-4138); a film's poster is its Video
1735
1749
  // element, filling the frame as the picture would (AGL-4140).
1736
- const fit = scope.page.options.verbatim === true && picture.given ? (_picture_fit = picture.fit) == null ? void 0 : _picture_fit.objectFit : undefined;
1750
+ // Under words laid over it, a photo fills the band edge to edge whatever the source fits it as (AGL-4152): a photo
1751
+ // fitted whole leaves bars of the scrim at its sides, a boxed picture under a header drawn as if over a hero.
1752
+ const fit = scope.page.options.verbatim === true && picture.given && role !== 'coverPhoto' ? (_picture_fit = picture.fit) == null ? void 0 : _picture_fit.objectFit : undefined;
1737
1753
  const image = picture.video ? video(scope, picture.video, picture.src ? {
1738
1754
  src: picture.src,
1739
1755
  alt: picture.alt