@aglyn/plugins-ai 1.0.0-beta.238 → 1.0.0-beta.240

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/package.json +17 -17
  2. package/src/lib/components/ai-job-links.js +8 -0
  3. package/src/lib/components/ai-job-links.js.map +1 -1
  4. package/src/lib/components/ai-job-requests.d.ts +5 -0
  5. package/src/lib/components/ai-job-requests.js +4 -2
  6. package/src/lib/components/ai-job-requests.js.map +1 -1
  7. package/src/lib/components/ai-jobs-store.d.ts +12 -0
  8. package/src/lib/components/ai-jobs-store.js +15 -0
  9. package/src/lib/components/ai-jobs-store.js.map +1 -1
  10. package/src/lib/components/ai-usage-meter-refresh.d.ts +35 -0
  11. package/src/lib/components/ai-usage-meter-refresh.js +63 -0
  12. package/src/lib/components/ai-usage-meter-refresh.js.map +1 -0
  13. package/src/lib/components/assist-panel.component.js +17 -1
  14. package/src/lib/components/assist-panel.component.js.map +1 -1
  15. package/src/lib/components/use-ai-usage-meter.d.ts +2 -0
  16. package/src/lib/components/use-ai-usage-meter.js +8 -3
  17. package/src/lib/components/use-ai-usage-meter.js.map +1 -1
  18. package/src/lib/jobs/ai-build-unit-outcome.d.ts +3 -1
  19. package/src/lib/jobs/ai-build-unit-outcome.js +19 -3
  20. package/src/lib/jobs/ai-build-unit-outcome.js.map +1 -1
  21. package/src/lib/jobs/ai-job-build-step.js +29 -2
  22. package/src/lib/jobs/ai-job-build-step.js.map +1 -1
  23. package/src/lib/jobs/ai-job-draft-ids.js +7 -2
  24. package/src/lib/jobs/ai-job-draft-ids.js.map +1 -1
  25. package/src/lib/jobs/ai-job-form-dataset.d.ts +100 -0
  26. package/src/lib/jobs/ai-job-form-dataset.js +161 -0
  27. package/src/lib/jobs/ai-job-form-dataset.js.map +1 -0
  28. package/src/lib/jobs/ai-job-form-step.d.ts +15 -3
  29. package/src/lib/jobs/ai-job-form-step.js +37 -9
  30. package/src/lib/jobs/ai-job-form-step.js.map +1 -1
  31. package/src/lib/jobs/ai-job-layout-language.js +7 -2
  32. package/src/lib/jobs/ai-job-layout-language.js.map +1 -1
  33. package/src/lib/jobs/ai-job-page-language.d.ts +9 -0
  34. package/src/lib/jobs/ai-job-page-language.js +44 -4
  35. package/src/lib/jobs/ai-job-page-language.js.map +1 -1
  36. package/src/lib/jobs/ai-job-page-sections.js +13 -2
  37. package/src/lib/jobs/ai-job-page-sections.js.map +1 -1
  38. package/src/lib/jobs/ai-job-page-step.js +32 -2
  39. package/src/lib/jobs/ai-job-page-step.js.map +1 -1
  40. package/src/lib/jobs/ai-job-plan-step.d.ts +18 -0
  41. package/src/lib/jobs/ai-job-plan-step.js +41 -4
  42. package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
  43. package/src/lib/jobs/ai-job-site-datasets.d.ts +183 -0
  44. package/src/lib/jobs/ai-job-site-datasets.js +530 -0
  45. package/src/lib/jobs/ai-job-site-datasets.js.map +1 -0
  46. package/src/lib/jobs/ai-job-site-step.d.ts +15 -8
  47. package/src/lib/jobs/ai-job-site-step.js +148 -29
  48. package/src/lib/jobs/ai-job-site-step.js.map +1 -1
  49. package/src/lib/jobs/fixtures/ai-dataset-site-plan-recordings.d.ts +30 -0
  50. package/src/lib/jobs/fixtures/ai-dataset-site-plan-recordings.js +637 -0
  51. package/src/lib/jobs/fixtures/ai-dataset-site-plan-recordings.js.map +1 -0
  52. package/src/lib/layout-language/ai-layout-compiler.d.ts +10 -0
  53. package/src/lib/layout-language/ai-layout-compiler.js +93 -1
  54. package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
  55. package/src/lib/layout-language/ai-layout-gaps.js +17 -1
  56. package/src/lib/layout-language/ai-layout-gaps.js.map +1 -1
  57. package/src/lib/layout-language/ai-layout-listings.d.ts +32 -3
  58. package/src/lib/layout-language/ai-layout-listings.js +62 -9
  59. package/src/lib/layout-language/ai-layout-listings.js.map +1 -1
  60. package/src/lib/layout-language/ai-layout-pictures.js +12 -4
  61. package/src/lib/layout-language/ai-layout-pictures.js.map +1 -1
  62. package/src/lib/model/ai-build-job.d.ts +2 -0
  63. package/src/lib/model/ai-build-job.js +16 -1
  64. package/src/lib/model/ai-build-job.js.map +1 -1
  65. package/src/lib/model/ai-build-plan.d.ts +23 -3
  66. package/src/lib/model/ai-build-plan.js +47 -6
  67. package/src/lib/model/ai-build-plan.js.map +1 -1
  68. package/src/lib/model/ai-plan-capabilities.d.ts +7 -0
  69. package/src/lib/model/ai-plan-capabilities.js.map +1 -1
  70. package/src/lib/model/ai-site-job.d.ts +19 -2
  71. package/src/lib/model/ai-site-job.js +21 -6
  72. package/src/lib/model/ai-site-job.js.map +1 -1
  73. package/src/lib/runtime/ai-dataset-generation.d.ts +77 -0
  74. package/src/lib/runtime/ai-dataset-generation.js +127 -0
  75. package/src/lib/runtime/ai-dataset-generation.js.map +1 -0
  76. package/src/lib/runtime/ai-doctrine-validators.d.ts +84 -0
  77. package/src/lib/runtime/ai-doctrine-validators.js +307 -1
  78. package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
  79. package/src/lib/runtime/ai-doctrine.js +10 -4
  80. package/src/lib/runtime/ai-doctrine.js.map +1 -1
  81. package/src/lib/runtime/ai-node-tree.d.ts +2 -0
  82. package/src/lib/runtime/ai-node-tree.js +16 -0
  83. package/src/lib/runtime/ai-node-tree.js.map +1 -1
  84. package/src/lib/tools/ai-dataset-tool.d.ts +68 -0
  85. package/src/lib/tools/ai-dataset-tool.js +231 -0
  86. package/src/lib/tools/ai-dataset-tool.js.map +1 -0
  87. package/src/lib/usage/free-ai-credits-left.js +26 -2
  88. package/src/lib/usage/free-ai-credits-left.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-plan-step.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 { aiSiteKindOfInputs } from '../model/ai-site-kinds'\nimport { createHash } from 'node:crypto'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport {\n AI_BUILD_PLAN_TOOL,\n aiBuildPlanToolFor,\n isAiPlanNewRef,\n type AiBuildPlan,\n} from '../model/ai-build-plan'\nimport type { AiJob, AiJobKind, AiJobPlan, AiJobReview, AiJobStatus } from '../model/ai-jobs.types'\nimport { readFreeAiCreditsLeft } from '../usage/free-ai-credits-left'\nimport {\n AI_TEMPLATE_SUBJECT_DEFINITIONS,\n aiTemplateShownTokens,\n type AiTemplateSubject,\n} from '../model/ai-template-subjects'\nimport { AI_JOB_CREATE_KINDS, AI_JOB_CREATE_NOUNS } from '../model/ai-job-creations'\nimport { AI_PAGE_CREATE_KINDS, aiPagePlanShapeRefusal } from '../model/ai-page-job'\nimport {\n AI_PLAN_COMPILED_REPEATS_SENTENCE,\n AI_PLAN_NO_FORM_SENTENCE,\n aiPlanCanPlaceForm,\n aiPlanCapabilitiesForJob,\n aiPlanCapabilityLines,\n type AiPlanCapabilities,\n type AiPlanJobScope,\n} from '../model/ai-plan-capabilities'\nimport type { AiSiteInventory } from '../model/ai-site-inventory'\nimport {\n AI_FREE_SITE_WORST_CASE_CREDITS,\n AI_SITE_CREATE_KINDS,\n AI_SITE_FREE_PAGES,\n AI_SITE_PLAN_MAX_TOKENS,\n AI_SITE_HOME_BANDS,\n aiFreeSiteSectionsWithin,\n aiSiteFullPlanSentence,\n aiSiteHomeMinSections,\n aiSiteNameSentence,\n aiSitePlanIsHome,\n aiSitePlanShapeRefusal,\n aiSiteBlogStandInViolations,\n aiSiteThinHomeViolations,\n AI_SITE_GALLERY_SENTENCE,\n aiSiteEmptyGalleryViolations,\n} from '../model/ai-site-job'\nimport { aiSiteContentPart } from './ai-job-site-content'\nimport { aiLayoutIsShopPage, aiLayoutShopGridSection } from '../layout-language/ai-layout-listings'\nimport { aiStorefrontPlanScreens } from '../layout-language/ai-layout-storefront'\nimport { AI_GENERATION_MAX_ATTEMPTS } from '../runtime/ai-generation-bounds'\nimport { aiPlanFailureCopy, aiPlanRetryRefusal } from '../model/ai-job-failure-copy'\nimport { FREE_AI_TASTE_CREDITS_PER_MONTH } from '../plan-entitlements'\nimport { aiDoctrineSystemBlocks, runValidatedGeneration } from '../runtime/ai-doctrine'\nimport { AI_STEP_TIERS, aiCatalogEntry, aiDefaultModelFor } from '../providers/catalog'\nimport {\n AI_FREE_PAGE_WORST_CASE_CREDITS,\n aiPlanEmbedBriefViolations,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport { assistCreditsFromUsd } from '../usage/assist-credits'\nimport { ASSIST_RETURNED_USD_FIELD, assistSpendAfterReturnsUsd } from '../usage/assist-credit-returns'\nimport { freeAccountUsageRef, freeAssistAccount, type AssistMeteredOrg } from '../usage/assist-free-taste'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport type { AiTool } from '../providers/contract'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport { readAiSiteContext } from '../runtime/site-context'\nimport { aiInstructionsWithSiteContext, type AiSiteContextInput } from '../model/ai-site-context'\nimport {\n AI_BUILD_CREATE_KINDS,\n AI_BUILD_STRUCTURAL_OPS,\n aiBuildPageLimit,\n aiBuildPlanShapeRefusal,\n type AiBuildOps,\n} from '../model/ai-build-job'\nimport { aiBuildOpLines, aiBuildOps } from './ai-build-capabilities'\nimport { aiJobAdmissionRefusal } from './ai-job-admission'\nimport { AI_CREDITS_CONFIRM_CODE } from '../model/ai-credit-estimate'\nimport { readAiPlanCapabilities } from './ai-job-drafts'\nimport {\n AI_JOB_BRIEF_MAX_CHARS,\n type AiJobStepOutcome,\n type AiJobStepRunner,\n} from './ai-job-text-step'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiDoctrineReview, aiUnspentOutcome } from './ai-job-generation'\nimport { aiPlanWithDraftIds } from './ai-job-draft-ids'\nimport { AI_JOBS_COLLECTION, registerAiJobPlanStep } from './ai-jobs'\n\n/**\n * The plan step (AGL-2935): the first step of every job that builds site\n * structure. Before a node is generated, the model answers with a typed plan\n * — what the site already has that the job reuses, what it creates and why,\n * and the screens it builds from them — held to the doctrine's plan rules\n * against the site's inventory and re-asked once when it breaks one.\n *\n * A plan that passes is kept on the job, and the job stops for review: the\n * member reads what it will build before a credit is spent building it, and\n * confirms through the resume door. A plan that still breaks a rule on its\n * re-ask stops the job the same way, with the rules named. Either way the\n * step writes nothing itself; the machine records the plan, the spend and\n * the stop, as it records every step.\n *\n * ── Told what it may create, refused what it cannot build (AGL-3030) ─────\n *\n * Before it asks, the step reads what the job may create on its site: the\n * workspace's plan, the site's counts against its limits, and — for a kind\n * that builds only some plans — what the job builds itself. The user turn\n * states it, the plan rules refuse a creation outside it with the one re-ask,\n * and where the workspace keeps no reusable components they accept the page\n * built inline. A plan the confirm door would still refuse — the kind's own\n * admission, handed the plan, as the resume door hands it — is refused HERE,\n * before a member is shown a Confirm: the job fails with the door's sentence,\n * its plan is not kept, and it holds nothing.\n */\n\n/** The plan step's own instructions, cached after the doctrine. */\nexport const AI_JOB_PLAN_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text:\n 'You plan what a website builder job will build, before anything is built. You are given the kind of job and the brief from the person who owns the site. ' +\n 'Answer with submit_build_plan: what the site inventory already has that the job reuses, what it must create and why nothing listed will do, and each page it builds (the screens list) with its layout, template, slug, search title, search description and sections from top to bottom. ' +\n 'Refer to inventory records by id and to what the plan creates as new:<name>. Plan only what the brief asks for: a component, layout, template, form or email job plans no pages unless the brief asks for them, and a page job plans exactly one page.',\n },\n]\n\n/**\n * The plan step's time (AGL-3026, AGL-3036): its two inventory-lookup rounds,\n * its answer and its re-ask at the routing table's ceiling for `job.plan`, on\n * the tier that step kind is served from, with the step's reads and writes,\n * at the rates `ai-job-budget.ts` assumes — fitted to what a beat can give a\n * step, so the served tier asks a little under the routing ceiling.\n */\nexport const AI_JOB_PLAN_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.plan'],\n maxTokens: AI_ROUTING_TABLE['job.plan'].maxTokens,\n})\n\n/**\n * The least time a plan needs before it starts. Registered with the step, so\n * an inline door never starts a plan. A plan thinks before it answers and\n * routinely runs past an inline door's budget, and a provider call that\n * budget cuts off is still generated and billed upstream while the meter\n * records nothing. The beat starts a plan only with this much of its own\n * budget left, and a spec holds it inside that budget.\n */\nexport const AI_JOB_PLAN_STEP_MINIMUM_MS = AI_JOB_PLAN_STEP_BUDGET.minimumMs\n\n/**\n * The plan's answer ceiling on the model a job runs: the most whose worst\n * case fits the least time the step registered, and never more than the\n * routing table's. A model the catalog does not know is planned at the\n * slowest.\n */\nexport function aiJobPlanMaxTokens(model: string): number {\n return AI_JOB_PLAN_STEP_BUDGET.maxTokens(model)\n}\n\n/** What the member reads while a plan waits for them. */\nexport const AI_JOB_PLAN_REVIEW_COPY =\n 'The plan is ready. Review what the job will reuse and create, then confirm it to build.'\n\n/**\n * The job as the plan step's user turn: its kind, its brief, its scalar\n * inputs and, where the job read them, what it may create on its site\n * (AGL-3030). Per workspace and per site, which is why they ride here and\n * never in a system block the platform's cache entry is keyed on.\n */\nexport function aiJobPlanPrompt(\n job: Pick<AiJob, 'kind' | 'brief' | 'inputs'>,\n capabilities: AiPlanCapabilities | null = null,\n inventory: AiSiteInventory | null = null,\n ops: AiBuildOps | null = null,\n): string {\n const lines = [`Job kind: ${job.kind}`, `Brief: ${job.brief.slice(0, AI_JOB_BRIEF_MAX_CHARS)}`]\n for (const [key, value] of Object.entries(job.inputs ?? {})) {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n lines.push(`${key}: ${String(value)}`)\n }\n }\n if (capabilities) lines.push(...aiPlanCapabilityLines(capabilities))\n // A form is a saved form or none (AGL-3596): said where the site read has\n // none to place and the job may create none.\n if (capabilities && inventory && !aiPlanCanPlaceForm(inventory, capabilities)) {\n lines.push(AI_PLAN_NO_FORM_SENTENCE)\n }\n lines.push(...aiPlanTemplateTokenLines(job))\n lines.push(...aiPlanSiteLines(job, inventory, capabilities))\n lines.push(...aiPlanBuildLines(job, capabilities, ops))\n return lines.join('\\n')\n}\n\n/**\n * What a BUILD job's plan is told (AGL-3616): that one request becomes pages,\n * creations and items, how many pages it may hold, and the item operations\n * this site has with their arguments. On the job's own turn, never a cached\n * system block, because the operations are per site.\n */\nexport function aiPlanBuildLines(\n job: Pick<AiJob, 'kind'>,\n capabilities: AiPlanCapabilities | null,\n ops: AiBuildOps | null,\n): string[] {\n if (job.kind !== 'build') return []\n const pages = aiBuildPageLimit(capabilities?.freeTaste === true)\n return [\n `This is a build from one request: plan each page it asks for in screens (at most ${pages}), each new layout, form, component or email design in create, and anything else in items. Plan only what the request asks for; reuse what the site has.`,\n 'A page section that shows a form or an item places it: put its new:<name> in that section\\'s uses. An item built after another lists it in dependsOn.',\n // The layout language draws a section's repeated items (AGL-3660), so the\n // doctrine's \"repeated items place a component\" is not asked of a build.\n ...(capabilities?.repeatsCompiled ? [AI_PLAN_COMPILED_REPEATS_SENTENCE] : []),\n ...(ops ? aiBuildOpLines(ops, AI_BUILD_STRUCTURAL_OPS) : []),\n ]\n}\n\n/**\n * What a SITE job's plan is told beside the inventory (AGL-3594): the pages\n * the site already has and that their addresses are taken, which one — the\n * untouched starter home — a planned home page at `/` replaces, the Free page\n * cap and its guidance, and that a plan is an outline.\n *\n * A site job only. A new site is born with a published home page at `/`\n * (AGL-3497), and a plan that did not know it could replace it planned its own\n * home there and was refused for the clash on every new site. Kept off a page\n * job's turn, whose length the Free page's wall is proven at.\n */\nexport function aiPlanSiteLines(\n job: Pick<AiJob, 'kind'> & Partial<Pick<AiJob, 'inputs'>>,\n inventory: AiSiteInventory | null,\n capabilities: AiPlanCapabilities | null,\n): string[] {\n if (job.kind !== 'site') return []\n const lines: string[] = []\n // The business's own name, as the name to use (AGL-3596): the plan's search\n // titles carry it, and an input line alone left the model free to coin one.\n const name = job.inputs?.['businessName']\n if (typeof name === 'string' && name.trim()) lines.push(aiSiteNameSentence(name.trim()))\n const pages = (inventory?.screens ?? []).filter((screen) => !screen.template)\n const starter = pages.find((screen) => screen.replaceable)\n if (pages.length) {\n lines.push('Pages the site already has; their addresses are taken unless a line says otherwise:')\n for (const page of pages) {\n lines.push(\n page.replaceable\n ? `- ${page.name} at ${page.slug}: the starter home page the site was created with. Plan this site's home page at / and it replaces this one.`\n : `- ${page.name} at ${page.slug}`,\n )\n }\n if (!starter && pages.some((page) => page.slug.trim() === '/' || page.slug.trim() === '')) {\n lines.push(\"The home page at / is the owner's own and stays: give every page you plan another address.\")\n }\n }\n const cap = capabilities?.freeSitePages\n const home = aiSitePlanHomeRule(inventory, capabilities)\n if (cap !== undefined) {\n lines.push(\n `This is a Free workspace: plan at most ${cap} ${cap === 1 ? 'page' : 'pages'} — the home page at / and the one page the brief most needs, such as services, booking or contact — and ${home.across} sections across them.${aiPlanCanPlaceForm(inventory, capabilities) ? ' Put the contact form on one of them.' : ''}`,\n )\n }\n // A new site is a full website (AGL-3660): its home is planned as one, not\n // left to a ceiling the outline is free to stay far under.\n const plansHome = !pages.some((page) => !page.replaceable && aiSitePlanIsHome(page))\n if (home.min > 0 && plansHome) {\n // A store's home is a storefront (AGL-3676): its own parts, in its own order.\n const bands = aiSiteKindOfInputs(job.inputs)?.id === 'store' ? AI_SITE_STORE_HOME_BANDS : AI_SITE_HOME_BANDS\n lines.push(`The home page at / reads as a full website: at least ${home.min} sections — ${bands}.`)\n }\n // The sections are a budget to use (AGL-3660): a prod start of 2026-10-08\n // read \"at most 8\" as leave to plan a home of two.\n lines.push(aiSiteFullPlanSentence({ pages: cap ?? 1, across: home.across, min: plansHome ? home.min : 0 }))\n // A paid blog's first posts are written at /blog and linked from the\n // header (AGL-3660, AGL-3676), so the plan plans no page standing in for it.\n if (aiSiteContentPart(job.inputs ?? null, capabilities?.freeTaste === true) === 'posts') {\n lines.push(\n \"This site's blog is written for it with its first posts at /blog, and the header links it. Plan no page that stands in for it (no Blog, Articles, Journal, Posts or Stories page); feature the posts in a section of the home page instead.\",\n )\n }\n // A section that shows the work counts its pieces (AGL-3660): a planned\n // gallery of no items let a page about the work show none.\n lines.push(AI_SITE_GALLERY_SENTENCE)\n // A section that asks for something places the form (AGL-3660): a live\n // portfolio start planned a commissions inquiry beside the form it made\n // for its Contact page, without placing it.\n if (aiPlanCanPlaceForm(inventory, capabilities)) lines.push(AI_SITE_FORM_SENTENCE)\n // The kind of site the person picked (AGL-3660): the pages it usually has.\n const kind = aiSiteKindOfInputs(job.inputs)\n if (kind) lines.push(`This is a ${kind.label.toLowerCase()} site. ${kind.pages}`)\n // A store's Shop page IS its storefront (AGL-3676): the platform lists the\n // real products there, so the plan names the section and draws no range.\n if (kind?.id === 'store') lines.push(AI_SITE_STORE_SHOP_SENTENCE)\n lines.push(\n \"Keep the plan an outline: each page's title, address, a short search title and description, and its sections named in a few words. The build writes the copy.\",\n )\n return lines\n}\n\n/**\n * The sentence a site plan's turn states about a section that collects\n * answers (AGL-3660): it places the saved form by reference, and one form\n * may be placed on more than one page.\n */\nexport const AI_SITE_FORM_SENTENCE =\n \"A section that asks visitors for something (contact, inquiry, commissions, booking, sign-up) places the form: put new:<the form's name> or the site's form id in its uses. One form may be placed on several pages.\"\n\n/**\n * What a site start's home page is held to (AGL-3660): its fewest sections,\n * and on the Free taste the sections the wall fits across the pages, which\n * the home's count is shared out of. The plan's turn and its re-ask read this\n * one figure, so the sentence the model is told is the check it is held to.\n */\nexport function aiSitePlanHomeRule(\n inventory: AiSiteInventory | null,\n capabilities: AiPlanCapabilities | null,\n): { min: number; across: number | null } {\n const cap = capabilities?.freeSitePages\n if (cap === undefined) return { min: aiSiteHomeMinSections({ pages: 1, across: null }), across: null }\n // Dear: a guided start that places a form makes one (AGL-3596).\n const across = aiFreeSiteSectionsWithin(\n { layouts: (inventory?.layouts.length ?? 0) ? 0 : 1, pages: cap, forms: 1 },\n FREE_AI_TASTE_CREDITS_PER_MONTH,\n )\n return { min: aiSiteHomeMinSections({ pages: cap, across }), across }\n}\n\n/**\n * A site plan's thin home, asked about on the FIRST answer only (AGL-3660).\n * The re-ask names the count; an answer that still plans a thinner home is\n * kept, since a home with four sections is a site and a stopped start is\n * none — the same trade a language page makes with its last answer's gaps.\n */\nexport function aiSiteThinHomeCheck(\n rule: { min: number; across: number | null },\n): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n let answers = 0\n return (plan) => {\n answers += 1\n if (answers >= AI_GENERATION_MAX_ATTEMPTS) return []\n return aiSiteThinHomeViolations(plan, rule)\n }\n}\n\n/** What a store's plan is told about its Shop page (AGL-3676). */\nexport const AI_SITE_STORE_SHOP_SENTENCE =\n 'Plan a Shop page at /shop: a short title section, then a section named \"Product grid\" second, where the platform lists the store\\'s real products with sort, filters, photos, prices and cart, then at most one or two short sections (care, shipping, gifting help). Never open it with a hero, and never plan the products themselves as cards of your own.'\n\n/** What a store's home is composed of (AGL-3676): a storefront's parts, in a storefront's order. */\nexport const AI_SITE_STORE_HOME_BANDS =\n 'a hero that sells first, then \"Bestsellers\" (the platform lists the real products), \"Shop by collection\" with 3 or 4 items, the brand story, why buy here with 3 or 4 items, \"Customer reviews\" (the platform shows the store\\'s real ones) and a \"Newsletter sign-up\" band last'\n\n/**\n * A store plan held to a storefront (AGL-3676, `ai-layout-storefront.ts`):\n * on a paid start its home gains the parts a shopper expects that the plan\n * left out — bestsellers, collections, reviews, a newsletter sign-up —\n * while the page has room; on any start its Shop page opens on its grid.\n * Settled, never re-asked: each part has one answer, and the Free wall's\n * home keeps the sections it planned.\n */\nexport function aiSiteStorefrontPlan<P extends Pick<AiBuildPlan, 'screens'>>(plan: P, options: { paid: boolean }): P {\n const screens = aiStorefrontPlanScreens(plan.screens, {\n paid: options.paid,\n isShopPage: aiLayoutIsShopPage,\n gridSection: aiLayoutShopGridSection,\n })\n return screens.every((screen, index) => screen === plan.screens[index]) ? plan : { ...plan, screens }\n}\n\n/** The code a store plan with no Shop page is re-asked under. */\nexport const AI_SITE_STORE_SHOP_CODE = 'plan-store-shop-page'\n\n/**\n * A store plan of two or more pages with no Shop page (AGL-3676): the page\n * the platform lists the catalog on is the one a shopper looks for. A\n * one-page Free taste lists its products on the home instead.\n */\nexport function aiSiteStoreShopPageViolations(\n plan: Pick<AiBuildPlan, 'screens'>,\n): Array<{ rule: null; code: string; message: string; paths: string[] }> {\n if (plan.screens.length < 2 || plan.screens.some((screen) => aiLayoutIsShopPage(screen))) return []\n return [\n {\n rule: null,\n code: AI_SITE_STORE_SHOP_CODE,\n message:\n 'This store has no Shop page. Plan one at /shop, its second section named \"Product grid\": the platform lists the real products there.',\n paths: ['screens'],\n },\n ]\n}\n\n/** A store plan's missing Shop page, asked about on the FIRST answer only, like a thin home. */\nexport function aiSiteStoreShopCheck(): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n let answers = 0\n return (plan) => {\n answers += 1\n if (answers >= AI_GENERATION_MAX_ATTEMPTS) return []\n return aiSiteStoreShopPageViolations(plan)\n }\n}\n\n/**\n * A site plan's section that shows the work without its pieces (AGL-3660),\n * asked about on the FIRST answer only, like a thin home: the re-ask names\n * the section, and an answer that keeps it thin is kept.\n */\nexport function aiSiteEmptyGalleryCheck(): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n let answers = 0\n return (plan) => {\n answers += 1\n if (answers >= AI_GENERATION_MAX_ATTEMPTS) return []\n return aiSiteEmptyGalleryViolations(plan)\n }\n}\n\n/**\n * A site plan's page standing in for the blog its start writes (AGL-3660),\n * asked about on the FIRST answer only, like a thin home: the re-ask names\n * the page, and an answer that keeps it is kept — the posts then take the\n * next address the page leaves free, and the header links them all the same.\n */\nexport function aiSiteBlogStandInCheck(): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n let answers = 0\n return (plan) => {\n answers += 1\n if (answers >= AI_GENERATION_MAX_ATTEMPTS) return []\n return aiSiteBlogStandInViolations(plan)\n }\n}\n\n/**\n * What a TEMPLATE job's plan is told its creation's `fields` are (AGL-3143\n * §11): the subject's binding tokens, listed so the planner promises only\n * what the page can fill and the build can be held to it\n * (`aiPlanTemplateTokenViolations`).\n *\n * ⛔ It rides the job's own turn and NOT the `fields` description in the plan\n * tool, which every kind's request caches. Written there it read better and\n * cost 40 tokens of the shared prefix — 2,980 to 3,020 — which is one credit\n * of the Free page's 300-credit wall, taking the room it keeps for a re-asked\n * section from 45 credits to 44 and breaking `ai-job-free-page.spec.ts`. A\n * page job must not pay for a sentence about templates.\n *\n * The list is the tokens a reader sees, never the whole catalog (AGL-3143\n * §16). Offered a slug and the publish timestamp, a live plan promised them,\n * and its build kept the promise the only way a slug can be kept: it printed\n * \"entry slug: {{entry.slug}}\" on every article.\n */\nexport function aiPlanTemplateTokenLines(job: Pick<AiJob, 'kind' | 'inputs'>): string[] {\n if (job.kind !== 'template') return []\n const subject = (job.inputs ?? {})['subject']\n const definition =\n typeof subject === 'string'\n ? AI_TEMPLATE_SUBJECT_DEFINITIONS[subject as AiTemplateSubject]\n : undefined\n if (!definition) return []\n return [\n `The template's fields are the binding tokens its page shows a reader, each one of: ${aiTemplateShownTokens(\n definition,\n ).join(', ')}. A link or picture token is shown by the link or picture holding it. Promise only what the page fills.`,\n ]\n}\n\n/** A kind that builds only some plans: the creations it makes, and the shapes it refuses. */\nexport interface AiJobPlanScope extends AiPlanJobScope {\n /** Why a job of the kind cannot build a plan of this shape; `null` when it can. Pure. */\n shapeRefusal: (plan: AiBuildPlan, options?: { freeTaste?: boolean }) => string | null\n}\n\n/**\n * The kinds whose confirm door builds only some plans (AGL-3030). A page job\n * builds one screen and a scaffold four to eight; each builds only the\n * creations its list names. A template, layout, component, form or email job\n * builds its own record and what that record places (AGL-3143 §15,\n * `AI_JOB_CREATE_KINDS`), and holds no plan to a shape.\n */\nexport const AI_JOB_PLAN_SCOPES: Readonly<Partial<Record<AiJobKind, AiJobPlanScope>>> = {\n page: { noun: 'a page job', creates: AI_PAGE_CREATE_KINDS, shapeRefusal: aiPagePlanShapeRefusal },\n // A build from one request (AGL-3616): its operations are judged against\n // the site's registry by the step, which reads it (`aiBuildPlanViolations`).\n build: {\n noun: 'a build',\n creates: AI_BUILD_CREATE_KINDS,\n shapeRefusal: (plan, options) => aiBuildPlanShapeRefusal(plan, { freeTaste: options?.freeTaste }),\n },\n site: { noun: 'a site scaffold', creates: AI_SITE_CREATE_KINDS, shapeRefusal: aiSitePlanShapeRefusal },\n ...Object.fromEntries(\n Object.entries(AI_JOB_CREATE_KINDS).map(([kind, creates]) => [\n kind,\n { noun: AI_JOB_CREATE_NOUNS[kind as AiJobKind] as string, creates, shapeRefusal: () => null },\n ]),\n ),\n}\n\n/**\n * What the plan step holds beyond the doctrine's plan rules, as the\n * violations the plan's one re-ask names: the players the plan lists against\n * the brief it answers (AGL-3433), which only this step reads beside the plan,\n * and a kind's shape refusal.\n */\nfunction planViolations(\n scope: AiJobPlanScope | null,\n brief: string,\n freeTaste = false,\n ops: AiBuildOps | null = null,\n home: { min: number; across: number | null } | null = null,\n blog = false,\n site = false,\n store = false,\n): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n const thinHome = home && home.min > 0 ? aiSiteThinHomeCheck(home) : null\n const storeShop = store ? aiSiteStoreShopCheck() : null\n const blogStandIn = blog ? aiSiteBlogStandInCheck() : null\n const emptyGallery = site ? aiSiteEmptyGalleryCheck() : null\n return (plan) => {\n // A build's plan is held to the operations this site has (AGL-3616):\n // an unknown op, arguments its schema refuses, a cycle or a reference\n // nothing makes are re-asked once like every other plan rule.\n const message = ops\n ? aiBuildPlanShapeRefusal(plan, { freeTaste, ops })\n : (scope?.shapeRefusal(plan, { freeTaste }) ?? null)\n return [\n ...aiPlanEmbedBriefViolations(plan, brief),\n ...(message ? [{ rule: null, code: 'plan-job-shape', message }] : []),\n ...(thinHome ? thinHome(plan) : []),\n ...(blogStandIn ? blogStandIn(plan) : []),\n ...(emptyGallery ? emptyGallery(plan) : []),\n ...(storeShop ? storeShop(plan) : []),\n ]\n }\n}\n\n/**\n * The inventory names of every id the plan references, so the proposal reads\n * \"the Services layout\" rather than an id — kept on the plan because the\n * inventory is not read again when the member opens it.\n */\nexport function aiPlanLabels(\n plan: AiBuildPlan,\n inventory: AiSiteInventory | null,\n): Record<string, string> {\n const names = new Map<string, string>()\n for (const rows of [\n inventory?.components,\n inventory?.layouts,\n inventory?.templates,\n inventory?.forms,\n inventory?.datasets,\n inventory?.collections,\n inventory?.screens,\n ]) {\n for (const row of rows ?? []) names.set(row.id, row.name)\n }\n const refs = [\n ...plan.reuse.map((entry) => entry.id),\n ...plan.create.map((entry) => entry.duplicateOf),\n ...plan.screens.flatMap((screen) => [\n screen.layout,\n screen.template,\n screen.duplicateOf,\n ...screen.sections.flatMap((section) => section.uses),\n ]),\n ]\n const labels: Record<string, string> = {}\n for (const ref of refs) {\n if (!ref || isAiPlanNewRef(ref)) continue\n const name = names.get(ref)\n if (name) labels[ref] = name\n }\n return labels\n}\n\n/* ------------------------------------------------------------------------ *\n * Reusing an identical brief's plan\n * ------------------------------------------------------------------------ */\n\n/**\n * How long a plan may be reused for (AGL-2937).\n *\n * The window is what makes reuse safe rather than merely cheap. The key\n * already covers everything the request said — the brief, the inputs, the\n * model and the prompt as rendered, site inventory included — so a plan is\n * reused only when nothing the model was shown has changed. What the key\n * cannot see is the world outside the request: a page published, a component\n * renamed after the inventory was read, a member who meant something\n * different the second time. Fifteen minutes is short enough that the answer\n * is still the one the site would give, and long enough to cover what reuse\n * is actually for — the same brief run twice in a sitting, a job resubmitted\n * after a refused reservation, two members starting the same work.\n */\nexport const AI_PLAN_REUSE_WINDOW_MS = 15 * 60 * 1_000\n\n/** Jobs one lookup reads. More than one can share a key; the newest plan wins. */\nexport const AI_PLAN_REUSE_CANDIDATES = 5\n\n/** A job whose plan might be reused, as the finder reports it. */\nexport interface AiJobPlanCandidate {\n jobId: string\n status: AiJobStatus\n plan: AiJobPlan\n}\n\n/**\n * The digest a plan is reused by: the whole request, never the answer.\n *\n * It hashes what the model was asked and what it was shown — the job's kind\n * and site, the user turn (which carries the trimmed brief and every scalar\n * input), the model that would answer, every rendered system block including\n * the site inventory, and the tool's schema. Two requests that hash the same\n * would have been sent the same bytes to the same model, so the second can\n * keep the first's answer.\n *\n * The version tag is the escape hatch: anything that changes what a key\n * MEANS, rather than what it covers, bumps it and strands every old key\n * harmlessly, since a key nothing matches simply asks the model.\n */\nexport function aiJobPlanKey(input: {\n job: Pick<AiJob, 'kind' | 'hostId'>\n prompt: string\n model: string\n system: readonly AiSystemBlock[]\n /** The plan tool the request offers (AGL-3433); the plain one when absent. */\n tool?: AiTool\n}): string {\n const digest = createHash('sha256')\n for (const part of [\n 'plan.v1',\n input.job.kind,\n input.job.hostId ?? '',\n input.model,\n input.prompt,\n ...input.system.map((block) => block.text),\n JSON.stringify(input.tool ?? AI_BUILD_PLAN_TOOL),\n ]) {\n // Length-prefixed, so two different splits of the same characters cannot\n // collide by running into one another.\n digest.update(`${part.length}:${part}\\u0000`)\n }\n return digest.digest('hex')\n}\n\n/** A job that could not have produced a reusable plan, whatever its key says. */\nconst UNREUSABLE: readonly AiJobStatus[] = ['canceled', 'failed']\n\nfunction planMillis(plan: AiJobPlan): number | null {\n const at = plan.proposedAt as unknown\n if (at instanceof Date) return at.getTime()\n if (at && typeof (at as { toMillis?: unknown }).toMillis === 'function') {\n return (at as { toMillis(): number }).toMillis()\n }\n return null\n}\n\n/**\n * The newest plan worth reusing out of what the finder returned: another\n * job's, still proposed or already confirmed, on a job that was neither\n * canceled nor failed, proposed inside the window.\n *\n * A canceled or failed job is excluded even though its plan may be perfectly\n * good: those are the jobs a member walked away from, and handing their plan\n * to the next one would make a rejected answer look like a fresh one.\n */\nexport function aiReusablePlan(\n candidates: readonly AiJobPlanCandidate[],\n context: { jobId: string; now: Date },\n): AiJobPlanCandidate | null {\n const floor = context.now.getTime() - AI_PLAN_REUSE_WINDOW_MS\n let best: AiJobPlanCandidate | null = null\n let bestAt = -1\n for (const candidate of candidates) {\n if (candidate.jobId === context.jobId) continue\n if (UNREUSABLE.includes(candidate.status)) continue\n if (candidate.plan.status !== 'proposed' && candidate.plan.status !== 'confirmed') continue\n const at = planMillis(candidate.plan)\n if (at === null || at < floor || at > context.now.getTime()) continue\n if (at > bestAt) {\n best = candidate\n bestAt = at\n }\n }\n return best\n}\n\nexport type AiJobPlanFinder = (\n orgId: string,\n key: string,\n firestore?: FirebaseFirestore.Firestore,\n) => Promise<AiJobPlanCandidate[]>\n\n/**\n * The finder the step uses in production: an equality on `plan.key` inside\n * the org's own jobs.\n *\n * One equality on one field, with no ordering beside it, so Firestore's\n * automatic single-field index answers it and no composite index is deployed.\n * The window and the statuses are applied in memory instead, which is what\n * keeps it that way.\n */\nexport const findAiJobsByPlanKey: AiJobPlanFinder = async (orgId, key, firestore) => {\n if (!firestore) return []\n const snapshot = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection(AI_JOBS_COLLECTION)\n .where('plan.key', '==', key)\n .limit(AI_PLAN_REUSE_CANDIDATES)\n .get()\n return snapshot.docs.flatMap((doc) => {\n const data = doc.data() as { status?: AiJobStatus; plan?: AiJobPlan | null }\n return data.plan\n ? [{ jobId: doc.id, status: data.status ?? 'queued', plan: data.plan }]\n : []\n })\n}\n\n/** What a job may create on its site, read for the plan step; `null` for no site. */\nexport type AiPlanCapabilitiesReader = (input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n}) => Promise<AiPlanCapabilities | null>\n\n/** The reader the step uses in production: the draft bands' own arithmetic, for the job's site. */\nexport const readAiJobPlanCapabilities: AiPlanCapabilitiesReader = async ({ job, org, firestore }) =>\n job.hostId ? readAiPlanCapabilities(firestore, { hostId: job.hostId, org }) : null\n\nexport interface AiJobPlanStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** The reuse lookup; specs hand in a fake, and `null` turns reuse off. */\n findPlansByKey?: AiJobPlanFinder | null\n /** What the job may create on its site (AGL-3030); specs and the eval recorder hand in their own. */\n readCapabilities?: AiPlanCapabilitiesReader\n /** The kind's admission, asked of a plan before it is kept; the registry's otherwise. */\n admissionRefusal?: typeof aiJobAdmissionRefusal\n /** A build's operations on its site (AGL-3616); the registry and its gates otherwise. */\n readOps?: AiBuildOpsReader\n /**\n * The site's business profile, status and remembered preferences\n * (AGL-3661); specs and the eval recorder hand in their own, and `null`\n * turns it off.\n */\n readSiteContext?: AiSiteContextReader | null\n /**\n * What a Free workspace has left (AGL-3722), read when a build's plan is\n * kept so its card can say whether it fits; `null` turns it off.\n */\n readFreeCredits?: typeof readFreeAiCreditsLeft | null\n}\n\n/** What a job's site context is read with (AGL-3661). */\nexport type AiSiteContextReader = (input: {\n job: AiJob\n firestore: FirebaseFirestore.Firestore\n}) => Promise<AiSiteContextInput | null>\n\n/** The reader the step uses in production: fail-soft, org-scoped, `null` for a job with no site. */\nexport const readAiJobSiteContext: AiSiteContextReader = ({ job, firestore }) =>\n readAiSiteContext(firestore, { orgId: job.orgId, hostId: job.hostId })\n\n/** What a build may plan on its site (AGL-3616). */\nexport type AiBuildOpsReader = (input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n freeTaste: boolean\n}) => Promise<AiBuildOps>\n\n/** The reader the step uses in production: the registry, gated for the job's site. */\nexport const readAiBuildOps: AiBuildOpsReader = async ({ job, org, firestore, freeTaste }) => {\n const host = job.hostId\n ? (((await firestore.collection('hosts').doc(job.hostId).get()).data() ?? null) as Record<string, unknown> | null)\n : null\n return aiBuildOps({ orgId: job.orgId, hostId: job.hostId ?? null, org, host, freeTaste })\n}\n\n/**\n * A build plan's items with what each can cost (AGL-3616), from its\n * capability, recorded as the plan is kept so the console's estimate and the\n * confirm door read one figure without the registry.\n */\nexport function aiPlanWithItemCredits<T extends AiBuildPlan>(ops: AiBuildOps | null, plan: T): T {\n if (!ops || !plan.items?.length) return plan\n return {\n ...plan,\n items: plan.items.map((item) => {\n const capability = ops.get(item.op)\n return capability ? { ...item, credits: Math.max(0, Math.floor(capability.estimateCredits(item.args))) } : item\n }),\n }\n}\n\nexport function createAiJobPlanStep(deps: AiJobPlanStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const findPlansByKey =\n deps.findPlansByKey === undefined ? findAiJobsByPlanKey : deps.findPlansByKey\n const readCapabilities = deps.readCapabilities ?? readAiJobPlanCapabilities\n const admissionRefusal = deps.admissionRefusal ?? aiJobAdmissionRefusal\n const readOps = deps.readOps ?? readAiBuildOps\n const readContext = deps.readSiteContext === undefined ? readAiJobSiteContext : deps.readSiteContext\n const readFreeCredits = deps.readFreeCredits === undefined ? readFreeAiCreditsLeft : deps.readFreeCredits\n return async ({ job, now, signal, firestore, modelFor, org: orgDocument }) => {\n const org = (orgDocument ?? null) as Partial<AglynOrgBilling> | null\n const [inventory, workspace, siteContext] = await Promise.all([\n job.hostId ? readInventory(job.orgId, job.hostId, { firestore }) : Promise.resolve(null),\n readCapabilities({ job, org, firestore }),\n job.hostId && readContext ? readContext({ job, firestore }) : Promise.resolve(null),\n ])\n // The site's profile, status and memory (AGL-3661), as a per-site cached\n // block after the plan rules. The inventory block already lists what the\n // site holds, so the context carries no index of its own here.\n const instructions = aiInstructionsWithSiteContext(AI_JOB_PLAN_INSTRUCTIONS, siteContext)\n const scope = AI_JOB_PLAN_SCOPES[job.kind] ?? null\n const capabilities = aiSitePlanCapabilities(\n job,\n workspace ? aiPlanCapabilitiesForJob(workspace, scope) : null,\n )\n const freeTaste = capabilities?.freeTaste === true\n // A build's operations, as this site has them (AGL-3616).\n const ops = job.kind === 'build' ? await readOps({ job, org, firestore, freeTaste }) : null\n const site = job.kind === 'site'\n // A kept plan waits for its confirmation; a Free build's card is told what\n // is left, so it says before Confirm whether the build fits (AGL-3722).\n // Net of what THIS plan just spent: the machine meters the step after it\n // returns, so the meters read here do not hold it yet, and a card told\n // the figure from before the plan (101) offered Confirm to a person with\n // 48 left, who met the prompt only after pressing it (2026-10-10).\n const planReview = async (spentUsd = 0): Promise<AiJobReview> => {\n const review: AiJobReview = { reason: 'plan', message: AI_JOB_PLAN_REVIEW_COPY, findings: [] }\n if (job.kind !== 'build' || !freeTaste || !readFreeCredits) return review\n const credits = await readFreeCredits(firestore, { orgId: job.orgId, org, now, pendingUsd: spentUsd })\n return credits ? { ...review, freeCredits: credits } : review\n }\n // The model switch's answer for this job (AGL-2942): the creator's pick\n // where the plan, the org restriction and the allotment allowlists allow\n // it, and Auto held to those same lists otherwise. Without a resolver the\n // doctrine asks the routing table itself. A Free site plans on its\n // provider's fast tier (AGL-3594), unless the creator picked a model.\n const model = aiSitePlanModel(job, modelFor?.('job.plan'), freeTaste)\n const route = AI_ROUTING_TABLE['job.plan']\n const prompt = aiJobPlanPrompt(job, capabilities, inventory, ops)\n\n /**\n * The confirm door's answer for this plan, asked before the plan is kept\n * (AGL-3030): the kind's own admission, handed the plan as the resume\n * door hands it. A refusal fails the job with the door's sentence; a door\n * that could not answer keeps the plan, since the resume door asks again\n * before anything is built.\n *\n * Two answers are about the month's Free credits, not the plan (AGL-3722):\n * - the 409 credits prompt KEEPS the plan. The card is told what is left\n * (`planReview`) and offers Build what fits / the home page first /\n * Upgrade, and the confirm door asks with the person's choice. Failing\n * here instead failed every Free build past its p90 before the card\n * could offer them — and paged staff with `ai.jobFailed`, as at\n * 2026-10-09 16:38Z (600 credits estimated, 164 left).\n * - the 429 \"nothing left\" still fails the job with its sentence, but as\n * the customer's limit, which raises no staff alert.\n */\n const refusalOnKeep = async (plan: AiJobPlan, outcome: AiJobStepOutcome): Promise<AiJobStepOutcome | null> => {\n let refusal: Awaited<ReturnType<typeof aiJobAdmissionRefusal>> = null\n try {\n refusal = await admissionRefusal(job.kind, {\n firestore,\n orgId: job.orgId,\n hostId: job.hostId ?? null,\n inputs: job.inputs ?? {},\n org,\n plan,\n uid: job.createdBy,\n })\n } catch (error) {\n console.error('ai plan admission failed', { orgId: job.orgId, jobId: job.$id, error })\n }\n if (!refusal || refusal.code === AI_CREDITS_CONFIRM_CODE) return null\n return {\n ...outcome,\n failure: refusal.error,\n ...(refusal.status === 429 ? { customerLimit: true } : {}),\n }\n }\n\n // Reuse before asking (AGL-2937). The key covers the whole request, so a\n // hit is a request that would have been sent the same bytes to the same\n // model; the window covers what the key cannot see. A reused plan spends\n // nothing, so the machine's spent-nothing branch releases the reservation\n // and meters no credit, and the job still stops for the member to confirm\n // — this job's plan is proposed to this member, whatever the last one did\n // with theirs.\n const resolved = model ?? aiModelForStep('job.plan')\n // A brief that asks for a video is offered the plan's list of players\n // (AGL-3433), and a job that may bind a dataset a record template on\n // each screen (AGL-3475).\n const tool = aiBuildPlanToolFor(job.brief, {\n records: Boolean(inventory?.datasets.length) || capabilities?.create.dataset.allowed === true,\n items: job.kind === 'build',\n })\n const key = aiJobPlanKey({\n job,\n prompt,\n model: resolved,\n system: aiDoctrineSystemBlocks(inventory, { instructions }),\n tool,\n })\n const reused = findPlansByKey\n ? aiReusablePlan(await findPlansByKey(job.orgId, key, firestore), {\n jobId: job.$id,\n now,\n })\n : null\n if (reused) {\n // The reused plan's draft ids name the other job's drafts; this job's are its own.\n const plan: AiJobPlan = aiPlanWithItemCredits(ops, aiPlanWithDraftIds(job.kind, {\n ...reused.plan,\n status: 'proposed',\n labels: aiPlanLabels(reused.plan, inventory),\n proposedAt: now as unknown as AiJobPlan['proposedAt'],\n confirmedAt: null,\n confirmedBy: null,\n key,\n reusedFrom: reused.jobId,\n }))\n const unspent = aiUnspentOutcome(resolved)\n return (\n (await refusalOnKeep(plan, unspent)) ?? {\n ...unspent,\n plan,\n review: await planReview(),\n }\n )\n }\n\n const result = await runValidatedGeneration('plan', {\n step: 'job.plan',\n ...(model ? { model } : {}),\n instructions,\n inventory,\n messages: [{ role: 'user', content: prompt }],\n tool,\n // The routing ceiling, lowered on a tier too slow to look records up,\n // answer and ask again inside the least time the step registered; a\n // scaffold's outline is held to its own, far lower ceiling (AGL-3594).\n maxTokens: aiSitePlanMaxTokens(job, resolved, freeTaste),\n // A scaffold plans an outline without thinking (AGL-3594): the thinking\n // was nearly all of the 13,491 tokens a Free site's plan spent.\n ...(site ? { thinking: 'off' as const } : route.thinking ? { thinking: route.thinking } : {}),\n ...(route.effort ? { effort: route.effort } : {}),\n ...(signal ? { signal } : {}),\n capabilities,\n extend: planViolations(\n scope,\n job.brief,\n freeTaste,\n ops,\n site ? aiSitePlanHomeRule(inventory, capabilities) : null,\n site && aiSiteContentPart(job.inputs ?? null, freeTaste) === 'posts',\n site,\n site && aiSiteKindOfInputs(job.inputs)?.id === 'store',\n ),\n })\n const spent: AiJobStepOutcome = {\n outputs: [],\n usage: result.usage,\n estCostUsd: result.estCostUsd,\n model: result.model,\n stopReason: result.stopReason,\n ...(result.effort ? { effort: result.effort } : {}),\n }\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') {\n // Refused by our own checks, after the one re-ask (AGL-3594): the member\n // reads a sentence and an action, staff the rules; the machine gives the\n // credits back (`uncredited`), and on the Free taste Try again says when\n // it cannot work. Whether the give-back was made is the job's to say\n // (`refundedCredits`), so this sentence does not promise it.\n const review = aiDoctrineReview(result)\n const retryRefusal = freeTaste\n ? await aiFreePlanRetryRefusal({ job, org, firestore, now, site })\n : null\n return {\n ...spent,\n uncredited: true,\n review: {\n ...review,\n message: aiPlanFailureCopy({\n kind: job.kind,\n codes: result.violations.map((violation) => violation.code),\n refunded: false,\n }),\n detail: review.detail ?? review.message,\n ...(retryRefusal ? { retryRefusal } : {}),\n },\n }\n }\n // A store's plan is a storefront's (AGL-3676): settled before it is kept and priced.\n const answered = site && aiSiteKindOfInputs(job.inputs)?.id === 'store' ? aiSiteStorefrontPlan(result.value, { paid: !freeTaste }) : result.value\n // Each draft the plan decides is named as the plan is kept, before anything is built (AGL-3079).\n const plan: AiJobPlan = aiPlanWithItemCredits(ops, aiPlanWithDraftIds(job.kind, {\n ...answered,\n status: 'proposed',\n labels: aiPlanLabels(answered, inventory),\n // A Date the Admin SDK stores as a timestamp, like every instant the machine writes.\n proposedAt: now as unknown as AiJobPlan['proposedAt'],\n confirmedAt: null,\n confirmedBy: null,\n key,\n }))\n return (\n (await refusalOnKeep(plan, spent)) ?? {\n ...spent,\n plan,\n review: await planReview(result.estCostUsd),\n }\n )\n }\n}\n\n/**\n * A site job's capabilities (AGL-3594, AGL-3660): it changes no theme in its\n * plan — every scaffold designs its look first, in a unit of its own — and on\n * the Free taste its plan holds at most the pages the member asked for within\n * the Free band, which the Free wall then holds it to.\n *\n * A build's pages are written in the layout language (`aiBuildUnitJob`), whose\n * compiler draws a section's repeated items itself, so its plan is not asked\n * for a component for them (`repeatsCompiled`, AGL-3616). It still may plan\n * one, and a section two pages share is still one. Every other job's\n * capabilities pass through.\n */\nexport function aiSitePlanCapabilities(\n job: Pick<AiJob, 'kind' | 'inputs'>,\n capabilities: AiPlanCapabilities | null,\n): AiPlanCapabilities | null {\n if (job.kind === 'build' && capabilities) return { ...capabilities, repeatsCompiled: true }\n if (job.kind !== 'site' || !capabilities) return capabilities\n const create = {\n ...capabilities.create,\n 'theme-change': {\n allowed: false,\n left: null,\n reason: 'a site start designs its own look before its pages',\n },\n // A site start builds its look, one layout and one form, never a\n // component (`AI_SITE_CREATE_KINDS`), so a paid workspace's plan draws\n // repeated items in their sections, as a Free one's does. Held to rule 1\n // instead, every paid plan was refused: for the component it left out,\n // or, re-asked, for the one it could not build (AGL-3660).\n component: {\n allowed: false,\n left: null,\n reason: 'a site start draws its repeated items in their sections',\n },\n }\n const site = { ...capabilities, reusableComponents: false, create }\n if (!capabilities.freeTaste) return site\n const asked = Number((job.inputs ?? {})['pages'])\n const pages =\n Number.isInteger(asked) && asked >= AI_SITE_FREE_PAGES.min\n ? Math.min(asked, AI_SITE_FREE_PAGES.max)\n : AI_SITE_FREE_PAGES.max\n return { ...site, freeSitePages: pages }\n}\n\n/**\n * The model a plan runs on (AGL-3594): the resolved one, except a Free site\n * plans on its provider's fast tier — an outline the plan rules hold and\n * re-ask, at a fifth of the balanced tier's output rate. A model the creator\n * picked by name stays theirs.\n */\nexport function aiSitePlanModel(\n job: Pick<AiJob, 'kind' | 'model'>,\n resolved: string | undefined,\n freeTaste: boolean,\n): string | undefined {\n if (job.kind !== 'site' || !freeTaste) return resolved\n const picked = typeof job.model === 'string' ? job.model.trim() : ''\n if (picked && picked !== 'auto') return resolved\n const entry = aiCatalogEntry(resolved ?? aiModelForStep('job.plan'))\n return (entry ? aiDefaultModelFor(entry.provider, 'fast') : undefined) ?? resolved\n}\n\n/** The plan's answer ceiling: the step's own, and a scaffold's outline ceiling under it (AGL-3594). */\nexport function aiSitePlanMaxTokens(\n job: Pick<AiJob, 'kind'>,\n model: string,\n freeTaste: boolean,\n): number {\n const ceiling = aiJobPlanMaxTokens(model)\n if (job.kind !== 'site') return ceiling\n return Math.min(ceiling, freeTaste ? AI_SITE_PLAN_MAX_TOKENS.free : AI_SITE_PLAN_MAX_TOKENS.paid)\n}\n\n/**\n * Why trying a Free plan again cannot work this month, or `null` (AGL-3594):\n * the owner's Free allowance left, read off the account month the meter\n * writes net of give-backs, against what a plan of this kind costs at its\n * worst. Read before this step is metered, and the machine gives a refused\n * plan's credits back, so the figure read is the figure left. A read that fails\n * leaves the button on: the reservation still refuses at the wall.\n */\nasync function aiFreePlanRetryRefusal(input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n now: Date\n site: boolean\n}): Promise<string | null> {\n const account = freeAssistAccount(input.org as AssistMeteredOrg | null)\n if (!account?.accountUid) return null\n try {\n // The meter's month key, `YYYY-MM` in UTC (`assistUsageMonth`).\n const month = input.now.toISOString().slice(0, 7)\n const snapshot = await freeAccountUsageRef(input.firestore, account.accountUid, month).get()\n const spent = assistCreditsFromUsd(\n assistSpendAfterReturnsUsd(snapshot.get('estCostUsd'), snapshot.get(ASSIST_RETURNED_USD_FIELD)),\n )\n return aiPlanRetryRefusal({\n creditsLeft: FREE_AI_TASTE_CREDITS_PER_MONTH - spent,\n planCredits: input.site ? AI_FREE_SITE_WORST_CASE_CREDITS.plan : AI_FREE_PAGE_WORST_CASE_CREDITS.plan,\n })\n } catch (error) {\n console.error('ai plan retry allowance read failed', { orgId: input.job.orgId, jobId: input.job.$id, error })\n return null\n }\n}\n\nexport const runAiJobPlanStep = createAiJobPlanStep()\n\n/**\n * Registers the plan step every planned kind runs first, with the least time\n * a plan needs; the plugin's console surface calls it.\n */\nexport function registerAiJobPlan(): void {\n registerAiJobPlanStep(runAiJobPlanStep, { minimumMs: AI_JOB_PLAN_STEP_MINIMUM_MS })\n}\n"],"names":["aiSiteKindOfInputs","createHash","AI_BUILD_PLAN_TOOL","aiBuildPlanToolFor","isAiPlanNewRef","readFreeAiCreditsLeft","AI_TEMPLATE_SUBJECT_DEFINITIONS","aiTemplateShownTokens","AI_JOB_CREATE_KINDS","AI_JOB_CREATE_NOUNS","AI_PAGE_CREATE_KINDS","aiPagePlanShapeRefusal","AI_PLAN_COMPILED_REPEATS_SENTENCE","AI_PLAN_NO_FORM_SENTENCE","aiPlanCanPlaceForm","aiPlanCapabilitiesForJob","aiPlanCapabilityLines","AI_FREE_SITE_WORST_CASE_CREDITS","AI_SITE_CREATE_KINDS","AI_SITE_FREE_PAGES","AI_SITE_PLAN_MAX_TOKENS","AI_SITE_HOME_BANDS","aiFreeSiteSectionsWithin","aiSiteFullPlanSentence","aiSiteHomeMinSections","aiSiteNameSentence","aiSitePlanIsHome","aiSitePlanShapeRefusal","aiSiteBlogStandInViolations","aiSiteThinHomeViolations","AI_SITE_GALLERY_SENTENCE","aiSiteEmptyGalleryViolations","aiSiteContentPart","aiLayoutIsShopPage","aiLayoutShopGridSection","aiStorefrontPlanScreens","AI_GENERATION_MAX_ATTEMPTS","aiPlanFailureCopy","aiPlanRetryRefusal","FREE_AI_TASTE_CREDITS_PER_MONTH","aiDoctrineSystemBlocks","runValidatedGeneration","AI_STEP_TIERS","aiCatalogEntry","aiDefaultModelFor","AI_FREE_PAGE_WORST_CASE_CREDITS","aiPlanEmbedBriefViolations","assistCreditsFromUsd","ASSIST_RETURNED_USD_FIELD","assistSpendAfterReturnsUsd","freeAccountUsageRef","freeAssistAccount","AI_ROUTING_TABLE","aiModelForStep","readSiteInventory","readAiSiteContext","aiInstructionsWithSiteContext","AI_BUILD_CREATE_KINDS","AI_BUILD_STRUCTURAL_OPS","aiBuildPageLimit","aiBuildPlanShapeRefusal","aiBuildOpLines","aiBuildOps","aiJobAdmissionRefusal","AI_CREDITS_CONFIRM_CODE","readAiPlanCapabilities","AI_JOB_BRIEF_MAX_CHARS","aiJobStepBudget","aiDoctrineReview","aiUnspentOutcome","aiPlanWithDraftIds","AI_JOBS_COLLECTION","registerAiJobPlanStep","AI_JOB_PLAN_INSTRUCTIONS","text","AI_JOB_PLAN_STEP_BUDGET","tier","maxTokens","AI_JOB_PLAN_STEP_MINIMUM_MS","minimumMs","aiJobPlanMaxTokens","model","AI_JOB_PLAN_REVIEW_COPY","aiJobPlanPrompt","job","capabilities","inventory","ops","lines","kind","brief","slice","key","value","Object","entries","inputs","push","String","aiPlanTemplateTokenLines","aiPlanSiteLines","aiPlanBuildLines","join","pages","freeTaste","repeatsCompiled","name","trim","screens","filter","screen","template","starter","find","replaceable","length","page","slug","some","cap","freeSitePages","home","aiSitePlanHomeRule","undefined","across","plansHome","min","bands","id","AI_SITE_STORE_HOME_BANDS","AI_SITE_FORM_SENTENCE","label","toLowerCase","AI_SITE_STORE_SHOP_SENTENCE","layouts","forms","aiSiteThinHomeCheck","rule","answers","plan","aiSiteStorefrontPlan","options","paid","isShopPage","gridSection","every","index","AI_SITE_STORE_SHOP_CODE","aiSiteStoreShopPageViolations","code","message","paths","aiSiteStoreShopCheck","aiSiteEmptyGalleryCheck","aiSiteBlogStandInCheck","subject","definition","AI_JOB_PLAN_SCOPES","noun","creates","shapeRefusal","build","site","fromEntries","map","planViolations","scope","blog","store","thinHome","storeShop","blogStandIn","emptyGallery","aiPlanLabels","names","Map","rows","components","templates","datasets","collections","row","set","refs","reuse","entry","create","duplicateOf","flatMap","layout","sections","section","uses","labels","ref","get","AI_PLAN_REUSE_WINDOW_MS","AI_PLAN_REUSE_CANDIDATES","aiJobPlanKey","input","digest","part","hostId","prompt","system","block","JSON","stringify","tool","update","UNREUSABLE","planMillis","at","proposedAt","Date","getTime","toMillis","aiReusablePlan","candidates","context","floor","now","best","bestAt","candidate","jobId","includes","status","findAiJobsByPlanKey","orgId","firestore","snapshot","collection","doc","where","limit","docs","data","readAiJobPlanCapabilities","org","readAiJobSiteContext","readAiBuildOps","host","aiPlanWithItemCredits","items","item","capability","op","credits","Math","max","estimateCredits","args","createAiJobPlanStep","deps","readInventory","findPlansByKey","readCapabilities","admissionRefusal","readOps","readContext","readSiteContext","readFreeCredits","signal","modelFor","orgDocument","workspace","siteContext","Promise","all","resolve","instructions","aiSitePlanCapabilities","planReview","spentUsd","review","reason","findings","pendingUsd","freeCredits","aiSitePlanModel","route","refusalOnKeep","outcome","refusal","uid","createdBy","error","console","$id","failure","customerLimit","resolved","records","Boolean","dataset","allowed","reused","confirmedAt","confirmedBy","reusedFrom","unspent","result","step","messages","role","content","aiSitePlanMaxTokens","thinking","effort","extend","spent","outputs","usage","estCostUsd","stopReason","refused","retryRefusal","aiFreePlanRetryRefusal","uncredited","codes","violations","violation","refunded","detail","answered","left","component","reusableComponents","asked","Number","isInteger","picked","provider","ceiling","free","account","accountUid","month","toISOString","creditsLeft","planCredits","runAiJobPlanStep","registerAiJobPlan"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,4BAAwB;AAC3D,SAASC,UAAU,QAAQ,cAAa;AAExC,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,cAAc,QAET,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ed 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 { aiSiteKindOfInputs } from '../model/ai-site-kinds'\nimport { createHash } from 'node:crypto'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport {\n AI_BUILD_PLAN_TOOL,\n aiBuildPlanToolFor,\n isAiPlanNewRef,\n type AiBuildPlan,\n} from '../model/ai-build-plan'\nimport type { AiJob, AiJobKind, AiJobPlan, AiJobReview, AiJobStatus } from '../model/ai-jobs.types'\nimport { readFreeAiCreditsLeft } from '../usage/free-ai-credits-left'\nimport {\n AI_TEMPLATE_SUBJECT_DEFINITIONS,\n aiTemplateShownTokens,\n type AiTemplateSubject,\n} from '../model/ai-template-subjects'\nimport { AI_JOB_CREATE_KINDS, AI_JOB_CREATE_NOUNS } from '../model/ai-job-creations'\nimport { AI_PAGE_CREATE_KINDS, aiPagePlanShapeRefusal } from '../model/ai-page-job'\nimport {\n AI_PLAN_COMPILED_REPEATS_SENTENCE,\n AI_PLAN_NO_FORM_SENTENCE,\n aiPlanCanPlaceForm,\n aiPlanCapabilitiesForJob,\n aiPlanCapabilityLines,\n type AiPlanCapabilities,\n type AiPlanJobScope,\n} from '../model/ai-plan-capabilities'\nimport type { AiSiteInventory } from '../model/ai-site-inventory'\nimport { aiSitePlanDatasetCapability } from './ai-job-site-datasets'\nimport {\n AI_FREE_SITE_WORST_CASE_CREDITS,\n AI_SITE_CREATE_KINDS,\n AI_SITE_FREE_PAGES,\n AI_SITE_PLAN_MAX_TOKENS,\n AI_SITE_HOME_BANDS,\n aiFreeSiteSectionsWithin,\n aiSiteFullPlanSentence,\n aiSiteHomeMinSections,\n aiSiteNameSentence,\n aiSitePlanIsHome,\n aiSitePlanShapeRefusal,\n aiSiteBlogStandInViolations,\n aiSiteThinHomeViolations,\n AI_SITE_GALLERY_SENTENCE,\n aiSiteEmptyGalleryViolations,\n AI_SITE_DATASETS_MAX,\n} from '../model/ai-site-job'\nimport { aiSiteContentPart } from './ai-job-site-content'\nimport { aiLayoutIsShopPage, aiLayoutShopGridSection } from '../layout-language/ai-layout-listings'\nimport { aiStorefrontPlanScreens } from '../layout-language/ai-layout-storefront'\nimport { AI_GENERATION_MAX_ATTEMPTS } from '../runtime/ai-generation-bounds'\nimport { aiPlanFailureCopy, aiPlanRetryRefusal } from '../model/ai-job-failure-copy'\nimport { FREE_AI_TASTE_CREDITS_PER_MONTH } from '../plan-entitlements'\nimport { aiDoctrineSystemBlocks, runValidatedGeneration } from '../runtime/ai-doctrine'\nimport { AI_STEP_TIERS, aiCatalogEntry, aiDefaultModelFor } from '../providers/catalog'\nimport {\n AI_FREE_PAGE_WORST_CASE_CREDITS,\n aiPlanEmbedBriefViolations,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport { assistCreditsFromUsd } from '../usage/assist-credits'\nimport { ASSIST_RETURNED_USD_FIELD, assistSpendAfterReturnsUsd } from '../usage/assist-credit-returns'\nimport { freeAccountUsageRef, freeAssistAccount, type AssistMeteredOrg } from '../usage/assist-free-taste'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport type { AiTool } from '../providers/contract'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport { readAiSiteContext } from '../runtime/site-context'\nimport { aiInstructionsWithSiteContext, type AiSiteContextInput } from '../model/ai-site-context'\nimport {\n AI_BUILD_CREATE_KINDS,\n AI_BUILD_STRUCTURAL_OPS,\n aiBuildPageLimit,\n aiBuildPlanShapeRefusal,\n type AiBuildOps,\n} from '../model/ai-build-job'\nimport { aiBuildOpLines, aiBuildOps } from './ai-build-capabilities'\nimport { aiJobAdmissionRefusal } from './ai-job-admission'\nimport { AI_CREDITS_CONFIRM_CODE } from '../model/ai-credit-estimate'\nimport { readAiPlanCapabilities } from './ai-job-drafts'\nimport {\n AI_JOB_BRIEF_MAX_CHARS,\n type AiJobStepOutcome,\n type AiJobStepRunner,\n} from './ai-job-text-step'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiDoctrineReview, aiUnspentOutcome } from './ai-job-generation'\nimport { aiPlanWithDraftIds } from './ai-job-draft-ids'\nimport { AI_JOBS_COLLECTION, registerAiJobPlanStep } from './ai-jobs'\n\n/**\n * The plan step (AGL-2935): the first step of every job that builds site\n * structure. Before a node is generated, the model answers with a typed plan\n * — what the site already has that the job reuses, what it creates and why,\n * and the screens it builds from them — held to the doctrine's plan rules\n * against the site's inventory and re-asked once when it breaks one.\n *\n * A plan that passes is kept on the job, and the job stops for review: the\n * member reads what it will build before a credit is spent building it, and\n * confirms through the resume door. A plan that still breaks a rule on its\n * re-ask stops the job the same way, with the rules named. Either way the\n * step writes nothing itself; the machine records the plan, the spend and\n * the stop, as it records every step.\n *\n * ── Told what it may create, refused what it cannot build (AGL-3030) ─────\n *\n * Before it asks, the step reads what the job may create on its site: the\n * workspace's plan, the site's counts against its limits, and — for a kind\n * that builds only some plans — what the job builds itself. The user turn\n * states it, the plan rules refuse a creation outside it with the one re-ask,\n * and where the workspace keeps no reusable components they accept the page\n * built inline. A plan the confirm door would still refuse — the kind's own\n * admission, handed the plan, as the resume door hands it — is refused HERE,\n * before a member is shown a Confirm: the job fails with the door's sentence,\n * its plan is not kept, and it holds nothing.\n */\n\n/** The plan step's own instructions, cached after the doctrine. */\nexport const AI_JOB_PLAN_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text:\n 'You plan what a website builder job will build, before anything is built. You are given the kind of job and the brief from the person who owns the site. ' +\n 'Answer with submit_build_plan: what the site inventory already has that the job reuses, what it must create and why nothing listed will do, and each page it builds (the screens list) with its layout, template, slug, search title, search description and sections from top to bottom. ' +\n 'Refer to inventory records by id and to what the plan creates as new:<name>. Plan only what the brief asks for: a component, layout, template, form or email job plans no pages unless the brief asks for them, and a page job plans exactly one page.',\n },\n]\n\n/**\n * The plan step's time (AGL-3026, AGL-3036): its two inventory-lookup rounds,\n * its answer and its re-ask at the routing table's ceiling for `job.plan`, on\n * the tier that step kind is served from, with the step's reads and writes,\n * at the rates `ai-job-budget.ts` assumes — fitted to what a beat can give a\n * step, so the served tier asks a little under the routing ceiling.\n */\nexport const AI_JOB_PLAN_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.plan'],\n maxTokens: AI_ROUTING_TABLE['job.plan'].maxTokens,\n})\n\n/**\n * The least time a plan needs before it starts. Registered with the step, so\n * an inline door never starts a plan. A plan thinks before it answers and\n * routinely runs past an inline door's budget, and a provider call that\n * budget cuts off is still generated and billed upstream while the meter\n * records nothing. The beat starts a plan only with this much of its own\n * budget left, and a spec holds it inside that budget.\n */\nexport const AI_JOB_PLAN_STEP_MINIMUM_MS = AI_JOB_PLAN_STEP_BUDGET.minimumMs\n\n/**\n * The plan's answer ceiling on the model a job runs: the most whose worst\n * case fits the least time the step registered, and never more than the\n * routing table's. A model the catalog does not know is planned at the\n * slowest.\n */\nexport function aiJobPlanMaxTokens(model: string): number {\n return AI_JOB_PLAN_STEP_BUDGET.maxTokens(model)\n}\n\n/** What the member reads while a plan waits for them. */\nexport const AI_JOB_PLAN_REVIEW_COPY =\n 'The plan is ready. Review what the job will reuse and create, then confirm it to build.'\n\n/**\n * The job as the plan step's user turn: its kind, its brief, its scalar\n * inputs and, where the job read them, what it may create on its site\n * (AGL-3030). Per workspace and per site, which is why they ride here and\n * never in a system block the platform's cache entry is keyed on.\n */\nexport function aiJobPlanPrompt(\n job: Pick<AiJob, 'kind' | 'brief' | 'inputs'>,\n capabilities: AiPlanCapabilities | null = null,\n inventory: AiSiteInventory | null = null,\n ops: AiBuildOps | null = null,\n): string {\n const lines = [`Job kind: ${job.kind}`, `Brief: ${job.brief.slice(0, AI_JOB_BRIEF_MAX_CHARS)}`]\n for (const [key, value] of Object.entries(job.inputs ?? {})) {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n lines.push(`${key}: ${String(value)}`)\n }\n }\n if (capabilities) lines.push(...aiPlanCapabilityLines(capabilities))\n // A form is a saved form or none (AGL-3596): said where the site read has\n // none to place and the job may create none.\n if (capabilities && inventory && !aiPlanCanPlaceForm(inventory, capabilities)) {\n lines.push(AI_PLAN_NO_FORM_SENTENCE)\n }\n lines.push(...aiPlanTemplateTokenLines(job))\n lines.push(...aiPlanSiteLines(job, inventory, capabilities))\n lines.push(...aiPlanBuildLines(job, capabilities, ops))\n return lines.join('\\n')\n}\n\n/**\n * What a BUILD job's plan is told (AGL-3616): that one request becomes pages,\n * creations and items, how many pages it may hold, and the item operations\n * this site has with their arguments. On the job's own turn, never a cached\n * system block, because the operations are per site.\n */\nexport function aiPlanBuildLines(\n job: Pick<AiJob, 'kind'>,\n capabilities: AiPlanCapabilities | null,\n ops: AiBuildOps | null,\n): string[] {\n if (job.kind !== 'build') return []\n const pages = aiBuildPageLimit(capabilities?.freeTaste === true)\n return [\n `This is a build from one request: plan each page it asks for in screens (at most ${pages}), each new layout, form, component or email design in create, and anything else in items. Plan only what the request asks for; reuse what the site has.`,\n 'A page section that shows a form or an item places it: put its new:<name> in that section\\'s uses. An item built after another lists it in dependsOn.',\n // The layout language draws a section's repeated items (AGL-3660), so the\n // doctrine's \"repeated items place a component\" is not asked of a build.\n ...(capabilities?.repeatsCompiled ? [AI_PLAN_COMPILED_REPEATS_SENTENCE] : []),\n ...(ops ? aiBuildOpLines(ops, AI_BUILD_STRUCTURAL_OPS) : []),\n ]\n}\n\n/**\n * What a SITE job's plan is told beside the inventory (AGL-3594): the pages\n * the site already has and that their addresses are taken, which one — the\n * untouched starter home — a planned home page at `/` replaces, the Free page\n * cap and its guidance, and that a plan is an outline.\n *\n * A site job only. A new site is born with a published home page at `/`\n * (AGL-3497), and a plan that did not know it could replace it planned its own\n * home there and was refused for the clash on every new site. Kept off a page\n * job's turn, whose length the Free page's wall is proven at.\n */\nexport function aiPlanSiteLines(\n job: Pick<AiJob, 'kind'> & Partial<Pick<AiJob, 'inputs'>>,\n inventory: AiSiteInventory | null,\n capabilities: AiPlanCapabilities | null,\n): string[] {\n if (job.kind !== 'site') return []\n const lines: string[] = []\n // The business's own name, as the name to use (AGL-3596): the plan's search\n // titles carry it, and an input line alone left the model free to coin one.\n const name = job.inputs?.['businessName']\n if (typeof name === 'string' && name.trim()) lines.push(aiSiteNameSentence(name.trim()))\n const pages = (inventory?.screens ?? []).filter((screen) => !screen.template)\n const starter = pages.find((screen) => screen.replaceable)\n if (pages.length) {\n lines.push('Pages the site already has; their addresses are taken unless a line says otherwise:')\n for (const page of pages) {\n lines.push(\n page.replaceable\n ? `- ${page.name} at ${page.slug}: the starter home page the site was created with. Plan this site's home page at / and it replaces this one.`\n : `- ${page.name} at ${page.slug}`,\n )\n }\n if (!starter && pages.some((page) => page.slug.trim() === '/' || page.slug.trim() === '')) {\n lines.push(\"The home page at / is the owner's own and stays: give every page you plan another address.\")\n }\n }\n const cap = capabilities?.freeSitePages\n const home = aiSitePlanHomeRule(inventory, capabilities)\n if (cap !== undefined) {\n lines.push(\n `This is a Free workspace: plan at most ${cap} ${cap === 1 ? 'page' : 'pages'} — the home page at / and the one page the brief most needs, such as services, booking or contact — and ${home.across} sections across them.${aiPlanCanPlaceForm(inventory, capabilities) ? ' Put the contact form on one of them.' : ''}`,\n )\n }\n // A new site is a full website (AGL-3660): its home is planned as one, not\n // left to a ceiling the outline is free to stay far under.\n const plansHome = !pages.some((page) => !page.replaceable && aiSitePlanIsHome(page))\n if (home.min > 0 && plansHome) {\n // A store's home is a storefront (AGL-3676): its own parts, in its own order.\n const bands = aiSiteKindOfInputs(job.inputs)?.id === 'store' ? AI_SITE_STORE_HOME_BANDS : AI_SITE_HOME_BANDS\n lines.push(`The home page at / reads as a full website: at least ${home.min} sections — ${bands}.`)\n }\n // The sections are a budget to use (AGL-3660): a prod start of 2026-10-08\n // read \"at most 8\" as leave to plan a home of two.\n lines.push(aiSiteFullPlanSentence({ pages: cap ?? 1, across: home.across, min: plansHome ? home.min : 0 }))\n // A paid blog's first posts are written at /blog and linked from the\n // header (AGL-3660, AGL-3676), so the plan plans no page standing in for it.\n if (aiSiteContentPart(job.inputs ?? null, capabilities?.freeTaste === true) === 'posts') {\n lines.push(\n \"This site's blog is written for it with its first posts at /blog, and the header links it. Plan no page that stands in for it (no Blog, Articles, Journal, Posts or Stories page); feature the posts in a section of the home page instead.\",\n )\n }\n // A section that shows the work counts its pieces (AGL-3660): a planned\n // gallery of no items let a page about the work show none.\n lines.push(AI_SITE_GALLERY_SENTENCE)\n // A section that asks for something places the form (AGL-3660): a live\n // portfolio start planned a commissions inquiry beside the form it made\n // for its Contact page, without placing it.\n if (aiPlanCanPlaceForm(inventory, capabilities)) lines.push(AI_SITE_FORM_SENTENCE)\n // Structured content is kept as a dataset where one may be made (AGL-3616).\n if (capabilities?.create.dataset.allowed) {\n lines.push(aiSiteDatasetSentence(Math.min(capabilities.datasetsMax ?? AI_SITE_DATASETS_MAX, capabilities.create.dataset.left ?? AI_SITE_DATASETS_MAX)))\n }\n // The kind of site the person picked (AGL-3660): the pages it usually has.\n const kind = aiSiteKindOfInputs(job.inputs)\n if (kind) lines.push(`This is a ${kind.label.toLowerCase()} site. ${kind.pages}`)\n // A store's Shop page IS its storefront (AGL-3676): the platform lists the\n // real products there, so the plan names the section and draws no range.\n if (kind?.id === 'store') lines.push(AI_SITE_STORE_SHOP_SENTENCE)\n lines.push(\n \"Keep the plan an outline: each page's title, address, a short search title and description, and its sections named in a few words. The build writes the copy.\",\n )\n return lines\n}\n\n/**\n * The sentence a site plan's turn states about a section that collects\n * answers (AGL-3660): it places the saved form by reference, and one form\n * may be placed on more than one page.\n */\nexport const AI_SITE_FORM_SENTENCE =\n \"A section that asks visitors for something (contact, inquiry, commissions, booking, sign-up) places the form: put new:<the form's name> or the site's form id in its uses. One form may be placed on several pages.\"\n\n/**\n * The sentence a site plan's turn states where it may create datasets, with\n * how many it may (the live eval of 2026-10-10 planned four past a cap of\n * three it was never told)\n * (AGL-3616): a list of like things is kept as one, named in the sections\n * that list it, and a page of its own per record is that dataset's record\n * template. Only where datasets may be made, so a Free plan's turn, whose\n * length its wall is proven at, is unchanged.\n */\nexport function aiSiteDatasetSentence(max: number): string {\n return `Keep structured content as a dataset, at most ${max} ${max === 1 ? 'dataset' : 'datasets'}, and only for a list of 4 or more similar items: a menu, a team, services, portfolio pieces, events, questions and answers; never reviews or testimonials. Create the dataset, its fields the items' field names, and put new:<the dataset's name> in the uses of each section that lists them; the platform lists its records there. Where each item deserves a page of its own, plan one page as the dataset's record template. Anything else stays written on its page. ${AI_SITE_FORM_DATASET_SENTENCE}`\n}\n\n/**\n * What a paid site plan is told about a form that writes to a dataset\n * (AGL-3616, Zach 2026-10-10): only where the person would want each\n * submission kept as a record, the dataset created with the form's own\n * field names, and never listed, because its records are the people who\n * sent the form.\n */\nexport const AI_SITE_FORM_DATASET_SENTENCE =\n \"Where each submission of the form should also be kept as a record (volunteer sign-ups, RSVPs, inquiries), the form writes to a dataset: create the dataset, its fields the form's field names, and set the form's writesTo to new:<the dataset's name>; that dataset counts toward the same limit and no section lists it. Otherwise writesTo is null.\"\n\n\n/**\n * What a site start's home page is held to (AGL-3660): its fewest sections,\n * and on the Free taste the sections the wall fits across the pages, which\n * the home's count is shared out of. The plan's turn and its re-ask read this\n * one figure, so the sentence the model is told is the check it is held to.\n */\nexport function aiSitePlanHomeRule(\n inventory: AiSiteInventory | null,\n capabilities: AiPlanCapabilities | null,\n): { min: number; across: number | null } {\n const cap = capabilities?.freeSitePages\n if (cap === undefined) return { min: aiSiteHomeMinSections({ pages: 1, across: null }), across: null }\n // Dear: a guided start that places a form makes one (AGL-3596).\n const across = aiFreeSiteSectionsWithin(\n { layouts: (inventory?.layouts.length ?? 0) ? 0 : 1, pages: cap, forms: 1 },\n FREE_AI_TASTE_CREDITS_PER_MONTH,\n )\n return { min: aiSiteHomeMinSections({ pages: cap, across }), across }\n}\n\n/**\n * A site plan's thin home, asked about on the FIRST answer only (AGL-3660).\n * The re-ask names the count; an answer that still plans a thinner home is\n * kept, since a home with four sections is a site and a stopped start is\n * none — the same trade a language page makes with its last answer's gaps.\n */\nexport function aiSiteThinHomeCheck(\n rule: { min: number; across: number | null },\n): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n let answers = 0\n return (plan) => {\n answers += 1\n if (answers >= AI_GENERATION_MAX_ATTEMPTS) return []\n return aiSiteThinHomeViolations(plan, rule)\n }\n}\n\n/** What a store's plan is told about its Shop page (AGL-3676). */\nexport const AI_SITE_STORE_SHOP_SENTENCE =\n 'Plan a Shop page at /shop: a short title section, then a section named \"Product grid\" second, where the platform lists the store\\'s real products with sort, filters, photos, prices and cart, then at most one or two short sections (care, shipping, gifting help). Never open it with a hero, and never plan the products themselves as cards of your own.'\n\n/** What a store's home is composed of (AGL-3676): a storefront's parts, in a storefront's order. */\nexport const AI_SITE_STORE_HOME_BANDS =\n 'a hero that sells first, then \"Bestsellers\" (the platform lists the real products), \"Shop by collection\" with 3 or 4 items, the brand story, why buy here with 3 or 4 items, \"Customer reviews\" (the platform shows the store\\'s real ones) and a \"Newsletter sign-up\" band last'\n\n/**\n * A store plan held to a storefront (AGL-3676, `ai-layout-storefront.ts`):\n * on a paid start its home gains the parts a shopper expects that the plan\n * left out — bestsellers, collections, reviews, a newsletter sign-up —\n * while the page has room; on any start its Shop page opens on its grid.\n * Settled, never re-asked: each part has one answer, and the Free wall's\n * home keeps the sections it planned.\n */\nexport function aiSiteStorefrontPlan<P extends Pick<AiBuildPlan, 'screens'>>(plan: P, options: { paid: boolean }): P {\n const screens = aiStorefrontPlanScreens(plan.screens, {\n paid: options.paid,\n isShopPage: aiLayoutIsShopPage,\n gridSection: aiLayoutShopGridSection,\n })\n return screens.every((screen, index) => screen === plan.screens[index]) ? plan : { ...plan, screens }\n}\n\n/** The code a store plan with no Shop page is re-asked under. */\nexport const AI_SITE_STORE_SHOP_CODE = 'plan-store-shop-page'\n\n/**\n * A store plan of two or more pages with no Shop page (AGL-3676): the page\n * the platform lists the catalog on is the one a shopper looks for. A\n * one-page Free taste lists its products on the home instead.\n */\nexport function aiSiteStoreShopPageViolations(\n plan: Pick<AiBuildPlan, 'screens'>,\n): Array<{ rule: null; code: string; message: string; paths: string[] }> {\n if (plan.screens.length < 2 || plan.screens.some((screen) => aiLayoutIsShopPage(screen))) return []\n return [\n {\n rule: null,\n code: AI_SITE_STORE_SHOP_CODE,\n message:\n 'This store has no Shop page. Plan one at /shop, its second section named \"Product grid\": the platform lists the real products there.',\n paths: ['screens'],\n },\n ]\n}\n\n/** A store plan's missing Shop page, asked about on the FIRST answer only, like a thin home. */\nexport function aiSiteStoreShopCheck(): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n let answers = 0\n return (plan) => {\n answers += 1\n if (answers >= AI_GENERATION_MAX_ATTEMPTS) return []\n return aiSiteStoreShopPageViolations(plan)\n }\n}\n\n/**\n * A site plan's section that shows the work without its pieces (AGL-3660),\n * asked about on the FIRST answer only, like a thin home: the re-ask names\n * the section, and an answer that keeps it thin is kept.\n */\nexport function aiSiteEmptyGalleryCheck(): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n let answers = 0\n return (plan) => {\n answers += 1\n if (answers >= AI_GENERATION_MAX_ATTEMPTS) return []\n return aiSiteEmptyGalleryViolations(plan)\n }\n}\n\n/**\n * A site plan's page standing in for the blog its start writes (AGL-3660),\n * asked about on the FIRST answer only, like a thin home: the re-ask names\n * the page, and an answer that keeps it is kept — the posts then take the\n * next address the page leaves free, and the header links them all the same.\n */\nexport function aiSiteBlogStandInCheck(): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n let answers = 0\n return (plan) => {\n answers += 1\n if (answers >= AI_GENERATION_MAX_ATTEMPTS) return []\n return aiSiteBlogStandInViolations(plan)\n }\n}\n\n/**\n * What a TEMPLATE job's plan is told its creation's `fields` are (AGL-3143\n * §11): the subject's binding tokens, listed so the planner promises only\n * what the page can fill and the build can be held to it\n * (`aiPlanTemplateTokenViolations`).\n *\n * ⛔ It rides the job's own turn and NOT the `fields` description in the plan\n * tool, which every kind's request caches. Written there it read better and\n * cost 40 tokens of the shared prefix — 2,980 to 3,020 — which is one credit\n * of the Free page's 300-credit wall, taking the room it keeps for a re-asked\n * section from 45 credits to 44 and breaking `ai-job-free-page.spec.ts`. A\n * page job must not pay for a sentence about templates.\n *\n * The list is the tokens a reader sees, never the whole catalog (AGL-3143\n * §16). Offered a slug and the publish timestamp, a live plan promised them,\n * and its build kept the promise the only way a slug can be kept: it printed\n * \"entry slug: {{entry.slug}}\" on every article.\n */\nexport function aiPlanTemplateTokenLines(job: Pick<AiJob, 'kind' | 'inputs'>): string[] {\n if (job.kind !== 'template') return []\n const subject = (job.inputs ?? {})['subject']\n const definition =\n typeof subject === 'string'\n ? AI_TEMPLATE_SUBJECT_DEFINITIONS[subject as AiTemplateSubject]\n : undefined\n if (!definition) return []\n return [\n `The template's fields are the binding tokens its page shows a reader, each one of: ${aiTemplateShownTokens(\n definition,\n ).join(', ')}. A link or picture token is shown by the link or picture holding it. Promise only what the page fills.`,\n ]\n}\n\n/** A kind that builds only some plans: the creations it makes, and the shapes it refuses. */\nexport interface AiJobPlanScope extends AiPlanJobScope {\n /** Why a job of the kind cannot build a plan of this shape; `null` when it can. Pure. */\n shapeRefusal: (plan: AiBuildPlan, options?: { freeTaste?: boolean }) => string | null\n}\n\n/**\n * The kinds whose confirm door builds only some plans (AGL-3030). A page job\n * builds one screen and a scaffold four to eight; each builds only the\n * creations its list names. A template, layout, component, form or email job\n * builds its own record and what that record places (AGL-3143 §15,\n * `AI_JOB_CREATE_KINDS`), and holds no plan to a shape.\n */\nexport const AI_JOB_PLAN_SCOPES: Readonly<Partial<Record<AiJobKind, AiJobPlanScope>>> = {\n page: { noun: 'a page job', creates: AI_PAGE_CREATE_KINDS, shapeRefusal: aiPagePlanShapeRefusal },\n // A build from one request (AGL-3616): its operations are judged against\n // the site's registry by the step, which reads it (`aiBuildPlanViolations`).\n build: {\n noun: 'a build',\n creates: AI_BUILD_CREATE_KINDS,\n shapeRefusal: (plan, options) => aiBuildPlanShapeRefusal(plan, { freeTaste: options?.freeTaste }),\n },\n site: { noun: 'a site scaffold', creates: AI_SITE_CREATE_KINDS, shapeRefusal: aiSitePlanShapeRefusal },\n ...Object.fromEntries(\n Object.entries(AI_JOB_CREATE_KINDS).map(([kind, creates]) => [\n kind,\n { noun: AI_JOB_CREATE_NOUNS[kind as AiJobKind] as string, creates, shapeRefusal: () => null },\n ]),\n ),\n}\n\n/**\n * What the plan step holds beyond the doctrine's plan rules, as the\n * violations the plan's one re-ask names: the players the plan lists against\n * the brief it answers (AGL-3433), which only this step reads beside the plan,\n * and a kind's shape refusal.\n */\nfunction planViolations(\n scope: AiJobPlanScope | null,\n brief: string,\n freeTaste = false,\n ops: AiBuildOps | null = null,\n home: { min: number; across: number | null } | null = null,\n blog = false,\n site = false,\n store = false,\n): (plan: AiBuildPlan) => AiDoctrineViolation[] {\n const thinHome = home && home.min > 0 ? aiSiteThinHomeCheck(home) : null\n const storeShop = store ? aiSiteStoreShopCheck() : null\n const blogStandIn = blog ? aiSiteBlogStandInCheck() : null\n const emptyGallery = site ? aiSiteEmptyGalleryCheck() : null\n return (plan) => {\n // A build's plan is held to the operations this site has (AGL-3616):\n // an unknown op, arguments its schema refuses, a cycle or a reference\n // nothing makes are re-asked once like every other plan rule.\n const message = ops\n ? aiBuildPlanShapeRefusal(plan, { freeTaste, ops })\n : (scope?.shapeRefusal(plan, { freeTaste }) ?? null)\n return [\n ...aiPlanEmbedBriefViolations(plan, brief),\n ...(message ? [{ rule: null, code: 'plan-job-shape', message }] : []),\n ...(thinHome ? thinHome(plan) : []),\n ...(blogStandIn ? blogStandIn(plan) : []),\n ...(emptyGallery ? emptyGallery(plan) : []),\n ...(storeShop ? storeShop(plan) : []),\n ]\n }\n}\n\n/**\n * The inventory names of every id the plan references, so the proposal reads\n * \"the Services layout\" rather than an id — kept on the plan because the\n * inventory is not read again when the member opens it.\n */\nexport function aiPlanLabels(\n plan: AiBuildPlan,\n inventory: AiSiteInventory | null,\n): Record<string, string> {\n const names = new Map<string, string>()\n for (const rows of [\n inventory?.components,\n inventory?.layouts,\n inventory?.templates,\n inventory?.forms,\n inventory?.datasets,\n inventory?.collections,\n inventory?.screens,\n ]) {\n for (const row of rows ?? []) names.set(row.id, row.name)\n }\n const refs = [\n ...plan.reuse.map((entry) => entry.id),\n ...plan.create.map((entry) => entry.duplicateOf),\n ...plan.screens.flatMap((screen) => [\n screen.layout,\n screen.template,\n screen.duplicateOf,\n ...screen.sections.flatMap((section) => section.uses),\n ]),\n ]\n const labels: Record<string, string> = {}\n for (const ref of refs) {\n if (!ref || isAiPlanNewRef(ref)) continue\n const name = names.get(ref)\n if (name) labels[ref] = name\n }\n return labels\n}\n\n/* ------------------------------------------------------------------------ *\n * Reusing an identical brief's plan\n * ------------------------------------------------------------------------ */\n\n/**\n * How long a plan may be reused for (AGL-2937).\n *\n * The window is what makes reuse safe rather than merely cheap. The key\n * already covers everything the request said — the brief, the inputs, the\n * model and the prompt as rendered, site inventory included — so a plan is\n * reused only when nothing the model was shown has changed. What the key\n * cannot see is the world outside the request: a page published, a component\n * renamed after the inventory was read, a member who meant something\n * different the second time. Fifteen minutes is short enough that the answer\n * is still the one the site would give, and long enough to cover what reuse\n * is actually for — the same brief run twice in a sitting, a job resubmitted\n * after a refused reservation, two members starting the same work.\n */\nexport const AI_PLAN_REUSE_WINDOW_MS = 15 * 60 * 1_000\n\n/** Jobs one lookup reads. More than one can share a key; the newest plan wins. */\nexport const AI_PLAN_REUSE_CANDIDATES = 5\n\n/** A job whose plan might be reused, as the finder reports it. */\nexport interface AiJobPlanCandidate {\n jobId: string\n status: AiJobStatus\n plan: AiJobPlan\n}\n\n/**\n * The digest a plan is reused by: the whole request, never the answer.\n *\n * It hashes what the model was asked and what it was shown — the job's kind\n * and site, the user turn (which carries the trimmed brief and every scalar\n * input), the model that would answer, every rendered system block including\n * the site inventory, and the tool's schema. Two requests that hash the same\n * would have been sent the same bytes to the same model, so the second can\n * keep the first's answer.\n *\n * The version tag is the escape hatch: anything that changes what a key\n * MEANS, rather than what it covers, bumps it and strands every old key\n * harmlessly, since a key nothing matches simply asks the model.\n */\nexport function aiJobPlanKey(input: {\n job: Pick<AiJob, 'kind' | 'hostId'>\n prompt: string\n model: string\n system: readonly AiSystemBlock[]\n /** The plan tool the request offers (AGL-3433); the plain one when absent. */\n tool?: AiTool\n}): string {\n const digest = createHash('sha256')\n for (const part of [\n 'plan.v1',\n input.job.kind,\n input.job.hostId ?? '',\n input.model,\n input.prompt,\n ...input.system.map((block) => block.text),\n JSON.stringify(input.tool ?? AI_BUILD_PLAN_TOOL),\n ]) {\n // Length-prefixed, so two different splits of the same characters cannot\n // collide by running into one another.\n digest.update(`${part.length}:${part}\\u0000`)\n }\n return digest.digest('hex')\n}\n\n/** A job that could not have produced a reusable plan, whatever its key says. */\nconst UNREUSABLE: readonly AiJobStatus[] = ['canceled', 'failed']\n\nfunction planMillis(plan: AiJobPlan): number | null {\n const at = plan.proposedAt as unknown\n if (at instanceof Date) return at.getTime()\n if (at && typeof (at as { toMillis?: unknown }).toMillis === 'function') {\n return (at as { toMillis(): number }).toMillis()\n }\n return null\n}\n\n/**\n * The newest plan worth reusing out of what the finder returned: another\n * job's, still proposed or already confirmed, on a job that was neither\n * canceled nor failed, proposed inside the window.\n *\n * A canceled or failed job is excluded even though its plan may be perfectly\n * good: those are the jobs a member walked away from, and handing their plan\n * to the next one would make a rejected answer look like a fresh one.\n */\nexport function aiReusablePlan(\n candidates: readonly AiJobPlanCandidate[],\n context: { jobId: string; now: Date },\n): AiJobPlanCandidate | null {\n const floor = context.now.getTime() - AI_PLAN_REUSE_WINDOW_MS\n let best: AiJobPlanCandidate | null = null\n let bestAt = -1\n for (const candidate of candidates) {\n if (candidate.jobId === context.jobId) continue\n if (UNREUSABLE.includes(candidate.status)) continue\n if (candidate.plan.status !== 'proposed' && candidate.plan.status !== 'confirmed') continue\n const at = planMillis(candidate.plan)\n if (at === null || at < floor || at > context.now.getTime()) continue\n if (at > bestAt) {\n best = candidate\n bestAt = at\n }\n }\n return best\n}\n\nexport type AiJobPlanFinder = (\n orgId: string,\n key: string,\n firestore?: FirebaseFirestore.Firestore,\n) => Promise<AiJobPlanCandidate[]>\n\n/**\n * The finder the step uses in production: an equality on `plan.key` inside\n * the org's own jobs.\n *\n * One equality on one field, with no ordering beside it, so Firestore's\n * automatic single-field index answers it and no composite index is deployed.\n * The window and the statuses are applied in memory instead, which is what\n * keeps it that way.\n */\nexport const findAiJobsByPlanKey: AiJobPlanFinder = async (orgId, key, firestore) => {\n if (!firestore) return []\n const snapshot = await firestore\n .collection('orgs')\n .doc(orgId)\n .collection(AI_JOBS_COLLECTION)\n .where('plan.key', '==', key)\n .limit(AI_PLAN_REUSE_CANDIDATES)\n .get()\n return snapshot.docs.flatMap((doc) => {\n const data = doc.data() as { status?: AiJobStatus; plan?: AiJobPlan | null }\n return data.plan\n ? [{ jobId: doc.id, status: data.status ?? 'queued', plan: data.plan }]\n : []\n })\n}\n\n/** What a job may create on its site, read for the plan step; `null` for no site. */\nexport type AiPlanCapabilitiesReader = (input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n}) => Promise<AiPlanCapabilities | null>\n\n/** The reader the step uses in production: the draft bands' own arithmetic, for the job's site. */\nexport const readAiJobPlanCapabilities: AiPlanCapabilitiesReader = async ({ job, org, firestore }) => {\n if (!job.hostId) return null\n const capabilities = await readAiPlanCapabilities(firestore, { hostId: job.hostId, org })\n // A site start creates datasets only where the data plugin runs and its\n // writer admits this member now (AGL-3616), and at most a start's few.\n return job.kind === 'site'\n ? aiSitePlanDatasetCapability(capabilities, { firestore, org, now: new Date(), job })\n : capabilities\n}\n\nexport interface AiJobPlanStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** The reuse lookup; specs hand in a fake, and `null` turns reuse off. */\n findPlansByKey?: AiJobPlanFinder | null\n /** What the job may create on its site (AGL-3030); specs and the eval recorder hand in their own. */\n readCapabilities?: AiPlanCapabilitiesReader\n /** The kind's admission, asked of a plan before it is kept; the registry's otherwise. */\n admissionRefusal?: typeof aiJobAdmissionRefusal\n /** A build's operations on its site (AGL-3616); the registry and its gates otherwise. */\n readOps?: AiBuildOpsReader\n /**\n * The site's business profile, status and remembered preferences\n * (AGL-3661); specs and the eval recorder hand in their own, and `null`\n * turns it off.\n */\n readSiteContext?: AiSiteContextReader | null\n /**\n * What a Free workspace has left (AGL-3722), read when a build's plan is\n * kept so its card can say whether it fits; `null` turns it off.\n */\n readFreeCredits?: typeof readFreeAiCreditsLeft | null\n}\n\n/** What a job's site context is read with (AGL-3661). */\nexport type AiSiteContextReader = (input: {\n job: AiJob\n firestore: FirebaseFirestore.Firestore\n}) => Promise<AiSiteContextInput | null>\n\n/** The reader the step uses in production: fail-soft, org-scoped, `null` for a job with no site. */\nexport const readAiJobSiteContext: AiSiteContextReader = ({ job, firestore }) =>\n readAiSiteContext(firestore, { orgId: job.orgId, hostId: job.hostId })\n\n/** What a build may plan on its site (AGL-3616). */\nexport type AiBuildOpsReader = (input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n freeTaste: boolean\n}) => Promise<AiBuildOps>\n\n/** The reader the step uses in production: the registry, gated for the job's site. */\nexport const readAiBuildOps: AiBuildOpsReader = async ({ job, org, firestore, freeTaste }) => {\n const host = job.hostId\n ? (((await firestore.collection('hosts').doc(job.hostId).get()).data() ?? null) as Record<string, unknown> | null)\n : null\n return aiBuildOps({ orgId: job.orgId, hostId: job.hostId ?? null, org, host, freeTaste })\n}\n\n/**\n * A build plan's items with what each can cost (AGL-3616), from its\n * capability, recorded as the plan is kept so the console's estimate and the\n * confirm door read one figure without the registry.\n */\nexport function aiPlanWithItemCredits<T extends AiBuildPlan>(ops: AiBuildOps | null, plan: T): T {\n if (!ops || !plan.items?.length) return plan\n return {\n ...plan,\n items: plan.items.map((item) => {\n const capability = ops.get(item.op)\n return capability ? { ...item, credits: Math.max(0, Math.floor(capability.estimateCredits(item.args))) } : item\n }),\n }\n}\n\nexport function createAiJobPlanStep(deps: AiJobPlanStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const findPlansByKey =\n deps.findPlansByKey === undefined ? findAiJobsByPlanKey : deps.findPlansByKey\n const readCapabilities = deps.readCapabilities ?? readAiJobPlanCapabilities\n const admissionRefusal = deps.admissionRefusal ?? aiJobAdmissionRefusal\n const readOps = deps.readOps ?? readAiBuildOps\n const readContext = deps.readSiteContext === undefined ? readAiJobSiteContext : deps.readSiteContext\n const readFreeCredits = deps.readFreeCredits === undefined ? readFreeAiCreditsLeft : deps.readFreeCredits\n return async ({ job, now, signal, firestore, modelFor, org: orgDocument }) => {\n const org = (orgDocument ?? null) as Partial<AglynOrgBilling> | null\n const [inventory, workspace, siteContext] = await Promise.all([\n job.hostId ? readInventory(job.orgId, job.hostId, { firestore }) : Promise.resolve(null),\n readCapabilities({ job, org, firestore }),\n job.hostId && readContext ? readContext({ job, firestore }) : Promise.resolve(null),\n ])\n // The site's profile, status and memory (AGL-3661), as a per-site cached\n // block after the plan rules. The inventory block already lists what the\n // site holds, so the context carries no index of its own here.\n const instructions = aiInstructionsWithSiteContext(AI_JOB_PLAN_INSTRUCTIONS, siteContext)\n const scope = AI_JOB_PLAN_SCOPES[job.kind] ?? null\n const capabilities = aiSitePlanCapabilities(\n job,\n workspace ? aiPlanCapabilitiesForJob(workspace, scope) : null,\n )\n const freeTaste = capabilities?.freeTaste === true\n // A build's operations, as this site has them (AGL-3616).\n const ops = job.kind === 'build' ? await readOps({ job, org, firestore, freeTaste }) : null\n const site = job.kind === 'site'\n // A kept plan waits for its confirmation; a Free build's card is told what\n // is left, so it says before Confirm whether the build fits (AGL-3722).\n // Net of what THIS plan just spent: the machine meters the step after it\n // returns, so the meters read here do not hold it yet, and a card told\n // the figure from before the plan (101) offered Confirm to a person with\n // 48 left, who met the prompt only after pressing it (2026-10-10).\n const planReview = async (spentUsd = 0): Promise<AiJobReview> => {\n const review: AiJobReview = { reason: 'plan', message: AI_JOB_PLAN_REVIEW_COPY, findings: [] }\n if (job.kind !== 'build' || !freeTaste || !readFreeCredits) return review\n const credits = await readFreeCredits(firestore, { orgId: job.orgId, org, now, pendingUsd: spentUsd })\n return credits ? { ...review, freeCredits: credits } : review\n }\n // The model switch's answer for this job (AGL-2942): the creator's pick\n // where the plan, the org restriction and the allotment allowlists allow\n // it, and Auto held to those same lists otherwise. Without a resolver the\n // doctrine asks the routing table itself. A Free site plans on its\n // provider's fast tier (AGL-3594), unless the creator picked a model.\n const model = aiSitePlanModel(job, modelFor?.('job.plan'), freeTaste)\n const route = AI_ROUTING_TABLE['job.plan']\n const prompt = aiJobPlanPrompt(job, capabilities, inventory, ops)\n\n /**\n * The confirm door's answer for this plan, asked before the plan is kept\n * (AGL-3030): the kind's own admission, handed the plan as the resume\n * door hands it. A refusal fails the job with the door's sentence; a door\n * that could not answer keeps the plan, since the resume door asks again\n * before anything is built.\n *\n * Two answers are about the month's Free credits, not the plan (AGL-3722):\n * - the 409 credits prompt KEEPS the plan. The card is told what is left\n * (`planReview`) and offers Build what fits / the home page first /\n * Upgrade, and the confirm door asks with the person's choice. Failing\n * here instead failed every Free build past its p90 before the card\n * could offer them — and paged staff with `ai.jobFailed`, as at\n * 2026-10-09 16:38Z (600 credits estimated, 164 left).\n * - the 429 \"nothing left\" still fails the job with its sentence, but as\n * the customer's limit, which raises no staff alert.\n */\n const refusalOnKeep = async (plan: AiJobPlan, outcome: AiJobStepOutcome): Promise<AiJobStepOutcome | null> => {\n let refusal: Awaited<ReturnType<typeof aiJobAdmissionRefusal>> = null\n try {\n refusal = await admissionRefusal(job.kind, {\n firestore,\n orgId: job.orgId,\n hostId: job.hostId ?? null,\n inputs: job.inputs ?? {},\n org,\n plan,\n uid: job.createdBy,\n })\n } catch (error) {\n console.error('ai plan admission failed', { orgId: job.orgId, jobId: job.$id, error })\n }\n if (!refusal || refusal.code === AI_CREDITS_CONFIRM_CODE) return null\n return {\n ...outcome,\n failure: refusal.error,\n ...(refusal.status === 429 ? { customerLimit: true } : {}),\n }\n }\n\n // Reuse before asking (AGL-2937). The key covers the whole request, so a\n // hit is a request that would have been sent the same bytes to the same\n // model; the window covers what the key cannot see. A reused plan spends\n // nothing, so the machine's spent-nothing branch releases the reservation\n // and meters no credit, and the job still stops for the member to confirm\n // — this job's plan is proposed to this member, whatever the last one did\n // with theirs.\n const resolved = model ?? aiModelForStep('job.plan')\n // A brief that asks for a video is offered the plan's list of players\n // (AGL-3433), and a job that may bind a dataset a record template on\n // each screen (AGL-3475).\n const tool = aiBuildPlanToolFor(job.brief, {\n records: Boolean(inventory?.datasets.length) || capabilities?.create.dataset.allowed === true,\n items: job.kind === 'build',\n })\n const key = aiJobPlanKey({\n job,\n prompt,\n model: resolved,\n system: aiDoctrineSystemBlocks(inventory, { instructions }),\n tool,\n })\n const reused = findPlansByKey\n ? aiReusablePlan(await findPlansByKey(job.orgId, key, firestore), {\n jobId: job.$id,\n now,\n })\n : null\n if (reused) {\n // The reused plan's draft ids name the other job's drafts; this job's are its own.\n const plan: AiJobPlan = aiPlanWithItemCredits(ops, aiPlanWithDraftIds(job.kind, {\n ...reused.plan,\n status: 'proposed',\n labels: aiPlanLabels(reused.plan, inventory),\n proposedAt: now as unknown as AiJobPlan['proposedAt'],\n confirmedAt: null,\n confirmedBy: null,\n key,\n reusedFrom: reused.jobId,\n }))\n const unspent = aiUnspentOutcome(resolved)\n return (\n (await refusalOnKeep(plan, unspent)) ?? {\n ...unspent,\n plan,\n review: await planReview(),\n }\n )\n }\n\n const result = await runValidatedGeneration('plan', {\n step: 'job.plan',\n ...(model ? { model } : {}),\n instructions,\n inventory,\n messages: [{ role: 'user', content: prompt }],\n tool,\n // The routing ceiling, lowered on a tier too slow to look records up,\n // answer and ask again inside the least time the step registered; a\n // scaffold's outline is held to its own, far lower ceiling (AGL-3594).\n maxTokens: aiSitePlanMaxTokens(job, resolved, freeTaste),\n // A scaffold plans an outline without thinking (AGL-3594): the thinking\n // was nearly all of the 13,491 tokens a Free site's plan spent.\n ...(site ? { thinking: 'off' as const } : route.thinking ? { thinking: route.thinking } : {}),\n ...(route.effort ? { effort: route.effort } : {}),\n ...(signal ? { signal } : {}),\n capabilities,\n extend: planViolations(\n scope,\n job.brief,\n freeTaste,\n ops,\n site ? aiSitePlanHomeRule(inventory, capabilities) : null,\n site && aiSiteContentPart(job.inputs ?? null, freeTaste) === 'posts',\n site,\n site && aiSiteKindOfInputs(job.inputs)?.id === 'store',\n ),\n })\n const spent: AiJobStepOutcome = {\n outputs: [],\n usage: result.usage,\n estCostUsd: result.estCostUsd,\n model: result.model,\n stopReason: result.stopReason,\n ...(result.effort ? { effort: result.effort } : {}),\n }\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') {\n // Refused by our own checks, after the one re-ask (AGL-3594): the member\n // reads a sentence and an action, staff the rules; the machine gives the\n // credits back (`uncredited`), and on the Free taste Try again says when\n // it cannot work. Whether the give-back was made is the job's to say\n // (`refundedCredits`), so this sentence does not promise it.\n const review = aiDoctrineReview(result)\n const retryRefusal = freeTaste\n ? await aiFreePlanRetryRefusal({ job, org, firestore, now, site })\n : null\n return {\n ...spent,\n uncredited: true,\n review: {\n ...review,\n message: aiPlanFailureCopy({\n kind: job.kind,\n codes: result.violations.map((violation) => violation.code),\n refunded: false,\n }),\n detail: review.detail ?? review.message,\n ...(retryRefusal ? { retryRefusal } : {}),\n },\n }\n }\n // A store's plan is a storefront's (AGL-3676): settled before it is kept and priced.\n const answered = site && aiSiteKindOfInputs(job.inputs)?.id === 'store' ? aiSiteStorefrontPlan(result.value, { paid: !freeTaste }) : result.value\n // Each draft the plan decides is named as the plan is kept, before anything is built (AGL-3079).\n const plan: AiJobPlan = aiPlanWithItemCredits(ops, aiPlanWithDraftIds(job.kind, {\n ...answered,\n status: 'proposed',\n labels: aiPlanLabels(answered, inventory),\n // A Date the Admin SDK stores as a timestamp, like every instant the machine writes.\n proposedAt: now as unknown as AiJobPlan['proposedAt'],\n confirmedAt: null,\n confirmedBy: null,\n key,\n }))\n return (\n (await refusalOnKeep(plan, spent)) ?? {\n ...spent,\n plan,\n review: await planReview(result.estCostUsd),\n }\n )\n }\n}\n\n/**\n * A site job's capabilities (AGL-3594, AGL-3660): it changes no theme in its\n * plan — every scaffold designs its look first, in a unit of its own — and on\n * the Free taste its plan holds at most the pages the member asked for within\n * the Free band, which the Free wall then holds it to.\n *\n * A build's pages are written in the layout language (`aiBuildUnitJob`), whose\n * compiler draws a section's repeated items itself, so its plan is not asked\n * for a component for them (`repeatsCompiled`, AGL-3616). It still may plan\n * one, and a section two pages share is still one. Every other job's\n * capabilities pass through.\n */\nexport function aiSitePlanCapabilities(\n job: Pick<AiJob, 'kind' | 'inputs'>,\n capabilities: AiPlanCapabilities | null,\n): AiPlanCapabilities | null {\n if (job.kind === 'build' && capabilities) return { ...capabilities, repeatsCompiled: true }\n if (job.kind !== 'site' || !capabilities) return capabilities\n const create = {\n ...capabilities.create,\n 'theme-change': {\n allowed: false,\n left: null,\n reason: 'a site start designs its own look before its pages',\n },\n // A site start builds its look, one layout and one form, never a\n // component (`AI_SITE_CREATE_KINDS`), so a paid workspace's plan draws\n // repeated items in their sections, as a Free one's does. Held to rule 1\n // instead, every paid plan was refused: for the component it left out,\n // or, re-asked, for the one it could not build (AGL-3660).\n component: {\n allowed: false,\n left: null,\n reason: 'a site start draws its repeated items in their sections',\n },\n }\n // At most a start's few datasets, settled in code where a plan names more (AGL-3616).\n const site = { ...capabilities, reusableComponents: false, create, datasetsMax: AI_SITE_DATASETS_MAX }\n if (!capabilities.freeTaste) return site\n const asked = Number((job.inputs ?? {})['pages'])\n const pages =\n Number.isInteger(asked) && asked >= AI_SITE_FREE_PAGES.min\n ? Math.min(asked, AI_SITE_FREE_PAGES.max)\n : AI_SITE_FREE_PAGES.max\n return { ...site, freeSitePages: pages }\n}\n\n/**\n * The model a plan runs on (AGL-3594): the resolved one, except a Free site\n * plans on its provider's fast tier — an outline the plan rules hold and\n * re-ask, at a fifth of the balanced tier's output rate. A model the creator\n * picked by name stays theirs.\n */\nexport function aiSitePlanModel(\n job: Pick<AiJob, 'kind' | 'model'>,\n resolved: string | undefined,\n freeTaste: boolean,\n): string | undefined {\n if (job.kind !== 'site' || !freeTaste) return resolved\n const picked = typeof job.model === 'string' ? job.model.trim() : ''\n if (picked && picked !== 'auto') return resolved\n const entry = aiCatalogEntry(resolved ?? aiModelForStep('job.plan'))\n return (entry ? aiDefaultModelFor(entry.provider, 'fast') : undefined) ?? resolved\n}\n\n/** The plan's answer ceiling: the step's own, and a scaffold's outline ceiling under it (AGL-3594). */\nexport function aiSitePlanMaxTokens(\n job: Pick<AiJob, 'kind'>,\n model: string,\n freeTaste: boolean,\n): number {\n const ceiling = aiJobPlanMaxTokens(model)\n if (job.kind !== 'site') return ceiling\n return Math.min(ceiling, freeTaste ? AI_SITE_PLAN_MAX_TOKENS.free : AI_SITE_PLAN_MAX_TOKENS.paid)\n}\n\n/**\n * Why trying a Free plan again cannot work this month, or `null` (AGL-3594):\n * the owner's Free allowance left, read off the account month the meter\n * writes net of give-backs, against what a plan of this kind costs at its\n * worst. Read before this step is metered, and the machine gives a refused\n * plan's credits back, so the figure read is the figure left. A read that fails\n * leaves the button on: the reservation still refuses at the wall.\n */\nasync function aiFreePlanRetryRefusal(input: {\n job: AiJob\n org: Partial<AglynOrgBilling> | null\n firestore: FirebaseFirestore.Firestore\n now: Date\n site: boolean\n}): Promise<string | null> {\n const account = freeAssistAccount(input.org as AssistMeteredOrg | null)\n if (!account?.accountUid) return null\n try {\n // The meter's month key, `YYYY-MM` in UTC (`assistUsageMonth`).\n const month = input.now.toISOString().slice(0, 7)\n const snapshot = await freeAccountUsageRef(input.firestore, account.accountUid, month).get()\n const spent = assistCreditsFromUsd(\n assistSpendAfterReturnsUsd(snapshot.get('estCostUsd'), snapshot.get(ASSIST_RETURNED_USD_FIELD)),\n )\n return aiPlanRetryRefusal({\n creditsLeft: FREE_AI_TASTE_CREDITS_PER_MONTH - spent,\n planCredits: input.site ? AI_FREE_SITE_WORST_CASE_CREDITS.plan : AI_FREE_PAGE_WORST_CASE_CREDITS.plan,\n })\n } catch (error) {\n console.error('ai plan retry allowance read failed', { orgId: input.job.orgId, jobId: input.job.$id, error })\n return null\n }\n}\n\nexport const runAiJobPlanStep = createAiJobPlanStep()\n\n/**\n * Registers the plan step every planned kind runs first, with the least time\n * a plan needs; the plugin's console surface calls it.\n */\nexport function registerAiJobPlan(): void {\n registerAiJobPlanStep(runAiJobPlanStep, { minimumMs: AI_JOB_PLAN_STEP_MINIMUM_MS })\n}\n"],"names":["aiSiteKindOfInputs","createHash","AI_BUILD_PLAN_TOOL","aiBuildPlanToolFor","isAiPlanNewRef","readFreeAiCreditsLeft","AI_TEMPLATE_SUBJECT_DEFINITIONS","aiTemplateShownTokens","AI_JOB_CREATE_KINDS","AI_JOB_CREATE_NOUNS","AI_PAGE_CREATE_KINDS","aiPagePlanShapeRefusal","AI_PLAN_COMPILED_REPEATS_SENTENCE","AI_PLAN_NO_FORM_SENTENCE","aiPlanCanPlaceForm","aiPlanCapabilitiesForJob","aiPlanCapabilityLines","aiSitePlanDatasetCapability","AI_FREE_SITE_WORST_CASE_CREDITS","AI_SITE_CREATE_KINDS","AI_SITE_FREE_PAGES","AI_SITE_PLAN_MAX_TOKENS","AI_SITE_HOME_BANDS","aiFreeSiteSectionsWithin","aiSiteFullPlanSentence","aiSiteHomeMinSections","aiSiteNameSentence","aiSitePlanIsHome","aiSitePlanShapeRefusal","aiSiteBlogStandInViolations","aiSiteThinHomeViolations","AI_SITE_GALLERY_SENTENCE","aiSiteEmptyGalleryViolations","AI_SITE_DATASETS_MAX","aiSiteContentPart","aiLayoutIsShopPage","aiLayoutShopGridSection","aiStorefrontPlanScreens","AI_GENERATION_MAX_ATTEMPTS","aiPlanFailureCopy","aiPlanRetryRefusal","FREE_AI_TASTE_CREDITS_PER_MONTH","aiDoctrineSystemBlocks","runValidatedGeneration","AI_STEP_TIERS","aiCatalogEntry","aiDefaultModelFor","AI_FREE_PAGE_WORST_CASE_CREDITS","aiPlanEmbedBriefViolations","assistCreditsFromUsd","ASSIST_RETURNED_USD_FIELD","assistSpendAfterReturnsUsd","freeAccountUsageRef","freeAssistAccount","AI_ROUTING_TABLE","aiModelForStep","readSiteInventory","readAiSiteContext","aiInstructionsWithSiteContext","AI_BUILD_CREATE_KINDS","AI_BUILD_STRUCTURAL_OPS","aiBuildPageLimit","aiBuildPlanShapeRefusal","aiBuildOpLines","aiBuildOps","aiJobAdmissionRefusal","AI_CREDITS_CONFIRM_CODE","readAiPlanCapabilities","AI_JOB_BRIEF_MAX_CHARS","aiJobStepBudget","aiDoctrineReview","aiUnspentOutcome","aiPlanWithDraftIds","AI_JOBS_COLLECTION","registerAiJobPlanStep","AI_JOB_PLAN_INSTRUCTIONS","text","AI_JOB_PLAN_STEP_BUDGET","tier","maxTokens","AI_JOB_PLAN_STEP_MINIMUM_MS","minimumMs","aiJobPlanMaxTokens","model","AI_JOB_PLAN_REVIEW_COPY","aiJobPlanPrompt","job","capabilities","inventory","ops","lines","kind","brief","slice","key","value","Object","entries","inputs","push","String","aiPlanTemplateTokenLines","aiPlanSiteLines","aiPlanBuildLines","join","pages","freeTaste","repeatsCompiled","name","trim","screens","filter","screen","template","starter","find","replaceable","length","page","slug","some","cap","freeSitePages","home","aiSitePlanHomeRule","undefined","across","plansHome","min","bands","id","AI_SITE_STORE_HOME_BANDS","AI_SITE_FORM_SENTENCE","create","dataset","allowed","aiSiteDatasetSentence","Math","datasetsMax","left","label","toLowerCase","AI_SITE_STORE_SHOP_SENTENCE","max","AI_SITE_FORM_DATASET_SENTENCE","layouts","forms","aiSiteThinHomeCheck","rule","answers","plan","aiSiteStorefrontPlan","options","paid","isShopPage","gridSection","every","index","AI_SITE_STORE_SHOP_CODE","aiSiteStoreShopPageViolations","code","message","paths","aiSiteStoreShopCheck","aiSiteEmptyGalleryCheck","aiSiteBlogStandInCheck","subject","definition","AI_JOB_PLAN_SCOPES","noun","creates","shapeRefusal","build","site","fromEntries","map","planViolations","scope","blog","store","thinHome","storeShop","blogStandIn","emptyGallery","aiPlanLabels","names","Map","rows","components","templates","datasets","collections","row","set","refs","reuse","entry","duplicateOf","flatMap","layout","sections","section","uses","labels","ref","get","AI_PLAN_REUSE_WINDOW_MS","AI_PLAN_REUSE_CANDIDATES","aiJobPlanKey","input","digest","part","hostId","prompt","system","block","JSON","stringify","tool","update","UNREUSABLE","planMillis","at","proposedAt","Date","getTime","toMillis","aiReusablePlan","candidates","context","floor","now","best","bestAt","candidate","jobId","includes","status","findAiJobsByPlanKey","orgId","firestore","snapshot","collection","doc","where","limit","docs","data","readAiJobPlanCapabilities","org","readAiJobSiteContext","readAiBuildOps","host","aiPlanWithItemCredits","items","item","capability","op","credits","estimateCredits","args","createAiJobPlanStep","deps","readInventory","findPlansByKey","readCapabilities","admissionRefusal","readOps","readContext","readSiteContext","readFreeCredits","signal","modelFor","orgDocument","workspace","siteContext","Promise","all","resolve","instructions","aiSitePlanCapabilities","planReview","spentUsd","review","reason","findings","pendingUsd","freeCredits","aiSitePlanModel","route","refusalOnKeep","outcome","refusal","uid","createdBy","error","console","$id","failure","customerLimit","resolved","records","Boolean","reused","confirmedAt","confirmedBy","reusedFrom","unspent","result","step","messages","role","content","aiSitePlanMaxTokens","thinking","effort","extend","spent","outputs","usage","estCostUsd","stopReason","refused","retryRefusal","aiFreePlanRetryRefusal","uncredited","codes","violations","violation","refunded","detail","answered","component","reusableComponents","asked","Number","isInteger","picked","provider","ceiling","free","account","accountUid","month","toISOString","creditsLeft","planCredits","runAiJobPlanStep","registerAiJobPl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4J,MAAMwC,GAAG;IAC3C,IAAI,EAAC4F,2BAAAA,QAASC,UAAU,GAAE,OAAO;IACjC,IAAI;QACF,gEAAgE;QAChE,MAAMC,QAAQtI,MAAMsB,GAAG,CAACiH,WAAW,GAAG3P,KAAK,CAAC,GAAG;QAC/C,MAAMoJ,WAAW,MAAM7L,oBAAoB6J,MAAM+B,SAAS,EAAEqG,QAAQC,UAAU,EAAEC,OAAO1I,GAAG;QAC1F,MAAMgH,QAAQ5Q,qBACZE,2BAA2B8L,SAASpC,GAAG,CAAC,eAAeoC,SAASpC,GAAG,CAAC3J;QAEtE,OAAOV,mBAAmB;YACxBiT,aAAahT,kCAAkCoR;YAC/C6B,aAAazI,MAAMpC,IAAI,GAAG3J,gCAAgCoI,IAAI,GAAGvG,gCAAgCuG,IAAI;QACvG;IACF,EAAE,OAAOiJ,OAAO;QACdC,QAAQD,KAAK,CAAC,uCAAuC;YAAExD,OAAO9B,MAAM3H,GAAG,CAACyJ,KAAK;YAAEJ,OAAO1B,MAAM3H,GAAG,CAACmN,GAAG;YAAEF;QAAM;QAC3G,OAAO;IACT;AACF;AAEA,OAAO,MAAMoD,mBAAmBtF,sBAAqB;AAErD;;;CAGC,GACD,OAAO,SAASuF;IACdlR,sBAAsBiR,kBAAkB;QAAE1Q,WAAWD;IAA4B;AACnF"}
