@aglyn/plugins-ai 1.0.0-beta.246 → 1.0.0-beta.247

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 (127) hide show
  1. package/package.json +17 -17
  2. package/src/lib/activity/ai-activity-actions.js +5 -1
  3. package/src/lib/activity/ai-activity-actions.js.map +1 -1
  4. package/src/lib/components/ai-job-links.js +14 -0
  5. package/src/lib/components/ai-job-links.js.map +1 -1
  6. package/src/lib/components/ai-site-start-card.component.d.ts +1 -1
  7. package/src/lib/components/ai-site-start-card.component.js +92 -19
  8. package/src/lib/components/ai-site-start-card.component.js.map +1 -1
  9. package/src/lib/declarations.server.js +12 -0
  10. package/src/lib/declarations.server.js.map +1 -1
  11. package/src/lib/jobs/ai-build-capabilities.js +56 -2
  12. package/src/lib/jobs/ai-build-capabilities.js.map +1 -1
  13. package/src/lib/jobs/ai-job-build-step.d.ts +3 -8
  14. package/src/lib/jobs/ai-job-build-step.js +49 -12
  15. package/src/lib/jobs/ai-job-build-step.js.map +1 -1
  16. package/src/lib/jobs/ai-job-form-dataset.d.ts +8 -5
  17. package/src/lib/jobs/ai-job-form-dataset.js +28 -10
  18. package/src/lib/jobs/ai-job-form-dataset.js.map +1 -1
  19. package/src/lib/jobs/ai-job-form-step.d.ts +20 -4
  20. package/src/lib/jobs/ai-job-form-step.js +98 -28
  21. package/src/lib/jobs/ai-job-form-step.js.map +1 -1
  22. package/src/lib/jobs/ai-job-layout-language.d.ts +6 -2
  23. package/src/lib/jobs/ai-job-layout-language.js +16 -5
  24. package/src/lib/jobs/ai-job-layout-language.js.map +1 -1
  25. package/src/lib/jobs/ai-job-layout-step.js +4 -1
  26. package/src/lib/jobs/ai-job-layout-step.js.map +1 -1
  27. package/src/lib/jobs/ai-job-media-step.d.ts +239 -0
  28. package/src/lib/jobs/ai-job-media-step.js +610 -0
  29. package/src/lib/jobs/ai-job-media-step.js.map +1 -0
  30. package/src/lib/jobs/ai-job-page-language.d.ts +2 -0
  31. package/src/lib/jobs/ai-job-page-language.js +9 -0
  32. package/src/lib/jobs/ai-job-page-language.js.map +1 -1
  33. package/src/lib/jobs/ai-job-page-sections.js +4 -3
  34. package/src/lib/jobs/ai-job-page-sections.js.map +1 -1
  35. package/src/lib/jobs/ai-job-page-step.js +3 -2
  36. package/src/lib/jobs/ai-job-page-step.js.map +1 -1
  37. package/src/lib/jobs/ai-job-plan-step.d.ts +10 -1
  38. package/src/lib/jobs/ai-job-plan-step.js +73 -15
  39. package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
  40. package/src/lib/jobs/ai-job-settings-step.d.ts +0 -4
  41. package/src/lib/jobs/ai-job-settings-step.js +2 -7
  42. package/src/lib/jobs/ai-job-settings-step.js.map +1 -1
  43. package/src/lib/jobs/ai-job-site-content.d.ts +2 -2
  44. package/src/lib/jobs/ai-job-site-content.js +5 -3
  45. package/src/lib/jobs/ai-job-site-content.js.map +1 -1
  46. package/src/lib/jobs/ai-job-site-datasets.d.ts +1 -1
  47. package/src/lib/jobs/ai-job-site-datasets.js +3 -2
  48. package/src/lib/jobs/ai-job-site-datasets.js.map +1 -1
  49. package/src/lib/jobs/ai-job-site-events.d.ts +148 -0
  50. package/src/lib/jobs/ai-job-site-events.js +313 -0
  51. package/src/lib/jobs/ai-job-site-events.js.map +1 -0
  52. package/src/lib/jobs/ai-job-site-step.d.ts +9 -3
  53. package/src/lib/jobs/ai-job-site-step.js +63 -17
  54. package/src/lib/jobs/ai-job-site-step.js.map +1 -1
  55. package/src/lib/jobs/ai-job-tracking-step.d.ts +184 -0
  56. package/src/lib/jobs/ai-job-tracking-step.js +501 -0
  57. package/src/lib/jobs/ai-job-tracking-step.js.map +1 -0
  58. package/src/lib/jobs/ai-layout-stock-photos.d.ts +21 -0
  59. package/src/lib/jobs/ai-layout-stock-photos.js +41 -4
  60. package/src/lib/jobs/ai-layout-stock-photos.js.map +1 -1
  61. package/src/lib/jobs/ai-site-publish.js +2 -3
  62. package/src/lib/jobs/ai-site-publish.js.map +1 -1
  63. package/src/lib/jobs/ai-stock-photo-picker.d.ts +24 -0
  64. package/src/lib/jobs/ai-stock-photo-picker.js +108 -0
  65. package/src/lib/jobs/ai-stock-photo-picker.js.map +1 -0
  66. package/src/lib/jobs/fixtures/ai-jazz-events-build-plan-recording.d.ts +37 -0
  67. package/src/lib/jobs/fixtures/ai-jazz-events-build-plan-recording.js +47 -0
  68. package/src/lib/jobs/fixtures/ai-jazz-events-build-plan-recording.js.map +1 -0
  69. package/src/lib/jobs/fixtures/ai-stock-photo-agl3760-recordings.d.ts +21 -0
  70. package/src/lib/jobs/fixtures/ai-stock-photo-agl3760-recordings.js +128 -0
  71. package/src/lib/jobs/fixtures/ai-stock-photo-agl3760-recordings.js.map +1 -0
  72. package/src/lib/layout-language/ai-layout-compiler.d.ts +10 -4
  73. package/src/lib/layout-language/ai-layout-compiler.js +38 -19
  74. package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
  75. package/src/lib/layout-language/ai-layout-frame.d.ts +7 -5
  76. package/src/lib/layout-language/ai-layout-frame.js +12 -9
  77. package/src/lib/layout-language/ai-layout-frame.js.map +1 -1
  78. package/src/lib/layout-language/ai-layout-gaps.js +3 -1
  79. package/src/lib/layout-language/ai-layout-gaps.js.map +1 -1
  80. package/src/lib/layout-language/ai-layout-labels.d.ts +70 -0
  81. package/src/lib/layout-language/ai-layout-labels.js +162 -0
  82. package/src/lib/layout-language/ai-layout-labels.js.map +1 -0
  83. package/src/lib/layout-language/ai-layout-links.js +5 -2
  84. package/src/lib/layout-language/ai-layout-links.js.map +1 -1
  85. package/src/lib/layout-language/ai-layout-listings.d.ts +14 -1
  86. package/src/lib/layout-language/ai-layout-listings.js +32 -5
  87. package/src/lib/layout-language/ai-layout-listings.js.map +1 -1
  88. package/src/lib/model/ai-build-event-page.d.ts +70 -0
  89. package/src/lib/model/ai-build-event-page.js +145 -0
  90. package/src/lib/model/ai-build-event-page.js.map +1 -0
  91. package/src/lib/model/ai-build-job.d.ts +21 -0
  92. package/src/lib/model/ai-build-job.js +39 -0
  93. package/src/lib/model/ai-build-job.js.map +1 -1
  94. package/src/lib/model/ai-build-plan.d.ts +25 -14
  95. package/src/lib/model/ai-build-plan.js +33 -23
  96. package/src/lib/model/ai-build-plan.js.map +1 -1
  97. package/src/lib/model/ai-job-activity.js +3 -1
  98. package/src/lib/model/ai-job-activity.js.map +1 -1
  99. package/src/lib/model/ai-jobs.types.d.ts +10 -2
  100. package/src/lib/model/ai-jobs.types.js +3 -1
  101. package/src/lib/model/ai-jobs.types.js.map +1 -1
  102. package/src/lib/model/ai-plan-capabilities.d.ts +8 -0
  103. package/src/lib/model/ai-plan-capabilities.js.map +1 -1
  104. package/src/lib/model/ai-site-inventory.d.ts +2 -0
  105. package/src/lib/model/ai-site-inventory.js +5 -0
  106. package/src/lib/model/ai-site-inventory.js.map +1 -1
  107. package/src/lib/model/ai-site-job.d.ts +2 -2
  108. package/src/lib/model/ai-site-job.js +3 -3
  109. package/src/lib/model/ai-site-job.js.map +1 -1
  110. package/src/lib/runtime/ai-doctrine-validators.d.ts +25 -3
  111. package/src/lib/runtime/ai-doctrine-validators.js +53 -6
  112. package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
  113. package/src/lib/runtime/ai-doctrine.d.ts +6 -1
  114. package/src/lib/runtime/ai-doctrine.js +13 -9
  115. package/src/lib/runtime/ai-doctrine.js.map +1 -1
  116. package/src/lib/runtime/ai-eval-live.d.ts +1 -1
  117. package/src/lib/runtime/ai-eval-live.js +1 -1
  118. package/src/lib/runtime/ai-eval-live.js.map +1 -1
  119. package/src/lib/runtime/ai-palette.d.ts +3 -1
  120. package/src/lib/runtime/ai-palette.generated.js +498 -10
  121. package/src/lib/runtime/ai-palette.generated.js.map +1 -1
  122. package/src/lib/runtime/ai-palette.js +5 -3
  123. package/src/lib/runtime/ai-palette.js.map +1 -1
  124. package/src/lib/runtime/ai-template-examples.js +8 -2
  125. package/src/lib/runtime/ai-template-examples.js.map +1 -1
  126. package/src/lib/server.js +8 -0
  127. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-build-job.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n pluginAiCapabilityArgsProblems,\n type PluginAiCapability,\n} from '@aglyn/aglyn/plugin-manager/plugin-ai-capabilities'\nimport {\n AI_PLAN_NEW_REF_PREFIX,\n isAiPlanNewRef,\n type AiBuildItem,\n type AiBuildPlan,\n type AiBuildPlanCreate,\n type AiBuildPlanCreateKind,\n type AiBuildPlanScreen,\n} from './ai-build-plan'\nimport type { AiJobItemLedger, AiJobItemStatus } from './ai-jobs.types'\nimport {\n AI_BUILD_STORE_OP,\n AI_BUILD_STORE_PAGES_LABEL,\n AI_BUILD_STORE_SLOT,\n aiBuildMakesStore,\n aiBuildStorePagesAdded,\n} from './ai-build-store-pages'\nimport {\n AI_SITE_HOME_FIRST_LABEL,\n AI_SITE_MAX_SECTIONS,\n AI_SITE_PASS_CREDITS,\n aiCreationMeasuredCredits,\n aiJobPlanCreditEstimate,\n aiJobPlanCreditRange,\n aiSitePlanIsHome,\n aiStandaloneScreenCreditRange,\n} from './ai-site-job'\nimport {\n AI_CREDIT_RANGE_ZERO,\n AI_MEASURED_PASS_CREDITS,\n aiCreditRangeAdd,\n aiCreditRangeOf,\n aiCreditRangeOrdered,\n type AiCreditRange,\n type AiCreditsSmaller,\n} from './ai-credit-estimate'\n\n/**\n * What a `build` job is (AGL-3616): one request — \"a few pages, a contact\n * form and a way to book me\" — planned as creations, pages and items, built\n * one UNIT a pass in dependency order, and settled ITEM BY ITEM.\n *\n * A build is a generalized site scaffold. Every unit is handed to what\n * already builds that kind of thing — a page to the page step, a form to the\n * form step, another plugin's resource to that plugin's draft writer — so a\n * build cannot drift from what it builds. What is new is the settlement: one\n * failed unit does not end the job. It gives back its own spend, the units\n * that depended on it are built without it (or skipped, when they cannot\n * stand without it), and the job is `done` when anything was delivered.\n *\n * This module is the build's MODEL — its units, their order, how a failure\n * travels to what depends on it, what it is estimated to cost, and the\n * ledger arithmetic — and does no I/O, so the step, the machine, the doors\n * and the console read one vocabulary.\n */\n\n/** How much one build holds: what one proposal can describe and one person can read. */\nexport const AI_BUILD_LIMITS = {\n /** Creations, pages and items together. */\n units: 16,\n pages: 8,\n /** A Free workspace's pages. */\n freePages: 2,\n} as const\n\n/**\n * What a Free build's plan card says when it holds as many pages as a Free\n * build makes (AGL-3722): the plan is told the cap and plans the first pages\n * a request asks for, so a request for three — \"About us, Custom cakes and\n * Catering\", 2026-10-10 — came back as two with nothing saying why. `null`\n * when the plan holds fewer, or on a paid workspace.\n */\nexport function aiBuildFreePageCapNote(plan: Pick<AiBuildPlan, 'screens'>, freeTaste: boolean): string | null {\n const cap = AI_BUILD_LIMITS.freePages\n if (!freeTaste || plan.screens.length < cap) return null\n return `A Free workspace’s build makes up to ${cap} pages at a time. If you asked for more, ask Assist for the rest once this build is done.`\n}\n\n/** What a build creates through its `create` list; everything else beyond pages is an item. */\nexport const AI_BUILD_CREATE_KINDS: readonly AiBuildPlanCreateKind[] = ['layout', 'form', 'component', 'email']\n\n/**\n * The operations a build plans through `create` and `screens` rather than\n * `items`: an item naming one is a plan that put it in the wrong list.\n */\nexport const AI_BUILD_STRUCTURAL_OPS: readonly string[] = ['page', ...AI_BUILD_CREATE_KINDS]\n\n/**\n * What a build hands an item it made before it (AGL-3728): its pages, by the\n * title the plan gave each and the id it was written under, and its layouts,\n * by name. An item's `new:<title>` destinations are read against it.\n */\nexport const AI_BUILD_MADE_INPUT = 'buildMade'\n\nexport interface AiBuildMade {\n pages: Array<{ title: string; id: string }>\n layouts: Array<{ name: string; id: string }>\n}\n\n/** The job input a build's Assist proposal sets when the brief asked to publish. */\nexport const AI_BUILD_PUBLISH_INPUT = 'publish'\n\n/** A unit of a build: a creation, a page, or an item. */\nexport interface AiBuildUnit {\n slot: string\n /** The capability operation that builds it. */\n op: string\n label: string\n creation?: AiBuildPlanCreate\n screen?: AiBuildPlanScreen\n item?: AiBuildItem\n /** The slots it is built after, in plan order. */\n deps: string[]\n}\n\n/** The operation a creation is built as. */\nfunction creationOp(creation: AiBuildPlanCreate): string {\n return creation.kind\n}\n\n/** A plan's `new:<name>` names, each to the slot that builds it. */\nfunction namedSlots(plan: AiBuildPlan): Map<string, string> {\n const slots = new Map<string, string>()\n plan.create.forEach((creation, index) => {\n if (AI_BUILD_CREATE_KINDS.includes(creation.kind)) slots.set(creation.name.toLowerCase(), `c${index}`)\n })\n for (const item of plan.items ?? []) slots.set(item.name.toLowerCase(), item.slot)\n return slots\n}\n\n/** The name a `new:<name>` reference gives, lowercased. */\nexport function aiBuildRefName(ref: string): string {\n return ref.slice(AI_PLAN_NEW_REF_PREFIX.length).trim().toLowerCase()\n}\n\n/**\n * The `new:<name>` references an item's arguments make (AGL-3728): an\n * argument that is one, or the destination after `=>` in an entry such as a\n * menu item's `About => new:About`. Read from the arguments, never from the\n * model's `dependsOn`, so what an item links is always built before it.\n */\nexport function aiBuildItemArgRefs(args: Readonly<Record<string, unknown>> | null | undefined): string[] {\n const refs: string[] = []\n const take = (value: unknown) => {\n if (typeof value !== 'string') return\n for (const part of [value, value.split('=>').slice(-1)[0] ?? '']) {\n const ref = part.trim()\n if (isAiPlanNewRef(ref) && !refs.includes(ref)) refs.push(ref)\n }\n }\n for (const value of Object.values(args ?? {})) {\n if (Array.isArray(value)) value.forEach(take)\n else take(value)\n }\n return refs\n}\n\n/** Every reference a page makes: its layout, template, starting page and what its sections place. */\nexport function aiBuildScreenRefs(screen: AiBuildPlanScreen): string[] {\n return [\n screen.layout,\n screen.template,\n screen.duplicateOf,\n ...screen.sections.flatMap((section) => section.uses),\n ].filter((ref): ref is string => typeof ref === 'string' && ref.length > 0)\n}\n\n/**\n * The units a plan implies, in plan order: creations, then items, then\n * pages — the order a member reads them in, and the one a page that places\n * a creation or an item is built after anyway. `aiBuildOrder` sorts them on\n * their dependencies.\n */\nexport function aiBuildUnits(plan: AiBuildPlan): AiBuildUnit[] {\n const slots = namedSlots(plan)\n // A page, by the title the plan gave it: what an item's arguments may link\n // as `new:<title>` (a menu item, AGL-3728), built before the item.\n const pageSlots = new Map<string, string>()\n plan.screens.forEach((screen, index) => {\n const title = screen.title.trim().toLowerCase()\n if (title && !pageSlots.has(title)) pageSlots.set(title, `p${index}`)\n })\n const depsOf = (refs: readonly (string | null)[], self: string, pages = false): string[] => {\n const deps: string[] = []\n for (const ref of refs) {\n if (!isAiPlanNewRef(ref)) continue\n const slot = slots.get(aiBuildRefName(ref)) ?? (pages ? pageSlots.get(aiBuildRefName(ref)) : undefined)\n if (slot && slot !== self && !deps.includes(slot)) deps.push(slot)\n }\n return deps\n }\n const units: AiBuildUnit[] = []\n plan.create.forEach((creation, index) => {\n if (!AI_BUILD_CREATE_KINDS.includes(creation.kind)) return\n const slot = `c${index}`\n // A form is built after the dataset it writes to (AGL-3616).\n units.push({\n slot,\n op: creationOp(creation),\n label: creation.name,\n creation,\n deps: depsOf([creation.duplicateOf, creation.kind === 'form' ? (creation.writesTo ?? null) : null], slot),\n })\n })\n for (const item of plan.items ?? []) {\n units.push({\n slot: item.slot,\n op: item.op,\n label: item.name,\n item,\n // What it depends on, and what its arguments link as `new:` (AGL-3728).\n deps: depsOf([...item.dependsOn, ...aiBuildItemArgRefs(item.args)], item.slot, true),\n })\n }\n plan.screens.forEach((screen, index) => {\n const slot = `p${index}`\n units.push({ slot, op: 'page', label: screen.title, screen, deps: depsOf(aiBuildScreenRefs(screen), slot) })\n })\n // A store's own pages (AGL-3676), added by the platform: last, so every\n // planned page keeps the first claim on the site's pages allowance.\n if (aiBuildStorePagesAdded(plan).length) {\n units.push({ slot: AI_BUILD_STORE_SLOT, op: AI_BUILD_STORE_OP, label: AI_BUILD_STORE_PAGES_LABEL, deps: [] })\n }\n return units\n}\n\n/** Whether a unit is one the platform adds rather than the plan (AGL-3676): a store's own pages. */\nexport function aiBuildUnitIsPlatform(unit: Pick<AiBuildUnit, 'op'>): boolean {\n return unit.op === AI_BUILD_STORE_OP\n}\n\n/**\n * The units in an order that builds every dependency before what depends on\n * it, plan order otherwise; `null` when the dependencies hold a cycle.\n */\nexport function aiBuildOrder(units: readonly AiBuildUnit[]): AiBuildUnit[] | null {\n const ordered: AiBuildUnit[] = []\n const placed = new Set<string>()\n const known = new Set(units.map((unit) => unit.slot))\n while (ordered.length < units.length) {\n const next = units.find(\n (unit) => !placed.has(unit.slot) && unit.deps.every((dep) => placed.has(dep) || !known.has(dep)),\n )\n if (!next) return null\n ordered.push(next)\n placed.add(next.slot)\n }\n return ordered\n}\n\n/**\n * What is wrong with a plan's references as a build reads them: a\n * `new:<name>` an item depends on that nothing in the plan makes, and a\n * cycle. Each is a sentence the plan's one re-ask carries.\n */\nexport function aiBuildGraphProblems(plan: AiBuildPlan): string[] {\n const problems: string[] = []\n const slots = namedSlots(plan)\n for (const item of plan.items ?? []) {\n for (const ref of item.dependsOn) {\n if (!isAiPlanNewRef(ref)) continue\n if (!slots.has(aiBuildRefName(ref))) {\n problems.push(`The item \"${item.name}\" depends on ${ref}, which the plan never makes. Declare it, or take it out of dependsOn.`)\n } else if (aiBuildRefName(ref) === item.name.toLowerCase()) {\n problems.push(`The item \"${item.name}\" depends on itself. Take it out of its own dependsOn.`)\n }\n }\n }\n if (!aiBuildOrder(aiBuildUnits(plan))) {\n problems.push('The plan’s dependencies go round in a circle, so nothing in the circle can be built first. Make one of them depend on nothing.')\n }\n return problems\n}\n\n/** The operations a build may plan, as the registry and the gates left them, by op. */\nexport type AiBuildOps = ReadonlyMap<string, PluginAiCapability>\n\n/** How many pages a build may hold on this workspace. */\nexport function aiBuildPageLimit(freeTaste: boolean | null | undefined): number {\n return freeTaste ? AI_BUILD_LIMITS.freePages : AI_BUILD_LIMITS.pages\n}\n\n/**\n * Why a build cannot build a plan of this shape, in a sentence a member\n * reads; `null` when it can. Held to the plan with the one re-ask (the plan\n * step's scope), and again by the doors before a confirmed plan runs.\n * `ops` is what may be planned on this site; absent, items are not judged\n * against the registry (a console reading a kept plan).\n */\nexport function aiBuildPlanShapeRefusal(\n plan: AiBuildPlan,\n options: { freeTaste?: boolean; ops?: AiBuildOps } = {},\n): string | null {\n // What the platform adds beside the plan (a store's own pages) is no part of its size.\n const units = aiBuildUnits(plan).filter((unit) => !aiBuildUnitIsPlatform(unit))\n if (!units.length) return 'This plan builds nothing. Describe what to build again.'\n if (units.length > AI_BUILD_LIMITS.units) {\n return `This plan builds ${units.length} things, and one build holds ${AI_BUILD_LIMITS.units}. Ask for the rest in a second request.`\n }\n const pages = aiBuildPageLimit(options.freeTaste)\n if (plan.screens.length > pages) {\n return options.freeTaste\n ? `This plan builds ${plan.screens.length} pages, and a Free workspace's build makes at most ${pages}. Paid plans can build more.`\n : `This plan builds ${plan.screens.length} pages, and one build makes at most ${pages}.`\n }\n const slugs = new Set<string>()\n for (const screen of plan.screens) {\n if (!screen.sections.length) return `The page “${screen.title}” has no sections to build.`\n if (screen.sections.length > AI_SITE_MAX_SECTIONS) {\n return `The page “${screen.title}” has ${screen.sections.length} sections, and a built page holds ${AI_SITE_MAX_SECTIONS}.`\n }\n const slug = screen.slug.trim().toLowerCase()\n if (slugs.has(slug)) return `Two pages in this plan share the address ${screen.slug}.`\n slugs.add(slug)\n }\n for (const creation of plan.create) {\n if (!AI_BUILD_CREATE_KINDS.includes(creation.kind)) {\n return `A build does not create ${creation.kind === 'theme-change' ? 'theme changes' : `${creation.kind}s`} (“${creation.name}”). Take it out of create.`\n }\n }\n const graph = aiBuildGraphProblems(plan)\n if (graph.length) return graph[0]\n const ops = options.ops\n const counts = new Map<string, number>()\n for (const unit of units) counts.set(unit.op, (counts.get(unit.op) ?? 0) + 1)\n for (const item of plan.items ?? []) {\n if (AI_BUILD_STRUCTURAL_OPS.includes(item.op)) {\n return item.op === 'page'\n ? `“${item.name}” is a page: plan it in screens, not items.`\n : `“${item.name}” is ${item.op === 'email' ? 'an' : 'a'} ${item.op}: plan it in create, not items.`\n }\n if (!ops) continue\n const capability = ops.get(item.op)\n if (!capability) return `Nothing on this site can make “${item.name}” (${item.op}). Take it out of items.`\n if (options.freeTaste && !capability.freeAllowed) {\n return `A Free workspace cannot have ${aiArticle(capability.noun)} made (“${item.name}”). Take it out of items.`\n }\n const problems = pluginAiCapabilityArgsProblems(capability.argsSchema, item.args)\n if (problems.length) return `The arguments of “${item.name}” do not read: ${problems.join('; ')}.`\n }\n if (ops) {\n for (const [op, count] of counts) {\n const capability = ops.get(op)\n if (capability && count > capability.maxPerPlan) {\n return `This plan makes ${count} of “${capability.noun}”, and one build makes at most ${capability.maxPerPlan}.`\n }\n }\n }\n return null\n}\n\n/** \"a booking service\", \"an email design\". */\nexport function aiArticle(noun: string): string {\n return `${/^[aeiou]/i.test(noun) ? 'an' : 'a'} ${noun}`\n}\n\n/** The passes one unit is estimated at: a page's sections and its listing, one for a creation. */\nfunction unitPasses(unit: AiBuildUnit): number {\n if (unit.screen) return unit.screen.sections.length + 1\n return 1\n}\n\n/**\n * About what one unit costs, in credits: a page or a creation by the passes\n * it implies at the nominal credits a pass is held against, as a site's are;\n * an item by its capability's own estimate, recorded on the plan when it was\n * kept.\n */\nexport function aiBuildUnitCreditEstimate(unit: AiBuildUnit, ops?: AiBuildOps): number {\n // A store's own pages are written by code, with no model: no credits (AGL-3676).\n if (aiBuildUnitIsPlatform(unit)) return 0\n if (unit.item) {\n if (typeof unit.item.credits === 'number') return unit.item.credits\n const capability = ops?.get(unit.item.op)\n if (capability) return Math.max(0, Math.floor(capability.estimateCredits(unit.item.args)))\n return AI_SITE_PASS_CREDITS\n }\n return unitPasses(unit) * AI_SITE_PASS_CREDITS\n}\n\n/**\n * About what a build costs, in credits: every unit's estimate, or only the\n * units named in `slots` — what Try again shows. The ceiling a member\n * confirms; the meter charges what actually runs.\n */\nexport function aiBuildCreditEstimate(\n plan: AiBuildPlan,\n options: { ops?: AiBuildOps; slots?: ReadonlySet<string> } = {},\n): number {\n return aiBuildUnits(plan)\n .filter((unit) => !options.slots || options.slots.has(unit.slot))\n .reduce((total, unit) => total + aiBuildUnitCreditEstimate(unit, options.ops), 0)\n}\n\n/**\n * About what a job of this kind costs to build from its plan: a build's\n * units, every other planned kind as `aiJobPlanCreditEstimate` counts it.\n */\nexport function aiJobCreditEstimate(kind: string, plan: AiBuildPlan): number {\n return kind === 'build' ? aiBuildCreditEstimate(plan) : aiJobPlanCreditEstimate(kind, plan)\n}\n\n/**\n * What one unit is likely to cost, its p90 and its ceiling (AGL-3722): a page\n * as a page written on its own measured (a fixed cost and one per section), a creation at what its kind\n * measured, an item at the measured pass times the passes its capability\n * estimates (none for a draft another plugin writes, which asks no model).\n * The ceiling is `aiBuildUnitCreditEstimate`, unchanged.\n */\nexport function aiBuildUnitCreditRange(unit: AiBuildUnit, ops?: AiBuildOps): AiCreditRange {\n const ceiling = aiBuildUnitCreditEstimate(unit, ops)\n // A build writes each page on its own, never in a site start's warm run (AGL-3722).\n if (unit.screen) return aiStandaloneScreenCreditRange(unit.screen.sections.length)\n if (unit.creation) return aiCreditRangeOf(aiCreationMeasuredCredits(unit.creation.kind, { standalone: true }), ceiling)\n const passes = Math.ceil(ceiling / AI_SITE_PASS_CREDITS)\n return aiCreditRangeOf(\n { median: passes * AI_MEASURED_PASS_CREDITS.median, p90: passes * AI_MEASURED_PASS_CREDITS.p90 },\n ceiling,\n )\n}\n\n/**\n * What a build is likely to cost, its p90 and its ceiling (AGL-3722): every\n * unit's range, or only the units named in `slots` — what Try again runs.\n * The plan card, Try again and the Free admission all read this; the meter\n * charges what actually runs.\n */\nexport function aiBuildCreditRange(\n plan: AiBuildPlan,\n options: { ops?: AiBuildOps; slots?: ReadonlySet<string> } = {},\n): AiCreditRange {\n return aiCreditRangeOrdered(\n aiBuildUnits(plan)\n .filter((unit) => !options.slots || options.slots.has(unit.slot))\n .reduce((total, unit) => aiCreditRangeAdd(total, aiBuildUnitCreditRange(unit, options.ops)), AI_CREDIT_RANGE_ZERO),\n )\n}\n\n/** `aiJobCreditEstimate` as a range (AGL-3722). */\nexport function aiJobCreditRange(kind: string, plan: AiBuildPlan): AiCreditRange {\n return kind === 'build' ? aiBuildCreditRange(plan) : aiJobPlanCreditRange(kind, plan)\n}\n\n/**\n * A smaller first build (AGL-3722): the plan's home page — its first page\n * where it has no home — and only what that page needs, transitively: the\n * layout it is drawn in, the form and anything else its sections place.\n * Every other page, and what only they needed, waits for a later request.\n * `null` when the plan has no page, or when the smaller plan is the whole one.\n */\nexport function aiBuildFirstPagePlan<T extends AiBuildPlan>(plan: T): T | null {\n if (!plan.screens.length) return null\n const index = Math.max(0, plan.screens.findIndex(aiSitePlanIsHome))\n const units = aiBuildUnits(plan).filter((unit) => !aiBuildUnitIsPlatform(unit))\n const bySlot = new Map(units.map((unit) => [unit.slot, unit]))\n const keep = new Set<string>()\n const queue = [`p${index}`]\n while (queue.length) {\n const slot = queue.shift() as string\n if (keep.has(slot)) continue\n keep.add(slot)\n for (const dep of bySlot.get(slot)?.deps ?? []) queue.push(dep)\n }\n if (keep.size === units.length) return null\n const screen = plan.screens[index]\n const create = plan.create.filter((creation, at) => !AI_BUILD_CREATE_KINDS.includes(creation.kind) || keep.has(`c${at}`))\n const items = (plan.items ?? []).filter((item) => keep.has(item.slot))\n const kept = new Set([screen.slug, ...create.map((entry) => `${AI_PLAN_NEW_REF_PREFIX}${entry.name}`)])\n const smaller: T = {\n ...plan,\n create,\n screens: [screen],\n ...(plan.items ? { items } : {}),\n ...(plan.embeds ? { embeds: plan.embeds.filter((embed) => kept.has(embed.where)) } : {}),\n }\n // The store's own pages stay only while the smaller build still makes a store (AGL-3676).\n if (smaller.storePages && !aiBuildMakesStore(smaller)) delete smaller.storePages\n return smaller\n}\n\n/** The smaller first build a build that does not fit is offered (AGL-3722), with its range; `null` when there is none. */\nexport function aiBuildSmaller(plan: AiBuildPlan, ops?: AiBuildOps): AiCreditsSmaller | null {\n const smaller = aiBuildFirstPagePlan(plan)\n if (!smaller) return null\n const screen = smaller.screens[0]\n const label = aiSitePlanIsHome(screen) ? AI_SITE_HOME_FIRST_LABEL : `Build the ${screen.title} page first`\n return { label, ...aiBuildCreditRange(smaller, { ops }) }\n}\n\n/** A fresh ledger: one pending row per unit, first attempt. */\nexport function aiBuildInitialLedger(units: readonly AiBuildUnit[]): AiJobItemLedger[] {\n return units.map((unit) => ({\n slot: unit.slot,\n op: unit.op,\n label: unit.label,\n status: 'pending',\n attempt: 1,\n creditsSpent: 0,\n attemptCredits: 0,\n creditsRefunded: 0,\n failure: null,\n outputs: [],\n }))\n}\n\nconst OPEN: readonly AiJobItemStatus[] = ['pending', 'running']\n\n/** Whether an item is still to be built. */\nexport function aiBuildItemOpen(row: Pick<AiJobItemLedger, 'status'>): boolean {\n return OPEN.includes(row.status)\n}\n\n/** Whether an item delivered: built as planned, or built without something that failed. */\nexport function aiBuildItemDelivered(row: Pick<AiJobItemLedger, 'status'>): boolean {\n return row.status === 'succeeded' || row.status === 'degraded'\n}\n\n/**\n * The next unit to build: the first in build order whose row is still open.\n * Its dependencies come before it, so by then each is settled one way or the\n * other. `null` when nothing is left.\n */\nexport function aiBuildNextUnit(\n ordered: readonly AiBuildUnit[],\n ledger: readonly AiJobItemLedger[],\n): AiBuildUnit | null {\n const rows = new Map(ledger.map((row) => [row.slot, row]))\n return ordered.find((unit) => {\n const row = rows.get(unit.slot)\n return !row || aiBuildItemOpen(row)\n }) ?? null\n}\n\n/** How a unit is built given what its dependencies came to. */\nexport interface AiBuildDegradation {\n /** The unit is not built at all, with the sentence why; nothing is spent. */\n skip: string | null\n /** The failed dependencies that change how it is built. */\n degradedBy: string[]\n /** What the person reads about the change; one per failed dependency. */\n notes: string[]\n /** `new:<name>` references (lowercased names) to leave out. */\n dropped: Set<string>\n /** Brief lines for the unit's own job: what to leave out, and what to place. */\n briefLines: string[]\n}\n\n/**\n * How a unit is built when some of what it depends on failed (AGL-3616).\n *\n * A PAGE is always built: a failed layout falls back to the site's own, a\n * failed form or component is left out of its section, and a failed item a\n * section places (a booking service) takes its block out of the page — each\n * with a note. Any OTHER unit whose dependency failed is skipped when that\n * dependency's capability says `omit` (a campaign whose email design failed\n * has nothing to send), and built without it when it says `fallback`.\n */\nexport function aiBuildDegradation(\n unit: AiBuildUnit,\n context: {\n units: readonly AiBuildUnit[]\n ledger: readonly AiJobItemLedger[]\n ops?: AiBuildOps\n },\n): AiBuildDegradation {\n const rows = new Map(context.ledger.map((row) => [row.slot, row]))\n const bySlot = new Map(context.units.map((one) => [one.slot, one]))\n const result: AiBuildDegradation = { skip: null, degradedBy: [], notes: [], dropped: new Set(), briefLines: [] }\n for (const slot of unit.deps) {\n const dep = bySlot.get(slot)\n const row = rows.get(slot)\n if (!dep || !row || aiBuildItemDelivered(row)) continue\n const noun = dep.creation\n ? aiBuildCreationNoun(dep.creation.kind)\n : (context.ops?.get(dep.op)?.noun ?? dep.op)\n const capability = dep.item ? context.ops?.get(dep.op) : undefined\n const degrade = dep.item?.degrade ?? capability?.degrade ?? (dep.creation?.kind === 'layout' ? 'fallback' : 'omit')\n // A form whose dataset could not be made is built without it (AGL-3616):\n // its submissions reach the Inbox, as any form's do.\n if (aiBuildUnitWritesTo(unit) === dep.label.toLowerCase()) {\n result.degradedBy.push(slot)\n result.notes.push(`Its submissions arrive in the Inbox only: the dataset “${dep.label}” could not be created.`)\n continue\n }\n if (!unit.screen && degrade === 'omit') {\n result.skip = `Not built: the ${noun} “${dep.label}” it needs could not be created.`\n result.degradedBy.push(slot)\n return result\n }\n result.degradedBy.push(slot)\n result.dropped.add(dep.label.toLowerCase())\n if (dep.creation?.kind === 'layout') {\n result.notes.push(`Built inside the site’s own layout: the layout “${dep.label}” could not be created.`)\n continue\n }\n if (unit.screen) {\n const section = unit.screen.sections.find((one) =>\n one.uses.some((ref) => isAiPlanNewRef(ref) && aiBuildRefName(ref) === dep.label.toLowerCase()),\n )\n // Another item this section places with the same block was built (one\n // of several events, AGL-3743): the block stays, and only this item is\n // missing from what it shows.\n const blockStays = Boolean(\n section &&\n capability?.pageBlocks?.length &&\n aiBuildSectionDeliveredBlocks(section, { ...context, rows, except: slot }).has(aiBuildBlocksKey(capability.pageBlocks)),\n )\n if (blockStays) {\n result.notes.push(`Built without the ${noun} “${dep.label}”: it could not be created.`)\n result.briefLines.push(`Leave the ${noun} “${dep.label}” out of the “${section?.name}” section: it could not be created.`)\n continue\n }\n const blocks = capability?.pageBlocks?.length ? ` the ${capability.pageBlocks.join(' or ')} block` : ''\n result.notes.push(\n `Built without${blocks || ` the ${noun}`}: the ${noun} “${dep.label}” could not be created.`,\n )\n result.briefLines.push(\n `${section ? `Build the “${section.name}” section` : 'Build the page'} without the ${noun} “${dep.label}”${blocks ? ` and without${blocks}` : ''}: it could not be created.`,\n )\n } else {\n result.notes.push(`Built without the ${noun} “${dep.label}”: it could not be created.`)\n }\n }\n return result\n}\n\n/** The dataset a form unit writes to, by its `new:` name lowercased; `null` for any other unit (AGL-3616). */\nexport function aiBuildUnitWritesTo(unit: Pick<AiBuildUnit, 'creation'>): string | null {\n const ref = unit.creation?.kind === 'form' ? unit.creation.writesTo : null\n return isAiPlanNewRef(ref) ? aiBuildRefName(ref) : null\n}\n\n/** What each creation is called in a note. */\nexport function aiBuildCreationNoun(kind: AiBuildPlanCreateKind): string {\n return kind === 'email' ? 'email design' : kind === 'theme-change' ? 'theme change' : kind\n}\n\n/**\n * The brief lines a page is told about the items its sections place and\n * that were built: the block to put there, in the owner's words.\n */\nexport function aiBuildPlacedItemLines(\n unit: AiBuildUnit,\n context: { units: readonly AiBuildUnit[]; ledger: readonly AiJobItemLedger[]; ops?: AiBuildOps },\n): string[] {\n if (!unit.screen) return []\n const rows = new Map(context.ledger.map((row) => [row.slot, row]))\n const lines: string[] = []\n for (const section of unit.screen.sections) {\n // One line per block a section places, naming every built item it shows:\n // a section listing four events places the Event List once (AGL-3743).\n const placed = new Map<string, { blocks: readonly string[]; noun: string; labels: string[] }>()\n for (const { dep, capability } of aiBuildSectionItems(section, context.units, context.ops)) {\n const row = rows.get(dep.slot)\n if (!row || !aiBuildItemDelivered(row)) continue\n const blocks = capability?.pageBlocks ?? []\n if (!blocks.length) continue\n const key = aiBuildBlocksKey(blocks)\n const entry = placed.get(key) ?? { blocks, noun: capability?.noun ?? dep.op, labels: [] }\n entry.labels.push(`“${dep.label}”`)\n placed.set(key, entry)\n }\n for (const { blocks, noun, labels } of placed.values()) {\n const named =\n labels.length === 1\n ? `the ${noun} ${labels[0]}`\n : `the ${noun}s ${labels.slice(0, -1).join(', ')} and ${labels[labels.length - 1]}`\n lines.push(`In the “${section.name}” section, place the ${blocks.join(' or ')} block for ${named}.`)\n }\n }\n return lines\n}\n\n/** The items a page section places, each with its capability, in the order its uses name them. */\nfunction aiBuildSectionItems(\n section: { uses: readonly string[] },\n units: readonly AiBuildUnit[],\n ops: AiBuildOps | undefined,\n): Array<{ dep: AiBuildUnit; capability: PluginAiCapability | undefined }> {\n const found: Array<{ dep: AiBuildUnit; capability: PluginAiCapability | undefined }> = []\n for (const ref of section.uses) {\n if (!isAiPlanNewRef(ref)) continue\n const dep = units.find((one) => one.item && one.item.name.toLowerCase() === aiBuildRefName(ref))\n if (dep?.item) found.push({ dep, capability: ops?.get(dep.op) })\n }\n return found\n}\n\n/** The blocks a section's built items place, each set as one key; `except` leaves one item out. */\nfunction aiBuildSectionDeliveredBlocks(\n section: { uses: readonly string[] },\n context: { units: readonly AiBuildUnit[]; rows: ReadonlyMap<string, AiJobItemLedger>; ops?: AiBuildOps; except: string },\n): Set<string> {\n const keys = new Set<string>()\n for (const { dep, capability } of aiBuildSectionItems(section, context.units, context.ops)) {\n if (dep.slot === context.except || !capability?.pageBlocks?.length) continue\n const row = context.rows.get(dep.slot)\n if (row && aiBuildItemDelivered(row)) keys.add(aiBuildBlocksKey(capability.pageBlocks))\n }\n return keys\n}\n\nfunction aiBuildBlocksKey(blocks: readonly string[]): string {\n return [...blocks].sort().join('|')\n}\n\n/** What a build came to: whether anything was delivered, and whether anything is left. */\nexport function aiBuildSettlement(ledger: readonly AiJobItemLedger[]): {\n delivered: boolean\n open: boolean\n failed: number\n} {\n return {\n delivered: ledger.some(aiBuildItemDelivered),\n open: ledger.some(aiBuildItemOpen),\n failed: ledger.filter((row) => row.status === 'failed').length,\n }\n}\n\n/**\n * The ledger Try again runs (AGL-3616): every failed item back to `pending`\n * on its next attempt, with the items left unbuilt because of it — skipped,\n * or degraded with no draft — and every item the build never reached. An\n * item that succeeded is never run again, and a degraded page that has its\n * draft keeps it, with a note that the page needs an edit. `retried` names\n * the slots that will run, which is what the estimate is shown for.\n */\nexport function aiBuildRetryLedger(\n ledger: readonly AiJobItemLedger[],\n units: readonly AiBuildUnit[],\n): { ledger: AiJobItemLedger[]; retried: string[] } {\n const failed = new Set(ledger.filter((row) => row.status === 'failed').map((row) => row.slot))\n const dependents = new Map<string, string[]>()\n for (const unit of units) {\n for (const dep of unit.deps) dependents.set(dep, [...(dependents.get(dep) ?? []), unit.slot])\n }\n // Everything downstream of a failed item, transitively.\n const downstream = new Set<string>()\n const queue = [...failed]\n while (queue.length) {\n const slot = queue.shift() as string\n for (const next of dependents.get(slot) ?? []) {\n if (downstream.has(next)) continue\n downstream.add(next)\n queue.push(next)\n }\n }\n const retried: string[] = []\n const next = ledger.map((row): AiJobItemLedger => {\n const again =\n row.status === 'failed' ||\n (row.status === 'skipped' && (downstream.has(row.slot) || !(row.degradedBy ?? []).length)) ||\n (row.status === 'degraded' && downstream.has(row.slot) && !row.outputs.length)\n if (again) {\n retried.push(row.slot)\n return {\n ...row,\n status: 'pending',\n attempt: row.attempt + 1,\n attemptCredits: 0,\n failure: null,\n note: null,\n degradedBy: [],\n settledAt: null,\n }\n }\n if (row.status === 'degraded' && downstream.has(row.slot) && row.outputs.length) {\n return {\n ...row,\n note: `${row.note ? `${row.note} ` : ''}It keeps its draft: once the rest is built, edit this page to add what it is missing.`,\n }\n }\n return row\n })\n return { ledger: next, retried }\n}\n\n/**\n * Units read back off a ledger alone (AGL-3616), for a job whose units are\n * not a build plan's — a site scaffold's: each row as its unit, and every\n * page built after the layouts and forms the ledger holds.\n */\nexport function aiLedgerUnits(ledger: readonly AiJobItemLedger[]): AiBuildUnit[] {\n const creations = ledger.filter((row) => row.op === 'layout' || row.op === 'form').map((row) => row.slot)\n return ledger.map((row) => ({\n slot: row.slot,\n op: row.op,\n label: row.label,\n deps: row.op === 'page' ? creations : [],\n }))\n}\n"],"names":["pluginAiCapabilityArgsProblems","AI_PLAN_NEW_REF_PREFIX","isAiPlanNewRef","AI_BUILD_STORE_OP","AI_BUILD_STORE_PAGES_LABEL","AI_BUILD_STORE_SLOT","aiBuildMakesStore","aiBuildStorePagesAdded","AI_SITE_HOME_FIRST_LABEL","AI_SITE_MAX_SECTIONS","AI_SITE_PASS_CREDITS","aiCreationMeasuredCredits","aiJobPlanCreditEstimate","aiJobPlanCreditRange","aiSitePlanIsHome","aiStandaloneScreenCreditRange","AI_CREDIT_RANGE_ZERO","AI_MEASURED_PASS_CREDITS","aiCreditRangeAdd","aiCreditRangeOf","aiCreditRangeOrdered","AI_BUILD_LIMITS","units","pages","freePages","aiBuildFreePageCapNote","plan","freeTaste","cap","screens","length","AI_BUILD_CREATE_KINDS","AI_BUILD_STRUCTURAL_OPS","AI_BUILD_MADE_INPUT","AI_BUILD_PUBLISH_INPUT","creationOp","creation","kind","namedSlots","slots","Map","create","forEach","index","includes","set","name","toLowerCase","item","items","slot","aiBuildRefName","ref","slice","trim","aiBuildItemArgRefs","args","refs","take","value","part","split","push","Object","values","Array","isArray","aiBuildScreenRefs","screen","layout","template","duplicateOf","sections","flatMap","section","uses","filter","aiBuildUnits","pageSlots","title","has","depsOf","self","deps","get","undefined","op","label","writesTo","dependsOn","aiBuildUnitIsPlatform","unit","aiBuildOrder","ordered","placed","Set","known","map","next","find","every","dep","add","aiBuildGraphProblems","problems","aiBuildPageLimit","aiBuildPlanShapeRefusal","options","counts","slugs","slug","graph","ops","capability","freeAllowed","aiArticle","noun","argsSchema","join","count","maxPerPlan","test","unitPasses","aiBuildUnitCreditEstimate","credits","Math","max","floor","estimateCredits","aiBuildCreditEstimate","reduce","total","aiJobCreditEstimate","aiBuildUnitCreditRange","ceiling","standalone","passes","ceil","median","p90","aiBuildCreditRange","aiJobCreditRange","aiBuildFirstPagePlan","findIndex","bySlot","keep","queue","shift","size","at","kept","entry","smaller","embeds","embed","where","storePages","aiBuildSmaller","aiBuildInitialLedger","status","attempt","creditsSpent","attemptCredits","creditsRefunded","failure","outputs","OPEN","aiBuildItemOpen","row","aiBuildItemDelivered","aiBuildNextUnit","ledger","rows","aiBuildDegradation","context","one","result","skip","degradedBy","notes","dropped","briefLines","aiBuildCreationNoun","degrade","aiBuildUnitWritesTo","some","blockStays","Boolean","pageBlocks","aiBuildSectionDeliveredBlocks","except","aiBuildBlocksKey","blocks","aiBuildPlacedItemLines","lines","aiBuildSectionItems","key","labels","named","found","keys","sort","aiBuildSettlement","delivered","open","failed","aiBuildRetryLedger","dependents","downstream","retried","again","note","settledAt","aiLedgerUnits","creations"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,8BAA8B,QAEzB,qDAAoD;AAC3D,SACEC,sBAAsB,EACtBC,cAAc,QAMT,qBAAiB;AAExB,SACEC,iBAAiB,EACjBC,0BAA0B,EAC1BC,mBAAmB,EACnBC,iBAAiB,EACjBC,sBAAsB,QACjB,4BAAwB;AAC/B,SACEC,wBAAwB,EACxBC,oBAAoB,EACpBC,oBAAoB,EACpBC,yBAAyB,EACzBC,uBAAuB,EACvBC,oBAAoB,EACpBC,gBAAgB,EAChBC,6BAA6B,QACxB,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AI;YACrB,OAAO,aACFsH;gBACHT,QAAQ;gBACRC,SAASQ,IAAIR,OAAO,GAAG;gBACvBE,gBAAgB;gBAChBE,SAAS;gBACT+C,MAAM;gBACNjC,YAAY,EAAE;gBACdkC,WAAW;;QAEf;QACA,IAAI5C,IAAIT,MAAM,KAAK,cAAciD,WAAWhI,GAAG,CAACwF,IAAItH,IAAI,KAAKsH,IAAIH,OAAO,CAACvI,MAAM,EAAE;YAC/E,OAAO,aACF0I;gBACH2C,MAAM,GAAG3C,IAAI2C,IAAI,GAAG,GAAG3C,IAAI2C,IAAI,CAAC,CAAC,CAAC,GAAG,GAAG,qFAAqF,CAAC;;QAElI;QACA,OAAO3C;IACT;IACA,OAAO;QAAEG,QAAQzE;QAAM+G;IAAQ;AACjC;AAEA;;;;CAIC,GACD,OAAO,SAASI,cAAc1C,MAAkC;IAC9D,MAAM2C,YAAY3C,OAAO/F,MAAM,CAAC,CAAC4F,MAAQA,IAAIlF,EAAE,KAAK,YAAYkF,IAAIlF,EAAE,KAAK,QAAQW,GAAG,CAAC,CAACuE,MAAQA,IAAItH,IAAI;IACxG,OAAOyH,OAAO1E,GAAG,CAAC,CAACuE,MAAS,CAAA;YAC1BtH,MAAMsH,IAAItH,IAAI;YACdoC,IAAIkF,IAAIlF,EAAE;YACVC,OAAOiF,IAAIjF,KAAK;YAChBJ,MAAMqF,IAAIlF,EAAE,KAAK,SAASgI,YAAY,EAAE;QAC1C,CAAA;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-build-job.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n pluginAiCapabilityArgsProblems,\n type PluginAiCapability,\n} from '@aglyn/aglyn/plugin-manager/plugin-ai-capabilities'\nimport type { PluginDraftRecord } from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport {\n AI_PLAN_NEW_REF_PREFIX,\n isAiPlanNewRef,\n type AiBuildItem,\n type AiBuildPlan,\n type AiBuildPlanCreate,\n type AiBuildPlanCreateKind,\n type AiBuildPlanScreen,\n} from './ai-build-plan'\nimport type { AiJobItemLedger, AiJobItemStatus } from './ai-jobs.types'\nimport {\n AI_BUILD_STORE_OP,\n AI_BUILD_STORE_PAGES_LABEL,\n AI_BUILD_STORE_SLOT,\n aiBuildMakesStore,\n aiBuildStorePagesAdded,\n} from './ai-build-store-pages'\nimport {\n AI_SITE_HOME_FIRST_LABEL,\n AI_SITE_MAX_SECTIONS,\n AI_SITE_PASS_CREDITS,\n aiCreationMeasuredCredits,\n aiJobPlanCreditEstimate,\n aiJobPlanCreditRange,\n aiSitePlanIsHome,\n aiStandaloneScreenCreditRange,\n} from './ai-site-job'\nimport {\n AI_CREDIT_RANGE_ZERO,\n AI_MEASURED_PASS_CREDITS,\n aiCreditRangeAdd,\n aiCreditRangeOf,\n aiCreditRangeOrdered,\n type AiCreditRange,\n type AiCreditsSmaller,\n} from './ai-credit-estimate'\n\n/**\n * What a `build` job is (AGL-3616): one request — \"a few pages, a contact\n * form and a way to book me\" — planned as creations, pages and items, built\n * one UNIT a pass in dependency order, and settled ITEM BY ITEM.\n *\n * A build is a generalized site scaffold. Every unit is handed to what\n * already builds that kind of thing — a page to the page step, a form to the\n * form step, another plugin's resource to that plugin's draft writer — so a\n * build cannot drift from what it builds. What is new is the settlement: one\n * failed unit does not end the job. It gives back its own spend, the units\n * that depended on it are built without it (or skipped, when they cannot\n * stand without it), and the job is `done` when anything was delivered.\n *\n * This module is the build's MODEL — its units, their order, how a failure\n * travels to what depends on it, what it is estimated to cost, and the\n * ledger arithmetic — and does no I/O, so the step, the machine, the doors\n * and the console read one vocabulary.\n */\n\n/** How much one build holds: what one proposal can describe and one person can read. */\nexport const AI_BUILD_LIMITS = {\n /** Creations, pages and items together. */\n units: 16,\n pages: 8,\n /** A Free workspace's pages. */\n freePages: 2,\n} as const\n\n/**\n * What a Free build's plan card says when it holds as many pages as a Free\n * build makes (AGL-3722): the plan is told the cap and plans the first pages\n * a request asks for, so a request for three — \"About us, Custom cakes and\n * Catering\", 2026-10-10 — came back as two with nothing saying why. `null`\n * when the plan holds fewer, or on a paid workspace.\n */\nexport function aiBuildFreePageCapNote(plan: Pick<AiBuildPlan, 'screens'>, freeTaste: boolean): string | null {\n const cap = AI_BUILD_LIMITS.freePages\n if (!freeTaste || plan.screens.length < cap) return null\n return `A Free workspace’s build makes up to ${cap} pages at a time. If you asked for more, ask Assist for the rest once this build is done.`\n}\n\n/** What a build creates through its `create` list; everything else beyond pages is an item. */\nexport const AI_BUILD_CREATE_KINDS: readonly AiBuildPlanCreateKind[] = ['layout', 'form', 'component', 'email']\n\n/**\n * The operations a build plans through `create` and `screens` rather than\n * `items`: an item naming one is a plan that put it in the wrong list.\n */\nexport const AI_BUILD_STRUCTURAL_OPS: readonly string[] = ['page', ...AI_BUILD_CREATE_KINDS]\n\n/**\n * What a build hands an item it made before it (AGL-3728): its pages, by the\n * title the plan gave each and the id it was written under, and its layouts,\n * by name. An item's `new:<title>` destinations are read against it.\n */\nexport const AI_BUILD_MADE_INPUT = 'buildMade'\n\nexport interface AiBuildMade {\n pages: Array<{ title: string; id: string }>\n layouts: Array<{ name: string; id: string }>\n}\n\n/** The job input a build's Assist proposal sets when the brief asked to publish. */\nexport const AI_BUILD_PUBLISH_INPUT = 'publish'\n\n/** A unit of a build: a creation, a page, or an item. */\nexport interface AiBuildUnit {\n slot: string\n /** The capability operation that builds it. */\n op: string\n label: string\n creation?: AiBuildPlanCreate\n screen?: AiBuildPlanScreen\n item?: AiBuildItem\n /** The slots it is built after, in plan order. */\n deps: string[]\n}\n\n/** The operation a creation is built as. */\nfunction creationOp(creation: AiBuildPlanCreate): string {\n return creation.kind\n}\n\n/** A plan's `new:<name>` names, each to the slot that builds it. */\nfunction namedSlots(plan: AiBuildPlan): Map<string, string> {\n const slots = new Map<string, string>()\n plan.create.forEach((creation, index) => {\n if (AI_BUILD_CREATE_KINDS.includes(creation.kind)) slots.set(creation.name.toLowerCase(), `c${index}`)\n })\n for (const item of plan.items ?? []) slots.set(item.name.toLowerCase(), item.slot)\n return slots\n}\n\n/** The name a `new:<name>` reference gives, lowercased. */\nexport function aiBuildRefName(ref: string): string {\n return ref.slice(AI_PLAN_NEW_REF_PREFIX.length).trim().toLowerCase()\n}\n\n/**\n * The `new:<name>` references an item's arguments make (AGL-3728): an\n * argument that is one, or the destination after `=>` in an entry such as a\n * menu item's `About => new:About`. Read from the arguments, never from the\n * model's `dependsOn`, so what an item links is always built before it.\n */\nexport function aiBuildItemArgRefs(args: Readonly<Record<string, unknown>> | null | undefined): string[] {\n const refs: string[] = []\n const take = (value: unknown) => {\n if (typeof value !== 'string') return\n for (const part of [value, value.split('=>').slice(-1)[0] ?? '']) {\n const ref = part.trim()\n if (isAiPlanNewRef(ref) && !refs.includes(ref)) refs.push(ref)\n }\n }\n for (const value of Object.values(args ?? {})) {\n if (Array.isArray(value)) value.forEach(take)\n else take(value)\n }\n return refs\n}\n\n/** Every reference a page makes: its layout, template, starting page and what its sections place. */\nexport function aiBuildScreenRefs(screen: AiBuildPlanScreen): string[] {\n return [\n screen.layout,\n screen.template,\n screen.duplicateOf,\n ...screen.sections.flatMap((section) => section.uses),\n ].filter((ref): ref is string => typeof ref === 'string' && ref.length > 0)\n}\n\n/**\n * The units a plan implies, in plan order: creations, then items, then\n * pages — the order a member reads them in, and the one a page that places\n * a creation or an item is built after anyway. `aiBuildOrder` sorts them on\n * their dependencies.\n */\nexport function aiBuildUnits(plan: AiBuildPlan): AiBuildUnit[] {\n const slots = namedSlots(plan)\n // A page, by the title the plan gave it: what an item's arguments may link\n // as `new:<title>` (a menu item, AGL-3728), built before the item.\n const pageSlots = new Map<string, string>()\n plan.screens.forEach((screen, index) => {\n const title = screen.title.trim().toLowerCase()\n if (title && !pageSlots.has(title)) pageSlots.set(title, `p${index}`)\n })\n const depsOf = (refs: readonly (string | null)[], self: string, pages = false): string[] => {\n const deps: string[] = []\n for (const ref of refs) {\n if (!isAiPlanNewRef(ref)) continue\n const slot = slots.get(aiBuildRefName(ref)) ?? (pages ? pageSlots.get(aiBuildRefName(ref)) : undefined)\n if (slot && slot !== self && !deps.includes(slot)) deps.push(slot)\n }\n return deps\n }\n const units: AiBuildUnit[] = []\n plan.create.forEach((creation, index) => {\n if (!AI_BUILD_CREATE_KINDS.includes(creation.kind)) return\n const slot = `c${index}`\n // A form is built after the dataset it writes to (AGL-3616).\n units.push({\n slot,\n op: creationOp(creation),\n label: creation.name,\n creation,\n deps: depsOf([creation.duplicateOf, creation.kind === 'form' ? (creation.writesTo ?? null) : null], slot),\n })\n })\n for (const item of plan.items ?? []) {\n units.push({\n slot: item.slot,\n op: item.op,\n label: item.name,\n item,\n // What it depends on, and what its arguments link as `new:` (AGL-3728).\n deps: depsOf([...item.dependsOn, ...aiBuildItemArgRefs(item.args)], item.slot, true),\n })\n }\n plan.screens.forEach((screen, index) => {\n const slot = `p${index}`\n units.push({ slot, op: 'page', label: screen.title, screen, deps: depsOf(aiBuildScreenRefs(screen), slot) })\n })\n // A store's own pages (AGL-3676), added by the platform: last, so every\n // planned page keeps the first claim on the site's pages allowance.\n if (aiBuildStorePagesAdded(plan).length) {\n units.push({ slot: AI_BUILD_STORE_SLOT, op: AI_BUILD_STORE_OP, label: AI_BUILD_STORE_PAGES_LABEL, deps: [] })\n }\n return units\n}\n\n/** Whether a unit is one the platform adds rather than the plan (AGL-3676): a store's own pages. */\nexport function aiBuildUnitIsPlatform(unit: Pick<AiBuildUnit, 'op'>): boolean {\n return unit.op === AI_BUILD_STORE_OP\n}\n\n/**\n * The units in an order that builds every dependency before what depends on\n * it, plan order otherwise; `null` when the dependencies hold a cycle.\n */\nexport function aiBuildOrder(units: readonly AiBuildUnit[]): AiBuildUnit[] | null {\n const ordered: AiBuildUnit[] = []\n const placed = new Set<string>()\n const known = new Set(units.map((unit) => unit.slot))\n while (ordered.length < units.length) {\n const next = units.find(\n (unit) => !placed.has(unit.slot) && unit.deps.every((dep) => placed.has(dep) || !known.has(dep)),\n )\n if (!next) return null\n ordered.push(next)\n placed.add(next.slot)\n }\n return ordered\n}\n\n/**\n * What is wrong with a plan's references as a build reads them: a\n * `new:<name>` an item depends on that nothing in the plan makes, and a\n * cycle. Each is a sentence the plan's one re-ask carries.\n */\nexport function aiBuildGraphProblems(plan: AiBuildPlan): string[] {\n const problems: string[] = []\n const slots = namedSlots(plan)\n for (const item of plan.items ?? []) {\n for (const ref of item.dependsOn) {\n if (!isAiPlanNewRef(ref)) continue\n if (!slots.has(aiBuildRefName(ref))) {\n problems.push(`The item \"${item.name}\" depends on ${ref}, which the plan never makes. Declare it, or take it out of dependsOn.`)\n } else if (aiBuildRefName(ref) === item.name.toLowerCase()) {\n problems.push(`The item \"${item.name}\" depends on itself. Take it out of its own dependsOn.`)\n }\n }\n }\n if (!aiBuildOrder(aiBuildUnits(plan))) {\n problems.push('The plan’s dependencies go round in a circle, so nothing in the circle can be built first. Make one of them depend on nothing.')\n }\n return problems\n}\n\n/** The operations a build may plan, as the registry and the gates left them, by op. */\nexport type AiBuildOps = ReadonlyMap<string, PluginAiCapability>\n\n/** How many pages a build may hold on this workspace. */\nexport function aiBuildPageLimit(freeTaste: boolean | null | undefined): number {\n return freeTaste ? AI_BUILD_LIMITS.freePages : AI_BUILD_LIMITS.pages\n}\n\n/**\n * Why a build cannot build a plan of this shape, in a sentence a member\n * reads; `null` when it can. Held to the plan with the one re-ask (the plan\n * step's scope), and again by the doors before a confirmed plan runs.\n * `ops` is what may be planned on this site; absent, items are not judged\n * against the registry (a console reading a kept plan).\n */\nexport function aiBuildPlanShapeRefusal(\n plan: AiBuildPlan,\n options: { freeTaste?: boolean; ops?: AiBuildOps } = {},\n): string | null {\n // What the platform adds beside the plan (a store's own pages) is no part of its size.\n const units = aiBuildUnits(plan).filter((unit) => !aiBuildUnitIsPlatform(unit))\n if (!units.length) return 'This plan builds nothing. Describe what to build again.'\n if (units.length > AI_BUILD_LIMITS.units) {\n return `This plan builds ${units.length} things, and one build holds ${AI_BUILD_LIMITS.units}. Ask for the rest in a second request.`\n }\n const pages = aiBuildPageLimit(options.freeTaste)\n if (plan.screens.length > pages) {\n return options.freeTaste\n ? `This plan builds ${plan.screens.length} pages, and a Free workspace's build makes at most ${pages}. Paid plans can build more.`\n : `This plan builds ${plan.screens.length} pages, and one build makes at most ${pages}.`\n }\n const slugs = new Set<string>()\n for (const screen of plan.screens) {\n if (!screen.sections.length) return `The page “${screen.title}” has no sections to build.`\n if (screen.sections.length > AI_SITE_MAX_SECTIONS) {\n return `The page “${screen.title}” has ${screen.sections.length} sections, and a built page holds ${AI_SITE_MAX_SECTIONS}.`\n }\n const slug = screen.slug.trim().toLowerCase()\n if (slugs.has(slug)) return `Two pages in this plan share the address ${screen.slug}.`\n slugs.add(slug)\n }\n for (const creation of plan.create) {\n if (!AI_BUILD_CREATE_KINDS.includes(creation.kind)) {\n return `A build does not create ${creation.kind === 'theme-change' ? 'theme changes' : `${creation.kind}s`} (“${creation.name}”). Take it out of create.`\n }\n }\n const graph = aiBuildGraphProblems(plan)\n if (graph.length) return graph[0]\n const ops = options.ops\n const counts = new Map<string, number>()\n for (const unit of units) counts.set(unit.op, (counts.get(unit.op) ?? 0) + 1)\n for (const item of plan.items ?? []) {\n if (AI_BUILD_STRUCTURAL_OPS.includes(item.op)) {\n return item.op === 'page'\n ? `“${item.name}” is a page: plan it in screens, not items.`\n : `“${item.name}” is ${item.op === 'email' ? 'an' : 'a'} ${item.op}: plan it in create, not items.`\n }\n if (!ops) continue\n const capability = ops.get(item.op)\n if (!capability) return `Nothing on this site can make “${item.name}” (${item.op}). Take it out of items.`\n if (options.freeTaste && !capability.freeAllowed) {\n return `A Free workspace cannot have ${aiArticle(capability.noun)} made (“${item.name}”). Take it out of items.`\n }\n const problems = pluginAiCapabilityArgsProblems(capability.argsSchema, item.args)\n if (problems.length) return `The arguments of “${item.name}” do not read: ${problems.join('; ')}.`\n }\n if (ops) {\n for (const [op, count] of counts) {\n const capability = ops.get(op)\n if (capability && count > capability.maxPerPlan) {\n return `This plan makes ${count} of “${capability.noun}”, and one build makes at most ${capability.maxPerPlan}.`\n }\n }\n }\n return null\n}\n\n/**\n * What the person must still say before this plan can be built, as the\n * questions its operations ask (`missingInput`), or `null` when nothing is\n * missing: an item the planner kept with nothing it may build from — a\n * tracking change naming no id, AGL-3751 — is asked about, never built\n * empty or from a value the planner made up. Not a plan rule: a re-ask\n * cannot supply what only the person knows, so the plan is not kept and\n * the build answers with the question.\n */\nexport function aiBuildPlanMissingInput(plan: AiBuildPlan, ops: AiBuildOps | null | undefined): string | null {\n if (!ops) return null\n const questions: string[] = []\n for (const item of plan.items ?? []) {\n const question = ops.get(item.op)?.missingInput?.({ name: item.name, why: item.why, args: item.args })\n if (question && !questions.includes(question)) questions.push(question)\n }\n return questions.length ? questions.join(' ') : null\n}\n\n/** \"a booking service\", \"an email design\". */\nexport function aiArticle(noun: string): string {\n return `${/^[aeiou]/i.test(noun) ? 'an' : 'a'} ${noun}`\n}\n\n/** The passes one unit is estimated at: a page's sections and its listing, one for a creation. */\nfunction unitPasses(unit: AiBuildUnit): number {\n if (unit.screen) return unit.screen.sections.length + 1\n return 1\n}\n\n/**\n * About what one unit costs, in credits: a page or a creation by the passes\n * it implies at the nominal credits a pass is held against, as a site's are;\n * an item by its capability's own estimate, recorded on the plan when it was\n * kept.\n */\nexport function aiBuildUnitCreditEstimate(unit: AiBuildUnit, ops?: AiBuildOps): number {\n // A store's own pages are written by code, with no model: no credits (AGL-3676).\n if (aiBuildUnitIsPlatform(unit)) return 0\n if (unit.item) {\n if (typeof unit.item.credits === 'number') return unit.item.credits\n const capability = ops?.get(unit.item.op)\n if (capability) return Math.max(0, Math.floor(capability.estimateCredits(unit.item.args)))\n return AI_SITE_PASS_CREDITS\n }\n return unitPasses(unit) * AI_SITE_PASS_CREDITS\n}\n\n/**\n * About what a build costs, in credits: every unit's estimate, or only the\n * units named in `slots` — what Try again shows. The ceiling a member\n * confirms; the meter charges what actually runs.\n */\nexport function aiBuildCreditEstimate(\n plan: AiBuildPlan,\n options: { ops?: AiBuildOps; slots?: ReadonlySet<string> } = {},\n): number {\n return aiBuildUnits(plan)\n .filter((unit) => !options.slots || options.slots.has(unit.slot))\n .reduce((total, unit) => total + aiBuildUnitCreditEstimate(unit, options.ops), 0)\n}\n\n/**\n * About what a job of this kind costs to build from its plan: a build's\n * units, every other planned kind as `aiJobPlanCreditEstimate` counts it.\n */\nexport function aiJobCreditEstimate(kind: string, plan: AiBuildPlan): number {\n return kind === 'build' ? aiBuildCreditEstimate(plan) : aiJobPlanCreditEstimate(kind, plan)\n}\n\n/**\n * What one unit is likely to cost, its p90 and its ceiling (AGL-3722): a page\n * as a page written on its own measured (a fixed cost and one per section), a creation at what its kind\n * measured, an item at the measured pass times the passes its capability\n * estimates (none for a draft another plugin writes, which asks no model).\n * The ceiling is `aiBuildUnitCreditEstimate`, unchanged.\n */\nexport function aiBuildUnitCreditRange(unit: AiBuildUnit, ops?: AiBuildOps): AiCreditRange {\n const ceiling = aiBuildUnitCreditEstimate(unit, ops)\n // A build writes each page on its own, never in a site start's warm run (AGL-3722).\n if (unit.screen) return aiStandaloneScreenCreditRange(unit.screen.sections.length)\n if (unit.creation) return aiCreditRangeOf(aiCreationMeasuredCredits(unit.creation.kind, { standalone: true }), ceiling)\n const passes = Math.ceil(ceiling / AI_SITE_PASS_CREDITS)\n return aiCreditRangeOf(\n { median: passes * AI_MEASURED_PASS_CREDITS.median, p90: passes * AI_MEASURED_PASS_CREDITS.p90 },\n ceiling,\n )\n}\n\n/**\n * What a build is likely to cost, its p90 and its ceiling (AGL-3722): every\n * unit's range, or only the units named in `slots` — what Try again runs.\n * The plan card, Try again and the Free admission all read this; the meter\n * charges what actually runs.\n */\nexport function aiBuildCreditRange(\n plan: AiBuildPlan,\n options: { ops?: AiBuildOps; slots?: ReadonlySet<string> } = {},\n): AiCreditRange {\n return aiCreditRangeOrdered(\n aiBuildUnits(plan)\n .filter((unit) => !options.slots || options.slots.has(unit.slot))\n .reduce((total, unit) => aiCreditRangeAdd(total, aiBuildUnitCreditRange(unit, options.ops)), AI_CREDIT_RANGE_ZERO),\n )\n}\n\n/** `aiJobCreditEstimate` as a range (AGL-3722). */\nexport function aiJobCreditRange(kind: string, plan: AiBuildPlan): AiCreditRange {\n return kind === 'build' ? aiBuildCreditRange(plan) : aiJobPlanCreditRange(kind, plan)\n}\n\n/**\n * A smaller first build (AGL-3722): the plan's home page — its first page\n * where it has no home — and only what that page needs, transitively: the\n * layout it is drawn in, the form and anything else its sections place.\n * Every other page, and what only they needed, waits for a later request.\n * `null` when the plan has no page, or when the smaller plan is the whole one.\n */\nexport function aiBuildFirstPagePlan<T extends AiBuildPlan>(plan: T): T | null {\n if (!plan.screens.length) return null\n const index = Math.max(0, plan.screens.findIndex(aiSitePlanIsHome))\n const units = aiBuildUnits(plan).filter((unit) => !aiBuildUnitIsPlatform(unit))\n const bySlot = new Map(units.map((unit) => [unit.slot, unit]))\n const keep = new Set<string>()\n const queue = [`p${index}`]\n while (queue.length) {\n const slot = queue.shift() as string\n if (keep.has(slot)) continue\n keep.add(slot)\n for (const dep of bySlot.get(slot)?.deps ?? []) queue.push(dep)\n }\n if (keep.size === units.length) return null\n const screen = plan.screens[index]\n const create = plan.create.filter((creation, at) => !AI_BUILD_CREATE_KINDS.includes(creation.kind) || keep.has(`c${at}`))\n const items = (plan.items ?? []).filter((item) => keep.has(item.slot))\n const kept = new Set([screen.slug, ...create.map((entry) => `${AI_PLAN_NEW_REF_PREFIX}${entry.name}`)])\n const smaller: T = {\n ...plan,\n create,\n screens: [screen],\n ...(plan.items ? { items } : {}),\n ...(plan.embeds ? { embeds: plan.embeds.filter((embed) => kept.has(embed.where)) } : {}),\n }\n // The store's own pages stay only while the smaller build still makes a store (AGL-3676).\n if (smaller.storePages && !aiBuildMakesStore(smaller)) delete smaller.storePages\n return smaller\n}\n\n/** The smaller first build a build that does not fit is offered (AGL-3722), with its range; `null` when there is none. */\nexport function aiBuildSmaller(plan: AiBuildPlan, ops?: AiBuildOps): AiCreditsSmaller | null {\n const smaller = aiBuildFirstPagePlan(plan)\n if (!smaller) return null\n const screen = smaller.screens[0]\n const label = aiSitePlanIsHome(screen) ? AI_SITE_HOME_FIRST_LABEL : `Build the ${screen.title} page first`\n return { label, ...aiBuildCreditRange(smaller, { ops }) }\n}\n\n/** A fresh ledger: one pending row per unit, first attempt. */\nexport function aiBuildInitialLedger(units: readonly AiBuildUnit[]): AiJobItemLedger[] {\n return units.map((unit) => ({\n slot: unit.slot,\n op: unit.op,\n label: unit.label,\n status: 'pending',\n attempt: 1,\n creditsSpent: 0,\n attemptCredits: 0,\n creditsRefunded: 0,\n failure: null,\n outputs: [],\n }))\n}\n\nconst OPEN: readonly AiJobItemStatus[] = ['pending', 'running']\n\n/** Whether an item is still to be built. */\nexport function aiBuildItemOpen(row: Pick<AiJobItemLedger, 'status'>): boolean {\n return OPEN.includes(row.status)\n}\n\n/** Whether an item delivered: built as planned, or built without something that failed. */\nexport function aiBuildItemDelivered(row: Pick<AiJobItemLedger, 'status'>): boolean {\n return row.status === 'succeeded' || row.status === 'degraded'\n}\n\n/**\n * The next unit to build: the first in build order whose row is still open.\n * Its dependencies come before it, so by then each is settled one way or the\n * other. `null` when nothing is left.\n */\nexport function aiBuildNextUnit(\n ordered: readonly AiBuildUnit[],\n ledger: readonly AiJobItemLedger[],\n): AiBuildUnit | null {\n const rows = new Map(ledger.map((row) => [row.slot, row]))\n return ordered.find((unit) => {\n const row = rows.get(unit.slot)\n return !row || aiBuildItemOpen(row)\n }) ?? null\n}\n\n/** How a unit is built given what its dependencies came to. */\nexport interface AiBuildDegradation {\n /** The unit is not built at all, with the sentence why; nothing is spent. */\n skip: string | null\n /** The failed dependencies that change how it is built. */\n degradedBy: string[]\n /** What the person reads about the change; one per failed dependency. */\n notes: string[]\n /** `new:<name>` references (lowercased names) to leave out. */\n dropped: Set<string>\n /** Brief lines for the unit's own job: what to leave out, and what to place. */\n briefLines: string[]\n}\n\n/**\n * How a unit is built when some of what it depends on failed (AGL-3616).\n *\n * A PAGE is always built: a failed layout falls back to the site's own, a\n * failed form or component is left out of its section, and a failed item a\n * section places (a booking service) takes its block out of the page — each\n * with a note. Any OTHER unit whose dependency failed is skipped when that\n * dependency's capability says `omit` (a campaign whose email design failed\n * has nothing to send), and built without it when it says `fallback`.\n */\nexport function aiBuildDegradation(\n unit: AiBuildUnit,\n context: {\n units: readonly AiBuildUnit[]\n ledger: readonly AiJobItemLedger[]\n ops?: AiBuildOps\n },\n): AiBuildDegradation {\n const rows = new Map(context.ledger.map((row) => [row.slot, row]))\n const bySlot = new Map(context.units.map((one) => [one.slot, one]))\n const result: AiBuildDegradation = { skip: null, degradedBy: [], notes: [], dropped: new Set(), briefLines: [] }\n for (const slot of unit.deps) {\n const dep = bySlot.get(slot)\n const row = rows.get(slot)\n if (!dep || !row || aiBuildItemDelivered(row)) continue\n const noun = dep.creation\n ? aiBuildCreationNoun(dep.creation.kind)\n : (context.ops?.get(dep.op)?.noun ?? dep.op)\n const capability = dep.item ? context.ops?.get(dep.op) : undefined\n const degrade = dep.item?.degrade ?? capability?.degrade ?? (dep.creation?.kind === 'layout' ? 'fallback' : 'omit')\n // A form whose dataset could not be made is built without it (AGL-3616):\n // its submissions reach the Inbox, as any form's do.\n if (aiBuildUnitWritesTo(unit) === dep.label.toLowerCase()) {\n result.degradedBy.push(slot)\n result.notes.push(`Its submissions arrive in the Inbox only: the dataset “${dep.label}” could not be created.`)\n continue\n }\n if (!unit.screen && degrade === 'omit') {\n result.skip = `Not built: the ${noun} “${dep.label}” it needs could not be created.`\n result.degradedBy.push(slot)\n return result\n }\n result.degradedBy.push(slot)\n result.dropped.add(dep.label.toLowerCase())\n if (dep.creation?.kind === 'layout') {\n result.notes.push(`Built inside the site’s own layout: the layout “${dep.label}” could not be created.`)\n continue\n }\n if (unit.screen) {\n const section = unit.screen.sections.find((one) =>\n one.uses.some((ref) => isAiPlanNewRef(ref) && aiBuildRefName(ref) === dep.label.toLowerCase()),\n )\n // Another item this section places with the same block was built (one\n // of several events, AGL-3743): the block stays, and only this item is\n // missing from what it shows.\n const blockStays = Boolean(\n section &&\n capability?.pageBlocks?.length &&\n aiBuildSectionDeliveredBlocks(section, { ...context, rows, except: slot }).has(aiBuildBlocksKey(capability.pageBlocks)),\n )\n if (blockStays) {\n result.notes.push(`Built without the ${noun} “${dep.label}”: it could not be created.`)\n result.briefLines.push(`Leave the ${noun} “${dep.label}” out of the “${section?.name}” section: it could not be created.`)\n continue\n }\n const blocks = capability?.pageBlocks?.length ? ` the ${capability.pageBlocks.join(' or ')} block` : ''\n result.notes.push(\n `Built without${blocks || ` the ${noun}`}: the ${noun} “${dep.label}” could not be created.`,\n )\n result.briefLines.push(\n `${section ? `Build the “${section.name}” section` : 'Build the page'} without the ${noun} “${dep.label}”${blocks ? ` and without${blocks}` : ''}: it could not be created.`,\n )\n } else {\n result.notes.push(`Built without the ${noun} “${dep.label}”: it could not be created.`)\n }\n }\n return result\n}\n\n/** The dataset a form unit writes to, by its `new:` name lowercased; `null` for any other unit (AGL-3616). */\nexport function aiBuildUnitWritesTo(unit: Pick<AiBuildUnit, 'creation'>): string | null {\n const ref = unit.creation?.kind === 'form' ? unit.creation.writesTo : null\n return isAiPlanNewRef(ref) ? aiBuildRefName(ref) : null\n}\n\n/** What each creation is called in a note. */\nexport function aiBuildCreationNoun(kind: AiBuildPlanCreateKind): string {\n return kind === 'email' ? 'email design' : kind === 'theme-change' ? 'theme change' : kind\n}\n\n/**\n * The brief lines a page is told about the items its sections place and\n * that were built: the block to put there, in the owner's words.\n */\nexport function aiBuildPlacedItemLines(\n unit: AiBuildUnit,\n context: {\n units: readonly AiBuildUnit[]\n ledger: readonly AiJobItemLedger[]\n ops?: AiBuildOps\n /** Operations whose items the platform places itself (a listing), so the page is told nothing of them. */\n placedByCode?: readonly string[]\n },\n): string[] {\n if (!unit.screen) return []\n const rows = new Map(context.ledger.map((row) => [row.slot, row]))\n const lines: string[] = []\n for (const section of unit.screen.sections) {\n // One line per block a section places, naming every built item it shows:\n // a section listing four events places the Event List once (AGL-3743).\n const placed = new Map<string, { blocks: readonly string[]; noun: string; labels: string[] }>()\n for (const { dep, capability } of aiBuildSectionItems(section, context.units, context.ops)) {\n const row = rows.get(dep.slot)\n if (!row || !aiBuildItemDelivered(row)) continue\n if (context.placedByCode?.includes(dep.op)) continue\n const blocks = capability?.pageBlocks ?? []\n if (!blocks.length) continue\n const key = aiBuildBlocksKey(blocks)\n const entry = placed.get(key) ?? { blocks, noun: capability?.noun ?? dep.op, labels: [] }\n entry.labels.push(`“${dep.label}”`)\n placed.set(key, entry)\n }\n for (const { blocks, noun, labels } of placed.values()) {\n const named =\n labels.length === 1\n ? `the ${noun} ${labels[0]}`\n : `the ${noun}s ${labels.slice(0, -1).join(', ')} and ${labels[labels.length - 1]}`\n lines.push(`In the “${section.name}” section, place the ${blocks.join(' or ')} block for ${named}.`)\n }\n }\n return lines\n}\n\n/** The items a page section places, each with its capability, in the order its uses name them. */\nfunction aiBuildSectionItems(\n section: { uses: readonly string[] },\n units: readonly AiBuildUnit[],\n ops: AiBuildOps | undefined,\n): Array<{ dep: AiBuildUnit; capability: PluginAiCapability | undefined }> {\n const found: Array<{ dep: AiBuildUnit; capability: PluginAiCapability | undefined }> = []\n for (const ref of section.uses) {\n if (!isAiPlanNewRef(ref)) continue\n const dep = units.find((one) => one.item && one.item.name.toLowerCase() === aiBuildRefName(ref))\n if (dep?.item) found.push({ dep, capability: ops?.get(dep.op) })\n }\n return found\n}\n\n/** The blocks a section's built items place, each set as one key; `except` leaves one item out. */\nfunction aiBuildSectionDeliveredBlocks(\n section: { uses: readonly string[] },\n context: { units: readonly AiBuildUnit[]; rows: ReadonlyMap<string, AiJobItemLedger>; ops?: AiBuildOps; except: string },\n): Set<string> {\n const keys = new Set<string>()\n for (const { dep, capability } of aiBuildSectionItems(section, context.units, context.ops)) {\n if (dep.slot === context.except || !capability?.pageBlocks?.length) continue\n const row = context.rows.get(dep.slot)\n if (row && aiBuildItemDelivered(row)) keys.add(aiBuildBlocksKey(capability.pageBlocks))\n }\n return keys\n}\n\nfunction aiBuildBlocksKey(blocks: readonly string[]): string {\n return [...blocks].sort().join('|')\n}\n\n/** What a build came to: whether anything was delivered, and whether anything is left. */\nexport function aiBuildSettlement(ledger: readonly AiJobItemLedger[]): {\n delivered: boolean\n open: boolean\n failed: number\n} {\n return {\n delivered: ledger.some(aiBuildItemDelivered),\n open: ledger.some(aiBuildItemOpen),\n failed: ledger.filter((row) => row.status === 'failed').length,\n }\n}\n\n/**\n * The ledger Try again runs (AGL-3616): every failed item back to `pending`\n * on its next attempt, with the items left unbuilt because of it — skipped,\n * or degraded with no draft — and every item the build never reached. An\n * item that succeeded is never run again, and a degraded page that has its\n * draft keeps it, with a note that the page needs an edit. `retried` names\n * the slots that will run, which is what the estimate is shown for.\n */\nexport function aiBuildRetryLedger(\n ledger: readonly AiJobItemLedger[],\n units: readonly AiBuildUnit[],\n): { ledger: AiJobItemLedger[]; retried: string[] } {\n const failed = new Set(ledger.filter((row) => row.status === 'failed').map((row) => row.slot))\n const dependents = new Map<string, string[]>()\n for (const unit of units) {\n for (const dep of unit.deps) dependents.set(dep, [...(dependents.get(dep) ?? []), unit.slot])\n }\n // Everything downstream of a failed item, transitively.\n const downstream = new Set<string>()\n const queue = [...failed]\n while (queue.length) {\n const slot = queue.shift() as string\n for (const next of dependents.get(slot) ?? []) {\n if (downstream.has(next)) continue\n downstream.add(next)\n queue.push(next)\n }\n }\n const retried: string[] = []\n const next = ledger.map((row): AiJobItemLedger => {\n const again =\n row.status === 'failed' ||\n (row.status === 'skipped' && (downstream.has(row.slot) || !(row.degradedBy ?? []).length)) ||\n (row.status === 'degraded' && downstream.has(row.slot) && !row.outputs.length)\n if (again) {\n retried.push(row.slot)\n return {\n ...row,\n status: 'pending',\n attempt: row.attempt + 1,\n attemptCredits: 0,\n failure: null,\n note: null,\n degradedBy: [],\n settledAt: null,\n }\n }\n if (row.status === 'degraded' && downstream.has(row.slot) && row.outputs.length) {\n return {\n ...row,\n note: `${row.note ? `${row.note} ` : ''}It keeps its draft: once the rest is built, edit this page to add what it is missing.`,\n }\n }\n return row\n })\n return { ledger: next, retried }\n}\n\n/**\n * Units read back off a ledger alone (AGL-3616), for a job whose units are\n * not a build plan's — a site scaffold's: each row as its unit, and every\n * page built after the layouts and forms the ledger holds.\n */\nexport function aiLedgerUnits(ledger: readonly AiJobItemLedger[]): AiBuildUnit[] {\n const creations = ledger.filter((row) => row.op === 'layout' || row.op === 'form').map((row) => row.slot)\n return ledger.map((row) => ({\n slot: row.slot,\n op: row.op,\n label: row.label,\n deps: row.op === 'page' ? creations : [],\n }))\n}\n\n/**\n * What the job drawer says under an item another plugin's writer made: a\n * draft, or, for setup its writer saves live (`live`, a CRM pipeline or\n * field, AGL-3746), that it was saved. A writer that went live only when the\n * member may (an event the publishing role publishes, AGL-3755) reports\n * `live: false` for one it kept as a draft, with its `notice` saying why.\n */\nexport function aiBuildItemOutputNote(\n capability: Pick<PluginAiCapability, 'where' | 'live'>,\n written?: Pick<PluginDraftRecord, 'live' | 'notice'>,\n): string {\n const live = written?.live ?? capability.live\n const said = live ? `Live now, in ${capability.where}.` : `A draft, in ${capability.where}.`\n const notice = written?.notice?.trim()\n return notice ? `${said} ${notice}` : said\n}\n"],"names":["pluginAiCapabilityArgsProblems","AI_PLAN_NEW_REF_PREFIX","isAiPlanNewRef","AI_BUILD_STORE_OP","AI_BUILD_STORE_PAGES_LABEL","AI_BUILD_STORE_SLOT","aiBuildMakesStore","aiBuildStorePagesAdded","AI_SITE_HOME_FIRST_LABEL","AI_SITE_MAX_SECTIONS","AI_SITE_PASS_CREDITS","aiCreationMeasuredCredits","aiJobPlanCreditEstimate","aiJobPlanCreditRange","aiSitePlanIsHome","aiStandaloneScreenCreditRange","AI_CREDIT_RANGE_ZERO","AI_MEASURED_PASS_CREDITS","aiCreditRangeAdd","aiCreditRangeOf","aiCreditRangeOrdered","AI_BUILD_LIMITS","units","pages","freePages","aiBuildFreePageCapNote","plan","freeTaste","cap","screens","length","AI_BUILD_CREATE_KINDS","AI_BUILD_STRUCTURAL_OPS","AI_BUILD_MADE_INPUT","AI_BUILD_PUBLISH_INPUT","creationOp","creation","kind","namedSlots","slots","Map","create","forEach","index","includes","set","name","toLowerCase","item","items","slot","aiBuildRefName","ref","slice","trim","aiBuildItemArgRefs","args","refs","take","value","part","split","push","Object","values","Array","isArray","aiBuildScreenRefs","screen","layout","template","duplicateOf","sections","flatMap","section","uses","filter","aiBuildUnits","pageSlots","title","has","depsOf","self","deps","get","undefined","op","label","writesTo","dependsOn","aiBuildUnitIsPlatform","unit","aiBuildOrder","ordered","placed","Set","known","map","next","find","every","dep","add","aiBuildGraphProblems","problems","aiBuildPageLimit","aiBuildPlanShapeRefusal","options","counts","slugs","slug","graph","ops","capability","freeAllowed","aiArticle","noun","argsSchema","join","count","maxPerPlan","aiBuildPlanMissingInput","questions","question","missingInput","why","test","unitPasses","aiBuildUnitCreditEstimate","credits","Math","max","floor","estimateCredits","aiBuildCreditEstimate","reduce","total","aiJobCreditEstimate","aiBuildUnitCreditRange","ceiling","standalone","passes","ceil","median","p90","aiBuildCreditRange","aiJobCreditRange","aiBuildFirstPagePlan","findIndex","bySlot","keep","queue","shift","size","at","kept","entry","smaller","embeds","embed","where","storePages","aiBuildSmaller","aiBuildInitialLedger","status","attempt","creditsSpent","attemptCredits","creditsRefunded","failure","outputs","OPEN","aiBuildItemOpen","row","aiBuildItemDelivered","aiBuildNextUnit","ledger","rows","aiBuildDegradation","context","one","result","skip","degradedBy","notes","dropped","briefLines","aiBuildCreationNoun","degrade","aiBuildUnitWritesTo","some","blockStays","Boolean","pageBlocks","aiBuildSectionDeliveredBlocks","except","aiBuildBlocksKey","blocks","aiBuildPlacedItemLines","lines","aiBuildSectionItems","placedByCode","key","labels","named","found","keys","sort","aiBuildSettlement","delivered","open","failed","aiBuildRetryLedger","dependents","downstream","retried","again","note","settledAt","aiLedgerUnits","creations","aiBuildItemOutputNote","written","live","said","notice"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,8BAA8B,QAEzB,qDAAoD;AAE3D,SACEC,sBAAsB,EACtBC,cAAc,QAMT,qBAAiB;AAExB,SACEC,iBAAiB,EACjBC,0BAA0B,EAC1BC,mBAAmB,EACnBC,iBAAiB,EACjBC,sBAAsB,QACjB,4BAAwB;AAC/B,SACEC,wBAAwB,EACxBC,oBAAoB,EACpBC,oBAAoB,EACpBC,yBAAyB,EACzBC,uBAAuB,EACvBC,oBAAoB,EACpBC,gBAAgB,EAChBC,6BAA6B,QACxB,mBAAe;AACtB,SACEC,oBAAoB,EACpBC,wBAAwB,EACxBC,gBAAgB,EAChBC,eAAe,EACfC,oBAAoB,QAGf,0BAAsB;AAE7B;;;;;;;;;;;;;;;;;CAiBC,GAED,sFAAsF,GACtF,OAAO,MAAMC,kBAAkB;IAC7B,yCAAyC,GACzCC,OAAO;IACPC,OAAO;IACP,8BAA8B,GAC9BC,WAAW;AACb,EAAU;AAEV;;;;;;CAMC,GACD,OAAO,SAASC,uBAAuBC,IAAkC,EAAEC,SAAkB;IAC3F,MAAMC,MAAMP,gBAAgBG,SAAS;IACrC,IAAI,CAACG,aAAaD,KAAKG,OAAO,CAACC,MAAM,GAAGF,KAAK,OAAO;IACpD,OAAO,CAAC,qCAAqC,EAAEA,IAAI,yFAAyF,CAAC;AAC/I;AAEA,6FAA6F,GAC7F,OAAO,MAAMG,wBAA0D;IAAC;IAAU;IAAQ;IAAa;CAAQ,CAAA;AAE/G;;;CAGC,GACD,OAAO,MAAMC,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AC,CAAC,CAAC,GAAG,CAAC,YAAY,EAAE/C,WAAW+C,KAAK,CAAC,CAAC,CAAC;IAC5F,MAAMiE,SAASH,4BAAAA,kBAAAA,QAASG,MAAM,qBAAfH,gBAAiBxK,IAAI;IACpC,OAAO2K,SAAS,GAAGD,KAAK,CAAC,EAAEC,QAAQ,GAAGD;AACxC"}
@@ -21,9 +21,10 @@ import type { AiBuildStorePages } from './ai-build-store-pages';
21
21
  * (`jobs/ai-job-plan-step.ts`) returns, before a single node is generated.
22
22
  *
23
23
  * This module is the plan's MODEL — its shape, its tool schema and its
24
- * reader — and imports nothing at runtime, so the doctrine validators, the
25
- * plan step, the job document and the proposal can all read it without
26
- * importing each other.
24
+ * reader — and imports nothing of the plugin's at runtime (its one runtime
25
+ * import is core's `seo-locale`, which imports nothing), so the doctrine
26
+ * validators, the plan step, the job document and the proposal can all read
27
+ * it without importing each other.
27
28
  *
28
29
  * A plan is REFERENCES, never documents (AGL-2937). It names what the site
29
30
  * already has by inventory id, what the job will create by a short name, and
@@ -217,11 +218,21 @@ export interface AiBuildPlan {
217
218
  storePages?: AiBuildStorePages;
218
219
  /**
219
220
  * The language a SITE plan's brief and copy are written in (AGL-3750), as
220
- * the Languages card stores a code (`aiPlanLanguage`). Absent is the site's
221
+ * the Languages card stores a code (`siteLanguageCode`). Absent is the site's
221
222
  * own language: every other kind's plan, a plan that said null, and one
222
223
  * whose code was not a language code, which is dropped rather than refused.
223
224
  */
224
225
  language?: string;
226
+ /**
227
+ * What a SITE plan's photos show, in English whatever language the brief
228
+ * is in (AGL-3760): two to four words a stock photo library is searched by,
229
+ * the business's subject first — "bakery bread pastries" for "una panadería
230
+ * … con pan dulce, conchas". The libraries are tagged in English, so a site
231
+ * in another language searches by these rather than its own words. Absent
232
+ * on every other kind's plan, on one that said null, and on one whose words
233
+ * were not plain English letters.
234
+ */
235
+ photoWords?: string;
225
236
  }
226
237
  /**
227
238
  * How much one plan may hold. A job builds what one proposal can describe
@@ -287,19 +298,19 @@ export declare const AI_BUILD_PLAN_EMBEDS_RECORDS_TOOL: AiTool;
287
298
  * whichever plugins registered operations, and the prompt cache keeps it.
288
299
  */
289
300
  export declare function withBuildItems(tool: AiTool): AiTool;
290
- /** The Languages card's own pattern for one language code (`LOCALE_PATTERN`). */
291
- export declare const AI_PLAN_LANGUAGE_PATTERN: RegExp;
301
+ /** The most words a plan's photo words keep. */
302
+ export declare const AI_PLAN_PHOTO_WORDS_MAX = 4;
292
303
  /**
293
- * A plan's language as the Languages card would store it (AGL-3750), or
294
- * `null`: a two-letter language, optionally with a region or a script, in
295
- * BCP 47 casing — `es`, `pt-BR`, `zh-Hant`; `_` reads as `-`. Anything the
296
- * card would not accept is no language at all, so a plan carrying one is
297
- * kept without it.
304
+ * A plan's photo words as a stock photo search takes them (AGL-3760), or
305
+ * `null`: lowercase English words, at most {@link AI_PLAN_PHOTO_WORDS_MAX}.
306
+ * Words with letters outside English's — "panadería" — are no English at all,
307
+ * so the plan is kept without them.
298
308
  */
299
- export declare function aiPlanLanguage(value: unknown): string | null;
309
+ export declare function aiPlanPhotoWords(value: unknown): string | null;
300
310
  /**
301
- * Any plan tool with the site's language (AGL-3750), offered only to a
302
- * `site` job, whose guided start sets the site's language from it. One
311
+ * Any plan tool with the site's language (AGL-3750) and its photo words in
312
+ * English (AGL-3760), offered only to a `site` job, whose guided start sets
313
+ * the site's language from one and searches its photos by the other. One
303
314
  * schema for every site plan, so the tool is the same bytes across briefs
304
315
  * and the prompt cache keeps it; every other kind's tool is unchanged.
305
316
  */
@@ -1,3 +1,4 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
1
2
  /**
2
3
  * @license
3
4
  * Copyright 2026 Aglyn LLC
@@ -13,15 +14,16 @@
13
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
15
  * See the License for the specific language governing permissions and
15
16
  * limitations under the License.
16
- */ import { _ as _extends } from "@swc/helpers/_/_extends";
17
+ */ import { siteLanguageCode } from "@aglyn/aglyn/app-utils/seo-locale";
17
18
  /**
18
19
  * The plan a generation job builds from (AGL-2935): what the job's plan step
19
20
  * (`jobs/ai-job-plan-step.ts`) returns, before a single node is generated.
20
21
  *
21
22
  * This module is the plan's MODEL — its shape, its tool schema and its
22
- * reader — and imports nothing at runtime, so the doctrine validators, the
23
- * plan step, the job document and the proposal can all read it without
24
- * importing each other.
23
+ * reader — and imports nothing of the plugin's at runtime (its one runtime
24
+ * import is core's `seo-locale`, which imports nothing), so the doctrine
25
+ * validators, the plan step, the job document and the proposal can all read
26
+ * it without importing each other.
25
27
  *
26
28
  * A plan is REFERENCES, never documents (AGL-2937). It names what the site
27
29
  * already has by inventory id, what the job will create by a short name, and
@@ -435,26 +437,25 @@ const ITEMS_SCHEMA = {
435
437
  })
436
438
  });
437
439
  }
438
- /** The Languages card's own pattern for one language code (`LOCALE_PATTERN`). */ export const AI_PLAN_LANGUAGE_PATTERN = /^[a-z]{2}(-[A-Za-z]{2,4})?$/;
440
+ const LANGUAGE_SCHEMA = nullableString("The language the brief is written in, which the site's copy is written in too: a code such as en, es, fr or pt-BR. Null when unsure.");
441
+ /** The most words a plan's photo words keep. */ export const AI_PLAN_PHOTO_WORDS_MAX = 4;
439
442
  /**
440
- * A plan's language as the Languages card would store it (AGL-3750), or
441
- * `null`: a two-letter language, optionally with a region or a script, in
442
- * BCP 47 casing — `es`, `pt-BR`, `zh-Hant`; `_` reads as `-`. Anything the
443
- * card would not accept is no language at all, so a plan carrying one is
444
- * kept without it.
445
- */ export function aiPlanLanguage(value) {
443
+ * A plan's photo words as a stock photo search takes them (AGL-3760), or
444
+ * `null`: lowercase English words, at most {@link AI_PLAN_PHOTO_WORDS_MAX}.
445
+ * Words with letters outside English's — "panadería" — are no English at all,
446
+ * so the plan is kept without them.
447
+ */ export function aiPlanPhotoWords(value) {
446
448
  if (typeof value !== 'string') return null;
447
- const match = /^([A-Za-z]{2})(?:-([A-Za-z]{2}|[A-Za-z]{4}))?$/.exec(value.trim().replace(/_/g, '-'));
448
- if (!match) return null;
449
- const [, language, sub] = match;
450
- const lower = language.toLowerCase();
451
- const tag = !sub ? lower : sub.length === 2 ? `${lower}-${sub.toUpperCase()}` : `${lower}-${sub[0].toUpperCase()}${sub.slice(1).toLowerCase()}`;
452
- return AI_PLAN_LANGUAGE_PATTERN.test(tag) ? tag : null;
449
+ const text = value.trim().toLowerCase();
450
+ if (!text || !/^[a-z][a-z\s,'&-]*$/.test(text)) return null;
451
+ const words = text.split(/[\s,&]+/).map((word)=>word.replace(/^[-']+|[-']+$/g, '')).filter((word)=>word.length > 1);
452
+ return words.length ? words.slice(0, AI_PLAN_PHOTO_WORDS_MAX).join(' ') : null;
453
453
  }
454
- const LANGUAGE_SCHEMA = nullableString("The language the brief is written in, which the site's copy is written in too: a code such as en, es, fr or pt-BR. Null when unsure.");
454
+ const PHOTO_WORDS_SCHEMA = nullableString("For a brief not in English: 2-4 English words for its stock photos, subject first, e.g. bakery bread pastries; no place. Else null.");
455
455
  /**
456
- * Any plan tool with the site's language (AGL-3750), offered only to a
457
- * `site` job, whose guided start sets the site's language from it. One
456
+ * Any plan tool with the site's language (AGL-3750) and its photo words in
457
+ * English (AGL-3760), offered only to a `site` job, whose guided start sets
458
+ * the site's language from one and searches its photos by the other. One
458
459
  * schema for every site plan, so the tool is the same bytes across briefs
459
460
  * and the prompt cache keeps it; every other kind's tool is unchanged.
460
461
  */ export function withPlanLanguage(tool) {
@@ -462,10 +463,12 @@ const LANGUAGE_SCHEMA = nullableString("The language the brief is written in, wh
462
463
  inputSchema: _extends({}, tool.inputSchema, {
463
464
  required: [
464
465
  ...tool.inputSchema['required'],
465
- 'language'
466
+ 'language',
467
+ 'photoWords'
466
468
  ],
467
469
  properties: _extends({}, tool.inputSchema['properties'], {
468
- language: LANGUAGE_SCHEMA
470
+ language: LANGUAGE_SCHEMA,
471
+ photoWords: PHOTO_WORDS_SCHEMA
469
472
  })
470
473
  })
471
474
  });
@@ -701,10 +704,15 @@ export function parseAiBuildPlan(input) {
701
704
  });
702
705
  // A language that is no code is dropped, never refused (AGL-3750): the
703
706
  // site keeps the language it has.
704
- const language = aiPlanLanguage(root['language']);
707
+ const language = siteLanguageCode(root['language']);
705
708
  if (typeof root['language'] === 'string' && root['language'].trim() && !language) {
706
709
  repairs.push(`language "${root['language'].trim().slice(0, 40)}" is not a language code; ignored`);
707
710
  }
711
+ // Photo words that are not plain English are dropped, never refused (AGL-3760).
712
+ const photoWords = aiPlanPhotoWords(root['photoWords']);
713
+ if (typeof root['photoWords'] === 'string' && root['photoWords'].trim() && !photoWords) {
714
+ repairs.push(`photoWords "${root['photoWords'].trim().slice(0, 40)}" is not plain English; ignored`);
715
+ }
708
716
  // A plan whose brief asks for no player carries no list, as it did before the list existed;
709
717
  // so does a plan with no items.
710
718
  return {
@@ -719,6 +727,8 @@ export function parseAiBuildPlan(input) {
719
727
  items
720
728
  } : {}, language ? {
721
729
  language
730
+ } : {}, photoWords ? {
731
+ photoWords
722
732
  } : {}),
723
733
  repairs
724
734
  };