@@ -0,0 +1,183 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { pluginResourceDraftWriter } from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts';
18
+ import { type AiBuildPlanCreate, type AiBuildPlanScreen } from '../model/ai-build-plan';
19
+ import type { AiJob, AiJobOutput, AiJobPlan } from '../model/ai-jobs.types';
20
+ import type { AiPlanCapabilities } from '../model/ai-plan-capabilities';
21
+ import { generateAiDataset } from '../runtime/ai-dataset-generation';
22
+ import { type AiLayoutListing, type AiLayoutListingField, type AiLayoutListingScreen } from '../layout-language/ai-layout-listings';
23
+ import { aiPluginDraftAdmissionRefusal } from './ai-job-plugin-drafts';
24
+ import type { AiJobStepContext, AiJobStepRunner } from './ai-job-text-step';
25
+ /**
26
+ * A SITE START'S DATASETS (AGL-3616): "Aglyn AI can also use/create datasets
27
+ * too for whatever it needs" (Zach, 2026-10-10).
28
+ *
29
+ * A site whose content is a list of like things — a restaurant's menu, a
30
+ * studio's team, a contractor's services, a photographer's portfolio, an
31
+ * events list, its questions and answers — keeps it as a DATASET, the way the
32
+ * docs teach a person to: the owner edits one record and every page listing
33
+ * it follows. On a workspace that may create datasets, the site plan creates
34
+ * one for such content (`create`, kind `dataset`) and names it in the `uses`
35
+ * of each section that lists it. The scaffold then builds each dataset as a
36
+ * unit of its own, after the layout and before the form (which may write
37
+ * its submissions to one) and the pages:
38
+ *
39
+ * - DESIGNED by the `submit_dataset` generation (`ai-dataset-generation.ts`):
40
+ * the planned fields typed, at most a few more, and 3 to 12 records seeded
41
+ * from the brief. Nothing anybody did not say: no review, testimonial,
42
+ * rating, quote or person's name, no price the brief does not state.
43
+ * - WRITTEN by the data plugin's `dataset` writer — this plugin never names
44
+ * the datasets collection — with every rule the console's datasets route
45
+ * has: the member's role and `data.manage`, `release_data_store`,
46
+ * `dataStore` (Starter and up), `datasetsPerOrg` counted inside the create,
47
+ * `recordsPerDataset` and the storage band.
48
+ * - LISTED by the pages built after it: each section naming it repeats over
49
+ * the dataset (`aiSiteDatasetListings`, a `records` listing the layout
50
+ * compiler draws), and a page the plan made its record template binds its
51
+ * fields by id and keeps the address field the writer added.
52
+ *
53
+ * Where datasets cannot be created — the Free taste, Starter's two used up,
54
+ * the data store not released — the plan is told so and creates none, so its
55
+ * sections write the items out. A dataset unit that fails or is refused
56
+ * leaves the pages that list it built without it (they say so), and its
57
+ * record page is not built.
58
+ */
59
+ /** The most datasets one site start creates. */
60
+ export { AI_SITE_DATASETS_MAX } from '../model/ai-site-job';
61
+ /** The resource the data plugin's writer is registered under. */
62
+ export declare const AI_SITE_DATASET_RESOURCE = "dataset";
63
+ /** The input a dataset unit's own job carries what it needs in. */
64
+ export declare const AI_SITE_DATASET_INPUT = "siteDataset";
65
+ /** What a dataset unit's job is told beside its creation. */
66
+ export interface AiSiteDatasetInput {
67
+ /** The sections that list it, by page: "Menu › Our dishes (12 items)". */
68
+ shownIn: string[];
69
+ /** Whether a page of the plan is its record template. */
70
+ recordPages: boolean;
71
+ /**
72
+ * The form of the plan that writes its submissions to it (AGL-3616), by
73
+ * name, with that form's planned fields; absent where no form does.
74
+ */
75
+ forForm?: {
76
+ name: string;
77
+ fields: string[];
78
+ };
79
+ }
80
+ /** What a dataset row says when its design could not be written: our failure, refunded. */
81
+ export declare const AI_SITE_DATASET_NOT_WRITTEN_COPY = "This dataset could not be added this time.";
82
+ /** The note a written dataset carries on the job's page. */
83
+ export declare function aiSiteDatasetNote(records: number): string;
84
+ /** The note a record template's row adds: the binding is the member's to save (rule 13). */
85
+ export declare const AI_SITE_RECORD_PAGE_NOTE = "A page per record is drafted, not live: open Page Properties \u2192 Record pages to save it.";
86
+ /** ASSUMED: what one dataset pass reads and writes beside its generation: the site, the writer's reads and its transaction. */
87
+ export declare const AI_SITE_DATASET_WRITES_MS = 2000;
88
+ /** One dataset's pass: its generation and re-ask at its ceiling, and its writes. */
89
+ export declare const AI_SITE_DATASET_BUDGET: import("./ai-job-budget").AiJobStepBudget;
90
+ /** The plan's datasets, in plan order, at most the most a start creates. */
91
+ export declare function aiSitePlanDatasets(plan: Pick<AiJobPlan, 'create'>): AiBuildPlanCreate[];
92
+ /** Where the plan lists a dataset, in words its design reads, whether a page is its record template, and the form that writes to it. */
93
+ export declare function aiSiteDatasetInputOf(dataset: Pick<AiBuildPlanCreate, 'name'>, screens: readonly AiBuildPlanScreen[], create?: readonly AiBuildPlanCreate[]): AiSiteDatasetInput;
94
+ /** Whether a plan screen is the record template of a dataset the plan creates, and which. */
95
+ export declare function aiSiteRecordTemplateOf(screen: Pick<AiBuildPlanScreen, 'record'>): string | null;
96
+ /** The most fields a form's dataset is designed with: the data plugin writer's own ceiling is higher. */
97
+ export declare const AI_SITE_FORM_DATASET_FIELDS_MAX = 12;
98
+ /** A planned field as a person reads it: `fullName` and `full_name` are "Full name". */
99
+ export declare function aiSiteDatasetFieldName(planned: string): string;
100
+ /**
101
+ * A dataset a form writes to, as the data plugin's writer takes it
102
+ * (AGL-3616): designed with no model, since its records are the
103
+ * submissions. Its fields are its planned ones — or, where the plan gave it
104
+ * none, the form's — each a person's words for it, text unless the plan
105
+ * typed it as `Name:type`, never required, so a submission that leaves one
106
+ * blank is still a record. It starts with no records. Pure.
107
+ */
108
+ export declare function aiSiteFormDatasetContent(name: string, planned: readonly string[], form: {
109
+ fields: readonly string[];
110
+ }): Record<string, unknown>;
111
+ /** The note a form's dataset carries on the job's page. */
112
+ export declare function aiSiteFormDatasetNote(form: string): string;
113
+ export interface AiSiteDatasetRunnerDeps {
114
+ generate?: typeof generateAiDataset;
115
+ writerFor?: typeof pluginResourceDraftWriter;
116
+ }
117
+ /**
118
+ * The fields of a designed dataset that its records leave empty on most of
119
+ * them — every record, or more than half — by the id the data plugin gave
120
+ * each (AGL-3616). Its first field is the record's name and is never one. The
121
+ * live low-tide-hollow start (beta.239) seeded its tour dates with no venue,
122
+ * rightly inventing none, and its cards bound the venue as their eyebrow.
123
+ */
124
+ export declare function aiDatasetSparseFields(dataset: {
125
+ fields: ReadonlyArray<{
126
+ name: string;
127
+ }>;
128
+ records: ReadonlyArray<ReadonlyArray<string | undefined>>;
129
+ }, written: readonly AiLayoutListingField[]): string[];
130
+ /**
131
+ * The dataset unit's runner, on the job the scaffold derived for it: the one
132
+ * creation its plan carries, designed by the model and written by the data
133
+ * plugin, under the creation's own id. A pass repeated after its write finds
134
+ * the dataset the writer wrote and reports it again, spending nothing.
135
+ */
136
+ export declare function createAiSiteDatasetRunner(deps?: AiSiteDatasetRunnerDeps): AiJobStepRunner;
137
+ export declare const runAiSiteDatasetUnit: AiJobStepRunner;
138
+ /**
139
+ * Whether a dataset may be created for this member on this site, asked before
140
+ * its first pass so a refusal spends nothing; `null` admits. The data plugin
141
+ * must run here (on for the workspace and the site, past its release flag),
142
+ * and its writer says whether this member may make one now: the role, the
143
+ * plan, the flag, the allowance.
144
+ */
145
+ export declare function aiSiteDatasetRefusal(context: Pick<AiJobStepContext, 'firestore' | 'org' | 'now'> & {
146
+ job: Pick<AiJob, 'orgId' | 'hostId' | 'createdBy'>;
147
+ }, deps?: {
148
+ admission?: typeof aiPluginDraftAdmissionRefusal;
149
+ writerFor?: (resource: string) => ReturnType<typeof pluginResourceDraftWriter>;
150
+ }): Promise<string | null>;
151
+ /**
152
+ * A site plan's dataset capability on this workspace (AGL-3616): where the
153
+ * workspace's plan includes datasets, whether the data plugin runs here and
154
+ * this member may create one now, and how many a start may make. A clause the
155
+ * plan's turn completes is the reason where it may not.
156
+ */
157
+ export declare function aiSitePlanDatasetCapability(capabilities: AiPlanCapabilities, context: Parameters<typeof aiSiteDatasetRefusal>[0], deps?: Parameters<typeof aiSiteDatasetRefusal>[1]): Promise<AiPlanCapabilities>;
158
+ /**
159
+ * A `records` listing for each dataset that was made and that a section of the
160
+ * plan names (AGL-3616). Its fields, where none are given, are read off the
161
+ * site's inventory when the page is designed (`aiLayoutListingsWithDatasets`).
162
+ */
163
+ export declare function aiDatasetListingsOf(datasets: ReadonlyArray<{
164
+ id: string;
165
+ name: string;
166
+ records?: string[];
167
+ fields?: AiLayoutListingField[];
168
+ }>, screens: readonly AiLayoutListingScreen[]): AiLayoutListing[];
169
+ /**
170
+ * The site's datasets a layout or a page unit is handed (AGL-3616), each a
171
+ * `records` listing with the sections of the plan's pages that name it, once
172
+ * its unit wrote it. A dataset not yet written, or one that failed, lists
173
+ * nowhere: the pages built without it write the items out.
174
+ */
175
+ export declare function aiSiteDatasetListings(input: {
176
+ outputs: readonly AiJobOutput[];
177
+ datasets: ReadonlyArray<Pick<AiBuildPlanCreate, 'name'>>;
178
+ screens: readonly AiLayoutListingScreen[];
179
+ /** The ids each dataset's unit delivered, by plan name lowercased. */
180
+ delivered: ReadonlyMap<string, string>;
181
+ }): AiLayoutListing[];
182
+ /** What a page is told about the datasets built before it. */
183
+ export declare function aiSiteDatasetBriefLines(outputs: readonly AiJobOutput[]): string[];