@aglyn/plugins-ai 1.0.0-beta.152 → 1.0.0-beta.154
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +17 -17
- package/src/lib/jobs/ai-job-component-step.d.ts +27 -1
- package/src/lib/jobs/ai-job-component-step.js +62 -2
- package/src/lib/jobs/ai-job-component-step.js.map +1 -1
- package/src/lib/jobs/ai-job-drafts.d.ts +19 -0
- package/src/lib/jobs/ai-job-drafts.js +22 -0
- package/src/lib/jobs/ai-job-drafts.js.map +1 -1
- package/src/lib/jobs/ai-job-form-step.d.ts +22 -1
- package/src/lib/jobs/ai-job-form-step.js +63 -0
- package/src/lib/jobs/ai-job-form-step.js.map +1 -1
- package/src/lib/jobs/ai-job-page-sections.d.ts +28 -6
- package/src/lib/jobs/ai-job-page-sections.js +29 -7
- package/src/lib/jobs/ai-job-page-sections.js.map +1 -1
- package/src/lib/jobs/ai-job-template-step.d.ts +22 -1
- package/src/lib/jobs/ai-job-template-step.js +53 -2
- package/src/lib/jobs/ai-job-template-step.js.map +1 -1
- package/src/lib/jobs/fixtures/ai-page-briefs.d.ts +18 -1
- package/src/lib/jobs/fixtures/ai-page-briefs.js +79 -0
- package/src/lib/jobs/fixtures/ai-page-briefs.js.map +1 -1
- package/src/lib/runtime/ai-doctrine-validators.d.ts +21 -0
- package/src/lib/runtime/ai-doctrine-validators.js +50 -0
- package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
- package/src/lib/runtime/ai-repeated-items.d.ts +13 -2
- package/src/lib/runtime/ai-repeated-items.js +41 -17
- package/src/lib/runtime/ai-repeated-items.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-page-sections.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 { REUSABLE_INSTANCE_COMPONENT_ID } from '@aglyn/aglyn/app-utils/reusable-component-keys'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type { NodesMap } from '@aglyn/aglyn/types/nodes'\nimport type { AiBuildPlanScreen, AiBuildPlanSection } from '../model/ai-build-plan'\nimport { aiPageTypeDefinition, parseAiPageJobInputs } from '../model/ai-page-job'\nimport type { AiJob, AiJobPlan } from '../model/ai-jobs.types'\nimport { aiHomeScreenIds, type AiSiteInventory } from '../model/ai-site-inventory'\nimport type { AiTool } from '../providers/contract'\nimport {\n AI_REASK_OFFENDING_MAX_CHARS,\n aiAnswerTree,\n aiNodeTreeContextFromInventory,\n type AiGenerationCheck,\n} from '../runtime/ai-doctrine'\nimport {\n detectCutLines,\n detectDisagreeingNodes,\n isAiLinkElement,\n validateAiDoctrineTree,\n walkTree,\n type AiDoctrineNode,\n type AiDoctrineTreeContext,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport { AI_INSTANCE_REF_PROP, validateAiNodeTree } from '../runtime/ai-node-tree'\nimport { aiPageLinkTarget, aiPageScrollInteraction } from '../runtime/ai-page-links'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { AI_PALETTE_CATALOG } from '../runtime/ai-palette.generated'\nimport { AI_REPEAT_KEY, expandAiRepeatedItems } from '../runtime/ai-repeated-items'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { aiJobBriefLine, aiPlanReferenceLines } from './ai-job-generation'\nimport { aiPlanItemCountViolations } from './ai-job-plan-conformance'\n\n/**\n * A page built one section at a time (AGL-2907): what one section pass asks\n * for, how its answer is held to the building rules as part of the page, and\n * how it joins the page.\n *\n * Pure: no Firestore and no provider, so the page step, its specs and the\n * evals read one definition of a section.\n *\n * ── Held as part of the page ─────────────────────────────────────────────\n *\n * A section is checked twice over, by validators the doctrine already has:\n * the palette validator on the section as the model wrote it, then the\n * doctrine's whole page check on the page built so far with the section\n * added. So the page's one main, its one h1 and its heading outline, repeats\n * across sections, and its weight against the page budget are held on every\n * pass, not only on the last. The violations name the section's own nodes,\n * by the ids the model wrote, so a re-ask quotes this section and nothing\n * else — the page is never sent back.\n *\n * ── A repeated item written once (AGL-3053) ──────────────────────────────\n *\n * Where the workspace keeps no reusable components, an answer writes a\n * repeated item once and lists its copies' values, and the check draws the\n * copies before either validator reads the section (`ai-repeated-items.ts`).\n * Both then read the section as the page stores it, so the page's rules hold\n * on every copy exactly as on an item written out in full, and a finding on a\n * copy names the node the model wrote. Where the workspace keeps components,\n * an item written once is refused: it places instances.\n */\n\n/** The section root id a pass writes, from the job and the plan section's index. */\nexport function aiPageSectionNodeId(jobId: string, index: number): string {\n return `ai-${jobId.slice(0, 12)}-section-${index + 1}`\n}\n\n/** The strict tool a section arrives through. The node map rides as JSON text, as a page's does. */\nexport const AI_PAGE_SECTION_TOOL: AiTool = {\n name: 'submit_section',\n description: 'Submit one section of the page as one flat node map.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['tree'],\n properties: {\n tree: {\n type: 'string',\n description:\n 'The section as JSON: {\"rootId\": \"<id>\", \"nodes\": {\"<id>\": {\"componentId\": \"...\", \"props\": {...}, \"sx\": {...}, \"nodes\": [\"<child id>\", ...]}}}. The root is the document wrapper (componentId \"div\") holding one Section.',\n },\n },\n },\n}\n\n/** The page step's own instructions, cached after the doctrine, with the screen palette after them. */\nexport const AI_JOB_PAGE_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n 'You build a web page one section at a time, in the order a confirmed plan gives. Each answer is ONE section: call submit_section with a flat node map whose root is the document wrapper (componentId \"div\") holding exactly one Section (section).',\n 'The first section is the top of the page and holds the page’s one h1, its title. Every later section opens with an h2, and headings below it step down one level at a time.',\n 'Place what the section’s plan line names. A component the site has is placed as an instance, never drawn again: componentId \"reusableInstance\", props {\"refId\": \"<component id>\", \"propValues\": {…}} filling the props the inventory lists. A form the site has is a Form (form) whose formId is that form’s id. Another screen of the site is linked by its screen id, with a Screen Link (muiScreenLink) or a Button (muiButton) whose screenId is that id.',\n 'Where the request says the site keeps no saved forms or reusable components, draw them in the section instead: a repeated item is written once, and a form is a Form (form) with no formId, a formName saying what it collects and a submitLabel, holding one Form Field (formField) for each answer with its fieldName, label and fieldType.',\n 'Lay the section out with a Container, a Stack or a Grid (\"container\": true, \"spacing\": 3) of Grid items sized like \"xs:12 md:4\", and size nothing with a fixed width. Colors come from the theme’s palette tokens such as primary.main, spacing from the spacing scale, and type from the text variants.',\n 'The page renders inside the site’s layout, so a section is never a header, navigation or footer.',\n 'A picture is an Image (image) with alt text that says what it should show and no src, for the site owner to fill from the media library.',\n 'Write plain, specific copy in the site’s voice, with no filler. Where the brief leaves out a fact, such as a price, a phone number or an address, write the gap in square brackets instead of inventing it.',\n ].join('\\n'),\n },\n { text: AI_PALETTE_CATALOG.screen, cacheBreakpoint: true },\n]\n\n/** A plan reference as the request names it: the id with the name it was planned under. */\nfunction referenceOf(plan: AiJobPlan, ref: string): string {\n const label = plan.labels?.[ref]\n return label ? `${ref} (\"${label}\")` : ref\n}\n\nexport interface AiPageSectionPromptInput {\n job: Pick<AiJob, 'brief' | 'inputs'>\n plan: AiJobPlan\n screen: AiBuildPlanScreen\n index: number\n /** The most elements the section may carry at this pass's answer ceiling. */\n maxElements: number\n /**\n * Whether the workspace keeps reusable components and saved forms\n * (AGL-3030); `false` asks for the section built inline. Absent is `true`.\n */\n reusableComponents?: boolean\n}\n\n/** What a section request says where the workspace keeps no reusable components or saved forms. */\nexport const AI_PAGE_SECTION_INLINE_LINE =\n 'This site keeps no saved forms or reusable components: write a repeated item once, and draw a form as a Form holding its Form Fields.'\n\n/** How a repeated item is written once, in the words a request and a re-ask share. */\nconst AI_PAGE_SECTION_REPEAT_SHAPE = `put {{1}}, {{2}}… where its copies differ, and give its outermost node \"${AI_REPEAT_KEY}\", one list of values a copy, in that order, as [[\"Title 1\", \"Text 1\"], [\"Title 2\", \"Text 2\"]]`\n\n/**\n * How a repeated item is written once (AGL-3053): the item's subtree once,\n * with placeholders where its copies differ and their values listed, which\n * the section check draws into its copies (`ai-repeated-items.ts`). It rides\n * the request of a section whose plan line shows items on a workspace that\n * keeps no reusable components, and no other: a section with nothing to repeat\n * pays nothing for it, and the cached prefix every workspace shares says only\n * that a repeated item is written once.\n */\nexport const AI_PAGE_SECTION_REPEAT_LINE = `Write a repeated item once: ${AI_PAGE_SECTION_REPEAT_SHAPE}.`\n\n/**\n * How a workspace that keeps reusable components writes a repeated item\n * (AGL-3143 §10): as one instance of a component the section already places,\n * repeated, rather than the item's subtree drawn once per copy.\n *\n * It rides the request of a section whose plan line shows items AND names a\n * record to place, on the same terms the repeat line rides a Free one: a\n * section with nothing to repeat, or nothing to repeat it FROM, pays nothing\n * for it.\n *\n * ## Why a paid section could not be built without it (AGL-3024)\n *\n * The Free path is reconciled at both ends — its plan is held to the sections\n * its wall pays for (AGL-3070) and its request is shown the repeat shape\n * (AGL-3053). The paid path was reconciled at neither: `AI_BUILD_PLAN_LIMITS`\n * lets a plan promise up to `items: 500` in one section, the pass that builds\n * it fits `aiJobPageSectionMaxElements` — fifteen at the balanced tier — and\n * the request said only how many elements to keep under, never how to get\n * there. A six-card grid measured live on 2026-09-21 was drawn inline, ran\n * past its ceiling, and was cut off; the re-ask then said to place an instance\n * \"of a component the site has\" without naming one, so it was cut off too, and\n * `AI_GENERATION_MAX_ATTEMPTS` ended the job with no page. A four-card grid on\n * the same site had fitted, which is why this went unseen.\n *\n * ⛔ This does NOT make the plan and the pass agree about what fits — a plan\n * may still promise more items than any ceiling can carry, and this line only\n * gives the pass its cheapest way to try. That bound belongs on the plan step\n * and is deliberately not taken here.\n */\nexport const AI_PAGE_SECTION_INSTANCE_LINE =\n 'Write a repeated item once: place one instance of the component this section places and repeat that instance, rather than drawing the item again for each copy.'\n\n/**\n * What a pass whose answer ran past its ceiling is told makes a section\n * smaller (AGL-3042): fewer elements, down to the budget the request gave,\n * shorter copy, and a repeated item drawn no more than once — placed as an\n * instance where the workspace keeps reusable components, and written once\n * where it keeps none (AGL-3053), with the shape spelled out, since a section\n * whose plan line showed no items was never told it. It rides the re-ask,\n * never the first request, so a pass that fits sends no byte more.\n */\nexport function aiPageSectionSmaller(input: Pick<AiPageSectionPromptInput, 'maxElements' | 'reusableComponents'>): string {\n return input.reusableComponents === false\n ? `Make it smaller: use fewer elements, at most ${input.maxElements}; write shorter copy; and write a repeated item once instead of drawing it again: ${AI_PAGE_SECTION_REPEAT_SHAPE}.`\n : `Make it smaller: use fewer elements, at most ${input.maxElements}; write shorter copy; and place a repeated item as an instance of a component the site has instead of drawing it again.`\n}\n\n/** One pass's user turn: the page, the brief, the plan, this section and what is built above it. */\nexport function aiPageSectionPrompt(input: AiPageSectionPromptInput): string {\n const { job, plan, screen, index } = input\n const inputs = parseAiPageJobInputs(job.inputs)\n const type = typeof inputs === 'string' ? null : aiPageTypeDefinition(inputs.pageType)\n const section = screen.sections[index] as AiBuildPlanSection\n const places = section.uses.length\n ? ` It places ${section.uses.map((ref) => referenceOf(plan, ref)).join(', ')}.`\n : ''\n const items = section.items ? ` It shows ${section.items} items.` : ''\n const built = screen.sections.slice(0, index).map((entry, position) => `${position + 1}. ${entry.name}`)\n return [\n `Page: \"${screen.title}\" at ${screen.slug}`,\n ...(type ? [`Page type: ${type.purpose}`] : []),\n aiJobBriefLine(job),\n ...aiPlanReferenceLines(plan),\n `Build section ${index + 1} of ${screen.sections.length}: \"${section.name}\".${places}${items}`,\n built.length\n ? `Already built, above it: ${built.join('; ')}. The page’s h1 is in section 1.`\n : 'Nothing is built yet: this section holds the page’s h1.',\n ...(input.reusableComponents === false\n ? [AI_PAGE_SECTION_INLINE_LINE, ...(section.items ? [AI_PAGE_SECTION_REPEAT_LINE] : [])]\n : section.items && section.uses.length\n ? [AI_PAGE_SECTION_INSTANCE_LINE]\n : []),\n `Keep this section to at most ${input.maxElements} elements.`,\n ].join('\\n')\n}\n\n/** A validated section: its nodes keyed as the page stores them, its root under the page root. */\nexport interface AiPageSection {\n rootId: string\n nodes: NodesMap\n /** The page's weight with the section added, as the doctrine measured it. */\n load: AiLoadEstimate | null\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** A page with nothing on it yet: the document wrapper. */\nexport function aiEmptyPage(): NodesMap {\n return {\n [CANVAS_ROOT_ELEMENT_ID]: {\n $id: CANVAS_ROOT_ELEMENT_ID,\n componentId: 'div',\n parentId: null,\n nodes: [],\n },\n } as unknown as NodesMap\n}\n\n/**\n * The page with a section in its plan position: after every section with a\n * lower index and before every one with a higher, the page's other children\n * — whatever a member placed — kept where they are. A section already on the\n * page is replaced, never doubled.\n */\nexport function aiPageWithSection(\n page: NodesMap,\n section: AiPageSection,\n sectionIds: readonly string[],\n): NodesMap {\n const nodes: Record<string, Record<string, unknown>> = {}\n const previous = (page as unknown as Record<string, Record<string, unknown>>)[section.rootId]\n const replaced = new Set<string>()\n if (previous) {\n for (const { id } of walkTree({\n rootId: section.rootId,\n nodes: page as unknown as Record<string, AiDoctrineNode>,\n })) {\n replaced.add(id)\n }\n }\n for (const [id, node] of Object.entries(page)) {\n if (!replaced.has(id)) nodes[id] = { ...(node as unknown as Record<string, unknown>) }\n }\n const root = nodes[CANVAS_ROOT_ELEMENT_ID] ?? (aiEmptyPage()[CANVAS_ROOT_ELEMENT_ID] as unknown as Record<string, unknown>)\n const children = (Array.isArray(root['nodes']) ? (root['nodes'] as string[]) : []).filter(\n (id) => id !== section.rootId,\n )\n const order = new Map(sectionIds.map((id, position) => [id, position]))\n const at = order.get(section.rootId) ?? sectionIds.length\n const before = children.findIndex((id) => (order.get(id) ?? -1) > at)\n children.splice(before === -1 ? children.length : before, 0, section.rootId)\n nodes[CANVAS_ROOT_ELEMENT_ID] = { ...root, nodes: children }\n for (const [id, node] of Object.entries(section.nodes)) {\n nodes[id] = { ...(node as unknown as Record<string, unknown>) }\n }\n return nodes as unknown as NodesMap\n}\n\n/**\n * What a tree generated against this inventory may reference, the brand it is\n * held to, where the workspace keeps no reusable components or saved forms\n * (AGL-3030) that the page is built inline, and the sections its plan names,\n * which a link may take a visitor to (AGL-3097).\n */\nexport function aiPageCheckContext(\n inventory: AiSiteInventory | null,\n options: { reusableComponents?: boolean; sections?: readonly string[] } = {},\n): AiDoctrineTreeContext {\n return {\n brand: inventory?.theme ? { colors: inventory.theme.colors, fonts: inventory.theme.fonts } : null,\n ...aiNodeTreeContextFromInventory(inventory),\n homeScreenIds: aiHomeScreenIds(inventory),\n ...(options.reusableComponents === false ? { reusableComponents: false } : {}),\n ...(options.sections?.length ? { pageSections: options.sections } : {}),\n }\n}\n\nexport interface AiPageSectionCheckInput {\n /** The page as stored so far; an empty page on the first pass. */\n page: NodesMap\n /** Every section root id of the plan, in order. */\n sectionIds: readonly string[]\n index: number\n context: AiDoctrineTreeContext\n /**\n * The plan line this pass answers for: what it places by inventory id, and\n * how many items it promised, which the answer is held to (AGL-3024).\n */\n section: Pick<AiBuildPlanSection, 'name' | 'uses' | 'items'>\n inventory: AiSiteInventory | null\n}\n\n/** The parts of an answer the violations name, as the model wrote them, capped as the doctrine caps a re-ask. */\nfunction offendingOf(raw: unknown, violations: readonly AiDoctrineViolation[]): { offending?: Record<string, unknown> } {\n const rawNodes = isRecord(raw) && isRecord(raw['nodes']) ? raw['nodes'] : {}\n const offending: Record<string, unknown> = {}\n let used = 2\n for (const id of new Set(violations.flatMap((violation) => violation.nodeIds ?? []))) {\n if (rawNodes[id] === undefined) continue\n const size = JSON.stringify(rawNodes[id]).length + id.length + 4\n if (used + size > AI_REASK_OFFENDING_MAX_CHARS) break\n offending[id] = rawNodes[id]\n used += size\n }\n return Object.keys(offending).length ? { offending } : {}\n}\n\n/**\n * The check a section's answer is held to: a repeated item written once drawn\n * into its copies (AGL-3053), then the palette validator on the section, with\n * any line it cut at its ceiling refused (AGL-3076), the doctrine's page check\n * on the page with the section added, and the plan line — every component it\n * names placed as an instance, every form bound by its id (rule 7), and as\n * many items as it promised (AGL-3024). Violations\n * name the section's own nodes by the ids the MODEL wrote, and a copy's nodes\n * by the item's; one that names only nodes an earlier pass stored belongs to\n * the page rather than to this answer, and is left to the last pass (AGL-3078).\n */\nexport function aiPageSectionCheck(input: AiPageSectionCheckInput): AiGenerationCheck<AiPageSection> {\n const sectionId = input.sectionIds[input.index]\n const components = new Set((input.inventory?.components ?? []).map((row) => row.id))\n const forms = new Set((input.inventory?.forms ?? []).map((row) => row.id))\n return (answer) => {\n const raw = aiAnswerTree(answer)\n // Before anything is drawn or dropped: a repeated item written and never\n // placed is content the section loses silently, and a child named and\n // never written ends the pass with nothing to answer (AGL-3143).\n const disagreeing = detectDisagreeingNodes(raw)\n if (disagreeing.length) {\n return { value: null, violations: disagreeing, ...offendingOf(raw, disagreeing) }\n }\n const drawn = expandAiRepeatedItems(raw, { inline: input.context.reusableComponents === false, noun: 'section' })\n if (drawn.ok === false) {\n return { value: null, violations: drawn.violations, ...offendingOf(raw, drawn.violations) }\n }\n // Every id below is the drawn tree's; a copy's leads back to the node the model wrote.\n const written = (id: string): string => drawn.sourceIds[id] ?? id\n const validated = validateAiNodeTree(drawn.tree, 'screen', input.context)\n if (validated.ok === false) {\n return {\n value: null,\n violations: [\n {\n rule: null,\n code: `tree-${validated.code}`,\n message: 'The answer could not be used as a section.',\n detail: validated.error,\n },\n ],\n }\n }\n const wrapper = validated.nodes[validated.rootId] as unknown as AiDoctrineNode | undefined\n const top = (wrapper?.nodes ?? []).filter((id) => validated.nodes[id])\n const sectionNode = top.length === 1 ? (validated.nodes[top[0]] as unknown as AiDoctrineNode) : null\n if (!sectionNode || sectionNode.componentId !== 'section') {\n return {\n value: null,\n violations: [\n {\n rule: null,\n code: 'section-shape',\n message: 'Answer with exactly one Section element inside the document wrapper.',\n },\n ],\n }\n }\n\n // The section's root takes its plan id, so a pass run again finds it, and\n // hangs under the page root; every other minted id stays as minted.\n const minted = top[0]\n const modelIds: Record<string, string> = Object.fromEntries(\n Object.entries(validated.sourceIds).map(([id, source]) => [id, written(source)]),\n )\n modelIds[sectionId] = written(validated.sourceIds[minted] ?? minted)\n const sectionNodes: Record<string, Record<string, unknown>> = {}\n for (const { id, node } of walkTree({\n rootId: minted,\n nodes: validated.nodes as unknown as Record<string, AiDoctrineNode>,\n })) {\n const stored = { ...(node as unknown as Record<string, unknown>) }\n if (id === minted) {\n stored['$id'] = sectionId\n stored['parentId'] = CANVAS_ROOT_ELEMENT_ID\n } else if (stored['parentId'] === minted) {\n stored['parentId'] = sectionId\n }\n sectionNodes[id === minted ? sectionId : id] = stored\n }\n const drawnNodes = isRecord(drawn.tree) && isRecord(drawn.tree['nodes']) ? drawn.tree['nodes'] : {}\n // What the model wrote of one of the section's nodes, by the id the page stores it under.\n const drawnIdOf = (stored: string): string =>\n validated.sourceIds[stored === sectionId ? minted : stored] ?? stored\n // A link that names a section of this page carries the platform's Scroll to\n // element interaction to that section's root, whose id is minted from the\n // plan before the section is built (AGL-3097).\n const sections = input.context.pageSections ?? []\n for (const [id, node] of Object.entries(sectionNodes)) {\n const props = isRecord(node['props']) ? node['props'] : {}\n if (!isAiLinkElement(node['componentId']) || props['screenId'] || props['href']) continue\n const target = aiPageLinkTarget(drawnNodes[drawnIdOf(id)], sections)\n if (target?.kind === 'section') {\n node['interactions'] = [aiPageScrollInteraction(input.sectionIds[target.section], sections[target.section])]\n }\n }\n const section: AiPageSection = { rootId: sectionId, nodes: sectionNodes as unknown as NodesMap, load: null }\n\n const page = aiPageWithSection(input.page, section, input.sectionIds)\n const own = new Set(Object.keys(sectionNodes))\n // The page check reads the section as the page stores it, where the palette\n // validator has already dropped what it could not read, such as a\n // `container` written as text or a link's `scrollTo`; what the model wrote\n // of each of the section's nodes is read from the section as it was drawn\n // (AGL-3078). A link the page already carries to one of its section roots\n // goes there, whichever pass wrote it (AGL-3097).\n const report = validateAiDoctrineTree({ rootId: CANVAS_ROOT_ELEMENT_ID, nodes: page }, 'page', {\n ...input.context,\n writtenNode: (id) => (own.has(id) ? drawnNodes[drawnIdOf(id)] : undefined),\n scrollTargetIds: input.sectionIds,\n })\n // The page check mints its ids afresh: its map leads back to the page's\n // ids, and the section's own lead back to the model's.\n const pageIds = report.tree?.sourceIds ?? {}\n const toModel = (id: string): string | null => {\n const stored = pageIds[id] ?? id\n return own.has(stored) ? (modelIds[stored] ?? stored) : null\n }\n // The page check reads the section as it is stored, where a line the\n // palette validator cut is already cut, so the cut is read from the\n // section's own validation, first (AGL-3076). Copies of one item name one\n // node the model wrote, once.\n //\n // A PASS ANSWERS ONLY FOR THE SECTION IT WROTE (AGL-3078). The page check\n // reads the whole page, so it also names nodes an earlier pass stored; the\n // model is not shown those and cannot mend them, so a finding that names\n // none of this section's nodes is not held against this answer. Dropping\n // it neither hides nor forgives it: the last pass runs the same check on\n // the finished page, where every node is the page's and the review names\n // each one and outlines it. Kept, such a finding would re-ask the model\n // for a node it never saw, refuse the same answer twice, and stop the page\n // with findings whose ids all filtered away — no node ids, and so no\n // outline either.\n const violations: AiDoctrineViolation[] = [\n ...detectCutLines(validated.repairs, drawnNodes, written),\n ...report.violations.flatMap((violation) => {\n if (!violation.nodeIds?.length) return [violation]\n const named = [...new Set(violation.nodeIds.map(toModel).filter((id): id is string => id !== null))]\n return named.length ? [{ ...violation, nodeIds: named }] : []\n }),\n ]\n\n const placed = new Set<string>()\n const bound = new Set<string>()\n for (const node of Object.values(sectionNodes)) {\n const props = isRecord(node['props']) ? node['props'] : {}\n if (node['componentId'] === REUSABLE_INSTANCE_COMPONENT_ID && typeof props[AI_INSTANCE_REF_PROP] === 'string') {\n placed.add(props[AI_INSTANCE_REF_PROP] as string)\n }\n if (node['componentId'] === 'form' && typeof props['formId'] === 'string') bound.add(props['formId'])\n }\n const missing = input.section.uses.filter(\n (ref) => (components.has(ref) && !placed.has(ref)) || (forms.has(ref) && !bound.has(ref)),\n )\n if (missing.length) {\n violations.push({\n rule: 7,\n code: 'plan-reuse-not-placed',\n message: `The confirmed plan places ${missing.join(', ')} in this section, and the section does not. Place each one by its id.`,\n })\n }\n // The count the plan promised, against the section as the page stores it\n // (AGL-3024): the prompt states it, and until now nothing read it back.\n violations.push(\n ...aiPlanItemCountViolations(input.section, {\n rootId: sectionId,\n nodes: sectionNodes as unknown as Record<string, AiDoctrineNode>,\n }),\n )\n\n return {\n value: { ...section, load: report.load },\n violations,\n ...offendingOf(raw, violations),\n }\n }\n}\n"],"names":["REUSABLE_INSTANCE_COMPONENT_ID","CANVAS_ROOT_ELEMENT_ID","aiPageTypeDefinition","parseAiPageJobInputs","aiHomeScreenIds","AI_REASK_OFFENDING_MAX_CHARS","aiAnswerTree","aiNodeTreeContextFromInventory","detectCutLines","detectDisagreeingNodes","isAiLinkElement","validateAiDoctrineTree","walkTree","AI_INSTANCE_REF_PROP","validateAiNodeTree","aiPageLinkTarget","aiPageScrollInteraction","AI_PALETTE_CATALOG","AI_REPEAT_KEY","expandAiRepeatedItems","aiJobBriefLine","aiPlanReferenceLines","aiPlanItemCountViolations","aiPageSectionNodeId","jobId","index","slice","AI_PAGE_SECTION_TOOL","name","description","strict","inputSchema","type","additionalProperties","required","properties","tree","AI_JOB_PAGE_INSTRUCTIONS","text","join","screen","cacheBreakpoint","referenceOf","plan","ref","label","labels","AI_PAGE_SECTION_INLINE_LINE","AI_PAGE_SECTION_REPEAT_SHAPE","AI_PAGE_SECTION_REPEAT_LINE","AI_PAGE_SECTION_INSTANCE_LINE","aiPageSectionSmaller","input","reusableComponents","maxElements","aiPageSectionPrompt","job","inputs","pageType","section","sections","places","uses","length","map","items","built","entry","position","title","slug","purpose","isRecord","value","Array","isArray","aiEmptyPage","$id","componentId","parentId","nodes","aiPageWithSection","page","sectionIds","order","previous","rootId","replaced","Set","id","add","node","Object","entries","has","root","children","filter","Map","at","get","before","findIndex","splice","aiPageCheckContext","inventory","options","brand","theme","colors","fonts","homeScreenIds","pageSections","offendingOf","raw","violations","rawNodes","offending","used","flatMap","violation","nodeIds","undefined","size","JSON","stringify","keys","aiPageSectionCheck","sectionId","components","row","forms","answer","validated","report","disagreeing","drawn","inline","context","noun","ok","written","sourceIds","rule","code","message","detail","error","wrapper","top","sectionNode","minted","modelIds","fromEntries","source","sectionNodes","stored","drawnNodes","drawnIdOf","props","target","kind","load","own","writtenNode","scrollTargetIds","pageIds","toModel","repairs","named","placed","bound","values","missing","push"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,8BAA8B,QAAQ,iDAAgD;AAC/F,SAASC,sBAAsB,QAAQ,2CAA0C;AAGjF,SAASC,oBAAoB,EAAEC,oBAAoB,QAAQ,0BAAsB;AAEjF,SAASC,eAAe,QAA8B,gCAA4B;AAElF,SACEC,4BAA4B,EAC5BC,YAAY,EACZC,8BAA8B,QAEzB,4BAAwB;AAC/B,SACEC,cAAc,EACdC,sBAAsB,EACtBC,eAAe,EACfC,sBAAsB,EACtBC,QAAQ,QAIH,uCAAmC;AAC1C,SAASC,oBAAoB,EAAEC,kBAAkB,QAAQ,6BAAyB;AAClF,SAASC,gBAAgB,EAAEC,uBAAuB,QAAQ,8BAA0B;AAEpF,SAASC,kBAAkB,QAAQ,qCAAiC;AACpE,SAASC,aAAa,EAAEC,qBAAqB,QAAQ,kCAA8B;AAEnF,SAASC,cAAc,EAAEC,oBAAoB,QAAQ,yBAAqB;AAC1E,SAASC,yBAAyB,QAAQ,+BAA2B;AAErE;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GAED,kFAAkF,GAClF,OAAO,SAASC,oBAAoBC,KAAa,EAAEC,KAAa;IAC9D,OAAO,CAAC,GAAG,EAAED,MAAME,KAAK,CAAC,GAAG,IAAI,SAAS,EAAED,QAA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,UAAUzH,MAAMO,OAAO,CAACG,IAAI,CAACmC,MAAM,CACvC,CAACrD,MAAQ,AAACqF,WAAWnC,GAAG,CAAClD,QAAQ,CAAC8H,OAAO5E,GAAG,CAAClD,QAAUuF,MAAMrC,GAAG,CAAClD,QAAQ,CAAC+H,MAAM7E,GAAG,CAAClD;QAEtF,IAAIiI,QAAQ9G,MAAM,EAAE;YAClBoD,WAAW2D,IAAI,CAAC;gBACd/B,MAAM;gBACNC,MAAM;gBACNC,SAAS,CAAC,0BAA0B,EAAE4B,QAAQtI,IAAI,CAAC,MAAM,qEAAqE,CAAC;YACjI;QACF;QACA,yEAAyE;QACzE,wEAAwE;QACxE4E,WAAW2D,IAAI,IACVxJ,0BAA0B8B,MAAMO,OAAO,EAAE;YAC1C2B,QAAQ0C;YACRhD,OAAO2E;QACT;QAGF,OAAO;YACLlF,OAAO,aAAKd;gBAASuG,MAAM5B,OAAO4B,IAAI;;YACtC/C;WACGF,YAAYC,KAAKC;IAExB;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-page-sections.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 { REUSABLE_INSTANCE_COMPONENT_ID } from '@aglyn/aglyn/app-utils/reusable-component-keys'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type { NodesMap } from '@aglyn/aglyn/types/nodes'\nimport type { AiBuildPlanScreen, AiBuildPlanSection } from '../model/ai-build-plan'\nimport { aiPageTypeDefinition, parseAiPageJobInputs } from '../model/ai-page-job'\nimport type { AiJob, AiJobPlan } from '../model/ai-jobs.types'\nimport { aiHomeScreenIds, type AiSiteInventory } from '../model/ai-site-inventory'\nimport type { AiTool } from '../providers/contract'\nimport {\n AI_REASK_OFFENDING_MAX_CHARS,\n aiAnswerTree,\n aiNodeTreeContextFromInventory,\n type AiGenerationCheck,\n} from '../runtime/ai-doctrine'\nimport {\n detectCutLines,\n detectDisagreeingNodes,\n isAiLinkElement,\n validateAiDoctrineTree,\n walkTree,\n type AiDoctrineNode,\n type AiDoctrineTreeContext,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport { AI_INSTANCE_REF_PROP, validateAiNodeTree } from '../runtime/ai-node-tree'\nimport { aiPageLinkTarget, aiPageScrollInteraction } from '../runtime/ai-page-links'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { AI_PALETTE_CATALOG } from '../runtime/ai-palette.generated'\nimport { AI_REPEAT_KEY, expandAiRepeatedItems } from '../runtime/ai-repeated-items'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { aiJobBriefLine, aiPlanReferenceLines } from './ai-job-generation'\nimport { aiPlanItemCountViolations } from './ai-job-plan-conformance'\n\n/**\n * A page built one section at a time (AGL-2907): what one section pass asks\n * for, how its answer is held to the building rules as part of the page, and\n * how it joins the page.\n *\n * Pure: no Firestore and no provider, so the page step, its specs and the\n * evals read one definition of a section.\n *\n * ── Held as part of the page ─────────────────────────────────────────────\n *\n * A section is checked twice over, by validators the doctrine already has:\n * the palette validator on the section as the model wrote it, then the\n * doctrine's whole page check on the page built so far with the section\n * added. So the page's one main, its one h1 and its heading outline, repeats\n * across sections, and its weight against the page budget are held on every\n * pass, not only on the last. The violations name the section's own nodes,\n * by the ids the model wrote, so a re-ask quotes this section and nothing\n * else — the page is never sent back.\n *\n * ── A repeated item written once (AGL-3053) ──────────────────────────────\n *\n * Where the workspace keeps no reusable components, an answer writes a\n * repeated item once and lists its copies' values, and the check draws the\n * copies before either validator reads the section (`ai-repeated-items.ts`).\n * Both then read the section as the page stores it, so the page's rules hold\n * on every copy exactly as on an item written out in full, and a finding on a\n * copy names the node the model wrote. Where the workspace keeps components\n * the same shape is written around an instance (AGL-3024), so a section of\n * many cards costs its structure once on every plan; an item that places no\n * instance is still refused there.\n */\n\n/** The section root id a pass writes, from the job and the plan section's index. */\nexport function aiPageSectionNodeId(jobId: string, index: number): string {\n return `ai-${jobId.slice(0, 12)}-section-${index + 1}`\n}\n\n/** The strict tool a section arrives through. The node map rides as JSON text, as a page's does. */\nexport const AI_PAGE_SECTION_TOOL: AiTool = {\n name: 'submit_section',\n description: 'Submit one section of the page as one flat node map.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['tree'],\n properties: {\n tree: {\n type: 'string',\n description:\n 'The section as JSON: {\"rootId\": \"<id>\", \"nodes\": {\"<id>\": {\"componentId\": \"...\", \"props\": {...}, \"sx\": {...}, \"nodes\": [\"<child id>\", ...]}}}. The root is the document wrapper (componentId \"div\") holding one Section.',\n },\n },\n },\n}\n\n/** The page step's own instructions, cached after the doctrine, with the screen palette after them. */\nexport const AI_JOB_PAGE_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n 'You build a web page one section at a time, in the order a confirmed plan gives. Each answer is ONE section: call submit_section with a flat node map whose root is the document wrapper (componentId \"div\") holding exactly one Section (section).',\n 'The first section is the top of the page and holds the page’s one h1, its title. Every later section opens with an h2, and headings below it step down one level at a time.',\n 'Place what the section’s plan line names. A component the site has is placed as an instance, never drawn again: componentId \"reusableInstance\", props {\"refId\": \"<component id>\", \"propValues\": {…}} filling the props the inventory lists. A form the site has is a Form (form) whose formId is that form’s id. Another screen of the site is linked by its screen id, with a Screen Link (muiScreenLink) or a Button (muiButton) whose screenId is that id.',\n 'Where the request says the site keeps no saved forms or reusable components, draw them in the section instead: a repeated item is written once, and a form is a Form (form) with no formId, a formName saying what it collects and a submitLabel, holding one Form Field (formField) for each answer with its fieldName, label and fieldType.',\n 'Lay the section out with a Container, a Stack or a Grid (\"container\": true, \"spacing\": 3) of Grid items sized like \"xs:12 md:4\", and size nothing with a fixed width. Colors come from the theme’s palette tokens such as primary.main, spacing from the spacing scale, and type from the text variants.',\n 'The page renders inside the site’s layout, so a section is never a header, navigation or footer.',\n 'A picture is an Image (image) with alt text that says what it should show and no src, for the site owner to fill from the media library.',\n 'Write plain, specific copy in the site’s voice, with no filler. Where the brief leaves out a fact, such as a price, a phone number or an address, write the gap in square brackets instead of inventing it.',\n ].join('\\n'),\n },\n { text: AI_PALETTE_CATALOG.screen, cacheBreakpoint: true },\n]\n\n/** A plan reference as the request names it: the id with the name it was planned under. */\nfunction referenceOf(plan: AiJobPlan, ref: string): string {\n const label = plan.labels?.[ref]\n return label ? `${ref} (\"${label}\")` : ref\n}\n\nexport interface AiPageSectionPromptInput {\n job: Pick<AiJob, 'brief' | 'inputs'>\n plan: AiJobPlan\n screen: AiBuildPlanScreen\n index: number\n /** The most elements the section may carry at this pass's answer ceiling. */\n maxElements: number\n /**\n * Whether the workspace keeps reusable components and saved forms\n * (AGL-3030); `false` asks for the section built inline. Absent is `true`.\n */\n reusableComponents?: boolean\n}\n\n/** What a section request says where the workspace keeps no reusable components or saved forms. */\nexport const AI_PAGE_SECTION_INLINE_LINE =\n 'This site keeps no saved forms or reusable components: write a repeated item once, and draw a form as a Form holding its Form Fields.'\n\n/** How a repeated item is written once, in the words a request and a re-ask share. */\nconst AI_PAGE_SECTION_REPEAT_SHAPE = `put {{1}}, {{2}}… where its copies differ, and give its outermost node \"${AI_REPEAT_KEY}\", one list of values a copy, in that order, as [[\"Title 1\", \"Text 1\"], [\"Title 2\", \"Text 2\"]]`\n\n/**\n * How a repeated item is written once (AGL-3053): the item's subtree once,\n * with placeholders where its copies differ and their values listed, which\n * the section check draws into its copies (`ai-repeated-items.ts`). It rides\n * the request of a section whose plan line shows items on a workspace that\n * keeps no reusable components, and no other: a section with nothing to repeat\n * pays nothing for it, and the cached prefix every workspace shares says only\n * that a repeated item is written once.\n */\nexport const AI_PAGE_SECTION_REPEAT_LINE = `Write a repeated item once: ${AI_PAGE_SECTION_REPEAT_SHAPE}.`\n\n/**\n * How a workspace that keeps reusable components writes a repeated item\n * (AGL-3143 §10): the shape a Free section writes, around an instance of a\n * component the section already places — the instance ONCE, `{{n}}` through\n * the values it fills, and one list of values a copy — rather than the item's\n * subtree drawn once per copy, or one instance node written per copy.\n *\n * Six cards written as six instance nodes spend their structure six times;\n * written once they spend it once, which is the difference between a section\n * that fits its ceiling and one that is cut off. A section stays ONE section\n * either way: splitting it would give the page a second h2 for the same idea,\n * which is not what the member asked for and not what its outline should say.\n *\n * ⛔ The repeated item is the GRID ITEM, not the instance. Measured live on\n * 2026-09-22: told only to \"place ONE instance … and give its outermost node\n * repeat\", the model made the instance itself the repeated node and hung it\n * straight off the Grid container. The section fitted — the ceiling failure\n * was gone — and the page was then refused by rule 12, which requires every\n * child of a Grid container to be a sized Grid item (AGL-3055). The line has\n * to name the wrapper, because \"outermost node\" reads as the instance when\n * the instance is all the request mentions.\n *\n * It rides the request of a section whose plan line shows items AND names a\n * record to place, on the same terms the repeat line rides a Free one: a\n * section with nothing to repeat, or nothing to repeat it FROM, pays nothing\n * for it.\n *\n * ## Why a paid section could not be built without it (AGL-3024)\n *\n * The Free path is reconciled at both ends — its plan is held to the sections\n * its wall pays for (AGL-3070) and its request is shown the repeat shape\n * (AGL-3053). The paid path was reconciled at neither: `AI_BUILD_PLAN_LIMITS`\n * lets a plan promise up to `items: 500` in one section, the pass that builds\n * it fits `aiJobPageSectionMaxElements` — fifteen at the balanced tier — and\n * the request said only how many elements to keep under, never how to get\n * there. A six-card grid measured live on 2026-09-21 was drawn inline, ran\n * past its ceiling, and was cut off; the re-ask then said to place an instance\n * \"of a component the site has\" without naming one, so it was cut off too, and\n * `AI_GENERATION_MAX_ATTEMPTS` ended the job with no page. A four-card grid on\n * the same site had fitted, which is why this went unseen. Naming the shape\n * was not enough on its own: `ai-repeated-items.ts` refused `repeat` outright\n * on such a workspace, so the only shape the request could ask for was the\n * expensive one.\n *\n * ⛔ This does NOT make the plan and the pass agree about what fits — a plan\n * may still promise more items than any ceiling can carry, and this line only\n * gives the pass its cheapest way to try. That bound belongs on the plan step\n * and is deliberately not taken here.\n */\nexport const AI_PAGE_SECTION_INSTANCE_LINE = `Write a repeated item once: put ONE instance of the component this section places inside ONE Grid item sized like \"xs:12 sm:6 md:4\", and repeat THAT GRID ITEM rather than the instance — every child of a Grid container is itself a Grid item. Put {{1}}, {{2}}… where the copies differ, and give the Grid item \"${AI_REPEAT_KEY}\", one list of values a copy, in that order, as [[\"Title 1\", \"Text 1\"], [\"Title 2\", \"Text 2\"]].`\n\n/**\n * What a pass whose answer ran past its ceiling is told makes a section\n * smaller (AGL-3042): fewer elements, down to the budget the request gave,\n * shorter copy, and a repeated item drawn no more than once — placed as an\n * instance where the workspace keeps reusable components, and written once\n * where it keeps none (AGL-3053), with the shape spelled out, since a section\n * whose plan line showed no items was never told it. It rides the re-ask,\n * never the first request, so a pass that fits sends no byte more.\n */\nexport function aiPageSectionSmaller(input: Pick<AiPageSectionPromptInput, 'maxElements' | 'reusableComponents'>): string {\n return input.reusableComponents === false\n ? `Make it smaller: use fewer elements, at most ${input.maxElements}; write shorter copy; and write a repeated item once instead of drawing it again: ${AI_PAGE_SECTION_REPEAT_SHAPE}.`\n : `Make it smaller: use fewer elements, at most ${input.maxElements}; write shorter copy; and write a repeated item once instead of drawing it again: put ONE instance of a component the site has inside ONE Grid item sized like \"xs:12 sm:6 md:4\", and repeat that Grid item — ${AI_PAGE_SECTION_REPEAT_SHAPE}.`\n}\n\n/** One pass's user turn: the page, the brief, the plan, this section and what is built above it. */\nexport function aiPageSectionPrompt(input: AiPageSectionPromptInput): string {\n const { job, plan, screen, index } = input\n const inputs = parseAiPageJobInputs(job.inputs)\n const type = typeof inputs === 'string' ? null : aiPageTypeDefinition(inputs.pageType)\n const section = screen.sections[index] as AiBuildPlanSection\n const places = section.uses.length\n ? ` It places ${section.uses.map((ref) => referenceOf(plan, ref)).join(', ')}.`\n : ''\n const items = section.items ? ` It shows ${section.items} items.` : ''\n const built = screen.sections.slice(0, index).map((entry, position) => `${position + 1}. ${entry.name}`)\n return [\n `Page: \"${screen.title}\" at ${screen.slug}`,\n ...(type ? [`Page type: ${type.purpose}`] : []),\n aiJobBriefLine(job),\n ...aiPlanReferenceLines(plan),\n `Build section ${index + 1} of ${screen.sections.length}: \"${section.name}\".${places}${items}`,\n built.length\n ? `Already built, above it: ${built.join('; ')}. The page’s h1 is in section 1.`\n : 'Nothing is built yet: this section holds the page’s h1.',\n ...(input.reusableComponents === false\n ? [AI_PAGE_SECTION_INLINE_LINE, ...(section.items ? [AI_PAGE_SECTION_REPEAT_LINE] : [])]\n : section.items && section.uses.length\n ? [AI_PAGE_SECTION_INSTANCE_LINE]\n : []),\n `Keep this section to at most ${input.maxElements} elements.`,\n ].join('\\n')\n}\n\n/** A validated section: its nodes keyed as the page stores them, its root under the page root. */\nexport interface AiPageSection {\n rootId: string\n nodes: NodesMap\n /** The page's weight with the section added, as the doctrine measured it. */\n load: AiLoadEstimate | null\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** A page with nothing on it yet: the document wrapper. */\nexport function aiEmptyPage(): NodesMap {\n return {\n [CANVAS_ROOT_ELEMENT_ID]: {\n $id: CANVAS_ROOT_ELEMENT_ID,\n componentId: 'div',\n parentId: null,\n nodes: [],\n },\n } as unknown as NodesMap\n}\n\n/**\n * The page with a section in its plan position: after every section with a\n * lower index and before every one with a higher, the page's other children\n * — whatever a member placed — kept where they are. A section already on the\n * page is replaced, never doubled.\n */\nexport function aiPageWithSection(\n page: NodesMap,\n section: AiPageSection,\n sectionIds: readonly string[],\n): NodesMap {\n const nodes: Record<string, Record<string, unknown>> = {}\n const previous = (page as unknown as Record<string, Record<string, unknown>>)[section.rootId]\n const replaced = new Set<string>()\n if (previous) {\n for (const { id } of walkTree({\n rootId: section.rootId,\n nodes: page as unknown as Record<string, AiDoctrineNode>,\n })) {\n replaced.add(id)\n }\n }\n for (const [id, node] of Object.entries(page)) {\n if (!replaced.has(id)) nodes[id] = { ...(node as unknown as Record<string, unknown>) }\n }\n const root = nodes[CANVAS_ROOT_ELEMENT_ID] ?? (aiEmptyPage()[CANVAS_ROOT_ELEMENT_ID] as unknown as Record<string, unknown>)\n const children = (Array.isArray(root['nodes']) ? (root['nodes'] as string[]) : []).filter(\n (id) => id !== section.rootId,\n )\n const order = new Map(sectionIds.map((id, position) => [id, position]))\n const at = order.get(section.rootId) ?? sectionIds.length\n const before = children.findIndex((id) => (order.get(id) ?? -1) > at)\n children.splice(before === -1 ? children.length : before, 0, section.rootId)\n nodes[CANVAS_ROOT_ELEMENT_ID] = { ...root, nodes: children }\n for (const [id, node] of Object.entries(section.nodes)) {\n nodes[id] = { ...(node as unknown as Record<string, unknown>) }\n }\n return nodes as unknown as NodesMap\n}\n\n/**\n * What a tree generated against this inventory may reference, the brand it is\n * held to, where the workspace keeps no reusable components or saved forms\n * (AGL-3030) that the page is built inline, and the sections its plan names,\n * which a link may take a visitor to (AGL-3097).\n */\nexport function aiPageCheckContext(\n inventory: AiSiteInventory | null,\n options: { reusableComponents?: boolean; sections?: readonly string[] } = {},\n): AiDoctrineTreeContext {\n return {\n brand: inventory?.theme ? { colors: inventory.theme.colors, fonts: inventory.theme.fonts } : null,\n ...aiNodeTreeContextFromInventory(inventory),\n homeScreenIds: aiHomeScreenIds(inventory),\n ...(options.reusableComponents === false ? { reusableComponents: false } : {}),\n ...(options.sections?.length ? { pageSections: options.sections } : {}),\n }\n}\n\nexport interface AiPageSectionCheckInput {\n /** The page as stored so far; an empty page on the first pass. */\n page: NodesMap\n /** Every section root id of the plan, in order. */\n sectionIds: readonly string[]\n index: number\n context: AiDoctrineTreeContext\n /**\n * The plan line this pass answers for: what it places by inventory id, and\n * how many items it promised, which the answer is held to (AGL-3024).\n */\n section: Pick<AiBuildPlanSection, 'name' | 'uses' | 'items'>\n inventory: AiSiteInventory | null\n}\n\n/** The parts of an answer the violations name, as the model wrote them, capped as the doctrine caps a re-ask. */\nfunction offendingOf(raw: unknown, violations: readonly AiDoctrineViolation[]): { offending?: Record<string, unknown> } {\n const rawNodes = isRecord(raw) && isRecord(raw['nodes']) ? raw['nodes'] : {}\n const offending: Record<string, unknown> = {}\n let used = 2\n for (const id of new Set(violations.flatMap((violation) => violation.nodeIds ?? []))) {\n if (rawNodes[id] === undefined) continue\n const size = JSON.stringify(rawNodes[id]).length + id.length + 4\n if (used + size > AI_REASK_OFFENDING_MAX_CHARS) break\n offending[id] = rawNodes[id]\n used += size\n }\n return Object.keys(offending).length ? { offending } : {}\n}\n\n/**\n * The check a section's answer is held to: a repeated item written once drawn\n * into its copies (AGL-3053), then the palette validator on the section, with\n * any line it cut at its ceiling refused (AGL-3076), the doctrine's page check\n * on the page with the section added, and the plan line — every component it\n * names placed as an instance, every form bound by its id (rule 7), and as\n * many items as it promised (AGL-3024). Violations\n * name the section's own nodes by the ids the MODEL wrote, and a copy's nodes\n * by the item's; one that names only nodes an earlier pass stored belongs to\n * the page rather than to this answer, and is left to the last pass (AGL-3078).\n */\nexport function aiPageSectionCheck(input: AiPageSectionCheckInput): AiGenerationCheck<AiPageSection> {\n const sectionId = input.sectionIds[input.index]\n const components = new Set((input.inventory?.components ?? []).map((row) => row.id))\n const forms = new Set((input.inventory?.forms ?? []).map((row) => row.id))\n return (answer) => {\n const raw = aiAnswerTree(answer)\n // Before anything is drawn or dropped: a repeated item written and never\n // placed is content the section loses silently, and a child named and\n // never written ends the pass with nothing to answer (AGL-3143).\n const disagreeing = detectDisagreeingNodes(raw)\n if (disagreeing.length) {\n return { value: null, violations: disagreeing, ...offendingOf(raw, disagreeing) }\n }\n const drawn = expandAiRepeatedItems(raw, { inline: input.context.reusableComponents === false, noun: 'section' })\n if (drawn.ok === false) {\n return { value: null, violations: drawn.violations, ...offendingOf(raw, drawn.violations) }\n }\n // Every id below is the drawn tree's; a copy's leads back to the node the model wrote.\n const written = (id: string): string => drawn.sourceIds[id] ?? id\n const validated = validateAiNodeTree(drawn.tree, 'screen', input.context)\n if (validated.ok === false) {\n return {\n value: null,\n violations: [\n {\n rule: null,\n code: `tree-${validated.code}`,\n message: 'The answer could not be used as a section.',\n detail: validated.error,\n },\n ],\n }\n }\n const wrapper = validated.nodes[validated.rootId] as unknown as AiDoctrineNode | undefined\n const top = (wrapper?.nodes ?? []).filter((id) => validated.nodes[id])\n const sectionNode = top.length === 1 ? (validated.nodes[top[0]] as unknown as AiDoctrineNode) : null\n if (!sectionNode || sectionNode.componentId !== 'section') {\n return {\n value: null,\n violations: [\n {\n rule: null,\n code: 'section-shape',\n message: 'Answer with exactly one Section element inside the document wrapper.',\n },\n ],\n }\n }\n\n // The section's root takes its plan id, so a pass run again finds it, and\n // hangs under the page root; every other minted id stays as minted.\n const minted = top[0]\n const modelIds: Record<string, string> = Object.fromEntries(\n Object.entries(validated.sourceIds).map(([id, source]) => [id, written(source)]),\n )\n modelIds[sectionId] = written(validated.sourceIds[minted] ?? minted)\n const sectionNodes: Record<string, Record<string, unknown>> = {}\n for (const { id, node } of walkTree({\n rootId: minted,\n nodes: validated.nodes as unknown as Record<string, AiDoctrineNode>,\n })) {\n const stored = { ...(node as unknown as Record<string, unknown>) }\n if (id === minted) {\n stored['$id'] = sectionId\n stored['parentId'] = CANVAS_ROOT_ELEMENT_ID\n } else if (stored['parentId'] === minted) {\n stored['parentId'] = sectionId\n }\n sectionNodes[id === minted ? sectionId : id] = stored\n }\n const drawnNodes = isRecord(drawn.tree) && isRecord(drawn.tree['nodes']) ? drawn.tree['nodes'] : {}\n // What the model wrote of one of the section's nodes, by the id the page stores it under.\n const drawnIdOf = (stored: string): string =>\n validated.sourceIds[stored === sectionId ? minted : stored] ?? stored\n // A link that names a section of this page carries the platform's Scroll to\n // element interaction to that section's root, whose id is minted from the\n // plan before the section is built (AGL-3097).\n const sections = input.context.pageSections ?? []\n for (const [id, node] of Object.entries(sectionNodes)) {\n const props = isRecord(node['props']) ? node['props'] : {}\n if (!isAiLinkElement(node['componentId']) || props['screenId'] || props['href']) continue\n const target = aiPageLinkTarget(drawnNodes[drawnIdOf(id)], sections)\n if (target?.kind === 'section') {\n node['interactions'] = [aiPageScrollInteraction(input.sectionIds[target.section], sections[target.section])]\n }\n }\n const section: AiPageSection = { rootId: sectionId, nodes: sectionNodes as unknown as NodesMap, load: null }\n\n const page = aiPageWithSection(input.page, section, input.sectionIds)\n const own = new Set(Object.keys(sectionNodes))\n // The page check reads the section as the page stores it, where the palette\n // validator has already dropped what it could not read, such as a\n // `container` written as text or a link's `scrollTo`; what the model wrote\n // of each of the section's nodes is read from the section as it was drawn\n // (AGL-3078). A link the page already carries to one of its section roots\n // goes there, whichever pass wrote it (AGL-3097).\n const report = validateAiDoctrineTree({ rootId: CANVAS_ROOT_ELEMENT_ID, nodes: page }, 'page', {\n ...input.context,\n writtenNode: (id) => (own.has(id) ? drawnNodes[drawnIdOf(id)] : undefined),\n scrollTargetIds: input.sectionIds,\n })\n // The page check mints its ids afresh: its map leads back to the page's\n // ids, and the section's own lead back to the model's.\n const pageIds = report.tree?.sourceIds ?? {}\n const toModel = (id: string): string | null => {\n const stored = pageIds[id] ?? id\n return own.has(stored) ? (modelIds[stored] ?? stored) : null\n }\n // The page check reads the section as it is stored, where a line the\n // palette validator cut is already cut, so the cut is read from the\n // section's own validation, first (AGL-3076). Copies of one item name one\n // node the model wrote, once.\n //\n // A PASS ANSWERS ONLY FOR THE SECTION IT WROTE (AGL-3078). The page check\n // reads the whole page, so it also names nodes an earlier pass stored; the\n // model is not shown those and cannot mend them, so a finding that names\n // none of this section's nodes is not held against this answer. Dropping\n // it neither hides nor forgives it: the last pass runs the same check on\n // the finished page, where every node is the page's and the review names\n // each one and outlines it. Kept, such a finding would re-ask the model\n // for a node it never saw, refuse the same answer twice, and stop the page\n // with findings whose ids all filtered away — no node ids, and so no\n // outline either.\n const violations: AiDoctrineViolation[] = [\n ...detectCutLines(validated.repairs, drawnNodes, written),\n ...report.violations.flatMap((violation) => {\n if (!violation.nodeIds?.length) return [violation]\n const named = [...new Set(violation.nodeIds.map(toModel).filter((id): id is string => id !== null))]\n return named.length ? [{ ...violation, nodeIds: named }] : []\n }),\n ]\n\n const placed = new Set<string>()\n const bound = new Set<string>()\n for (const node of Object.values(sectionNodes)) {\n const props = isRecord(node['props']) ? node['props'] : {}\n if (node['componentId'] === REUSABLE_INSTANCE_COMPONENT_ID && typeof props[AI_INSTANCE_REF_PROP] === 'string') {\n placed.add(props[AI_INSTANCE_REF_PROP] as string)\n }\n if (node['componentId'] === 'form' && typeof props['formId'] === 'string') bound.add(props['formId'])\n }\n const missing = input.section.uses.filter(\n (ref) => (components.has(ref) && !placed.has(ref)) || (forms.has(ref) && !bound.has(ref)),\n )\n if (missing.length) {\n violations.push({\n rule: 7,\n code: 'plan-reuse-not-placed',\n message: `The confirmed plan places ${missing.join(', ')} in this section, and the section does not. Place each one by its id.`,\n })\n }\n // The count the plan promised, against the section as the page stores it\n // (AGL-3024): the prompt states it, and until now nothing read it back.\n violations.push(\n ...aiPlanItemCountViolations(input.section, {\n rootId: sectionId,\n nodes: sectionNodes as unknown as Record<string, AiDoctrineNode>,\n }),\n )\n\n return {\n value: { ...section, load: report.load },\n violations,\n ...offendingOf(raw, violations),\n }\n }\n}\n"],"names":["REUSABLE_INSTANCE_COMPONENT_ID","CANVAS_ROOT_ELEMENT_ID","aiPageTypeDefinition","parseAiPageJobInputs","aiHomeScreenIds","AI_REASK_OFFENDING_MAX_CHARS","aiAnswerTree","aiNodeTreeContextFromInventory","detectCutLines","detectDisagreeingNodes","isAiLinkElement","validateAiDoctrineTree","walkTree","AI_INSTANCE_REF_PROP","validateAiNodeTree","aiPageLinkTarget","aiPageScrollInteraction","AI_PALETTE_CATALOG","AI_REPEAT_KEY","expandAiRepeatedItems","aiJobBriefLine","aiPlanReferenceLines","aiPlanItemCountViolations","aiPageSectionNodeId","jobId","index","slice","AI_PAGE_SECTION_TOOL","name","description","strict","inputSchema","type","additionalProperties","required","properties","tree","AI_JOB_PAGE_INSTRUCTIONS","text","join","screen","cacheBreakpoint","referenceOf","plan","ref","label","labels","AI_PAGE_SECTION_INLINE_LINE","AI_PAGE_SECTION_REPEAT_SHAPE","AI_PAGE_SECTION_REPEAT_LINE","AI_PAGE_SECTION_INSTANCE_LINE","aiPageSectionSmaller","input","reusableComponents","maxElements","aiPageSectionPrompt","job","inputs","pageType","section","sections","places","uses","length","map","items","built","entry","position","title","slug","purpose","isRecord","value","Array","isArray","aiEmptyPage","$id","componentId","parentId","nodes","aiPageWithSection","page","sectionIds","order","previous","rootId","replaced","Set","id","add","node","Object","entries","has","root","children","filter","Map","at","get","before","findIndex","splice","aiPageCheckContext","inventory","options","brand","theme","colors","fonts","homeScreenIds","pageSections","offendingOf","raw","violations","rawNodes","offending","used","flatMap","violation","nodeIds","undefined","size","JSON","stringify","keys","aiPageSectionCheck","sectionId","components","row","forms","answer","validated","report","disagreeing","drawn","inline","context","noun","ok","written","sourceIds","rule","code","message","detail","error","wrapper","top","sectionNode","minted","modelIds","fromEntries","source","sectionNodes","stored","drawnNodes","drawnIdOf","props","target","kind","load","own","writtenNode","scrollTargetIds","pageIds","toModel","repairs","named","placed","bound","values","missing","push"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,8BAA8B,QAAQ,iDAAgD;AAC/F,SAASC,sBAAsB,QAAQ,2CAA0C;AAGjF,SAASC,oBAAoB,EAAEC,oBAAoB,QAAQ,0BAAsB;AAEjF,SAASC,eAAe,QAA8B,gCAA4B;AAElF,SACEC,4BAA4B,EAC5BC,YAAY,EACZC,8BAA8B,QAEzB,4BAAwB;AAC/B,SACEC,cAAc,EACdC,sBAAsB,EACtBC,eAAe,EACfC,sBAAsB,EACtBC,QAAQ,QAIH,uCAAmC;AAC1C,SAASC,oBAAoB,EAAEC,kBAAkB,QAAQ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-data-admin/server/duplicate-resource';
|
|
18
|
-
import type { AiJob, AiJobPlan } from '../model/ai-jobs.types';
|
|
18
|
+
import type { AiJob, AiJobPlan, AiJobReview } from '../model/ai-jobs.types';
|
|
19
19
|
import { type AiTemplateSubjectDefinition } from '../model/ai-template-subjects';
|
|
20
20
|
import { type AiValidatedTree } from '../runtime/ai-doctrine';
|
|
21
21
|
import { type AiDoctrineViolation } from '../runtime/ai-doctrine-validators';
|
|
@@ -99,6 +99,27 @@ export interface AiJobTemplateStepDeps {
|
|
|
99
99
|
/** The starter examples block; built from the starters once per process otherwise. */
|
|
100
100
|
examples?: () => AiSystemBlock;
|
|
101
101
|
}
|
|
102
|
+
/**
|
|
103
|
+
* The binding tokens the confirmed plan gives the template, against the
|
|
104
|
+
* template a COPY actually produced (AGL-3024); `null` when the copy keeps
|
|
105
|
+
* the plan, or when the plan promised no token to keep.
|
|
106
|
+
*
|
|
107
|
+
* The same hole as `aiCopiedLayoutReview` and `aiCopiedPageReview`, on the
|
|
108
|
+
* third kind that can start from a duplicate. The generate path already holds
|
|
109
|
+
* a built template to `aiPlanTemplateTokenViolations`; the copy path reached
|
|
110
|
+
* none of it, so a plan reading "duplicate it and bind the author's photo"
|
|
111
|
+
* got the duplicate and reported Done.
|
|
112
|
+
*
|
|
113
|
+
* A copy that cannot be read back settles nothing, and a promise this step
|
|
114
|
+
* cannot settle is reviewed by a person rather than reported as kept.
|
|
115
|
+
*/
|
|
116
|
+
export declare function aiCopiedTemplateReview(firestore: FirebaseFirestore.Firestore, input: {
|
|
117
|
+
hostId: string;
|
|
118
|
+
id: string;
|
|
119
|
+
name: string;
|
|
120
|
+
plan: AiJobPlan | null;
|
|
121
|
+
definition: AiTemplateSubjectDefinition;
|
|
122
|
+
}): Promise<AiJobReview | null>;
|
|
102
123
|
export declare function createAiJobTemplateStep(deps?: AiJobTemplateStepDeps): AiJobStepRunner;
|
|
103
124
|
export declare const runAiJobTemplateStep: AiJobStepRunner;
|
|
104
125
|
/** Registers the template step and the check a template job passes before it is created or resumed. */
|
|
@@ -17,6 +17,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
17
17
|
*/ import { hostCollectionKind } from "@aglyn/aglyn/app-utils/collection-kind";
|
|
18
18
|
import { normalizeScreenSlug } from "@aglyn/aglyn/app-utils/screen-route";
|
|
19
19
|
import { duplicateResource } from "@aglyn/tenant-data-admin/server/duplicate-resource";
|
|
20
|
+
import { CANVAS_ROOT_ELEMENT_ID } from "@aglyn/aglyn/foundation/constants/canvas";
|
|
20
21
|
import { AI_TEMPLATE_SUBJECT_DEFINITIONS, AI_TEMPLATE_SUBJECTS, aiBindingTokensIn, aiTemplateAddressTokens, parseAiTemplateJobInputs } from "../model/ai-template-subjects.js";
|
|
21
22
|
import { AI_STEP_TIERS } from "../providers/catalog.js";
|
|
22
23
|
import { AI_ROUTING_TABLE, aiModelForStep } from "../providers/routing.js";
|
|
@@ -27,9 +28,9 @@ import { aiTemplateExamplesSystemBlock } from "../runtime/ai-template-examples.j
|
|
|
27
28
|
import { readSiteInventory } from "../runtime/site-inventory.js";
|
|
28
29
|
import { registerAiJobAdmission } from "./ai-job-admission.js";
|
|
29
30
|
import { aiJobDraftId } from "./ai-job-draft-ids.js";
|
|
30
|
-
import { aiDraftAdmissionRefusal, aiDraftAllowanceRefusal, aiSiteSubdomain, readAiDraft, writeAiDraft } from "./ai-job-drafts.js";
|
|
31
|
+
import { aiDraftAdmissionRefusal, aiDraftAllowanceRefusal, aiSiteSubdomain, readAiDraft, readAiTemplateDraftNodes, writeAiDraft } from "./ai-job-drafts.js";
|
|
31
32
|
import { aiConfirmedPlan, aiDoctrineReview, aiGenerationSpent, aiJobBriefLine, aiLimitReview, aiModelNodeIds, aiPlacedComponentIds, aiPlanCreation, aiPlanReferenceLines, aiPlanReuseViolations, aiUnspentOutcome } from "./ai-job-generation.js";
|
|
32
|
-
import { aiPlanTemplateTokenViolations } from "./ai-job-plan-conformance.js";
|
|
33
|
+
import { aiPlannedTemplateTokens, aiPlanTemplateTokenViolations } from "./ai-job-plan-conformance.js";
|
|
33
34
|
import { aiJobStepBudget } from "./ai-job-budget.js";
|
|
34
35
|
import { registerAiJobStep } from "./ai-jobs.js";
|
|
35
36
|
/**
|
|
@@ -230,6 +231,44 @@ import { registerAiJobStep } from "./ai-jobs.js";
|
|
|
230
231
|
});
|
|
231
232
|
};
|
|
232
233
|
}
|
|
234
|
+
/**
|
|
235
|
+
* The binding tokens the confirmed plan gives the template, against the
|
|
236
|
+
* template a COPY actually produced (AGL-3024); `null` when the copy keeps
|
|
237
|
+
* the plan, or when the plan promised no token to keep.
|
|
238
|
+
*
|
|
239
|
+
* The same hole as `aiCopiedLayoutReview` and `aiCopiedPageReview`, on the
|
|
240
|
+
* third kind that can start from a duplicate. The generate path already holds
|
|
241
|
+
* a built template to `aiPlanTemplateTokenViolations`; the copy path reached
|
|
242
|
+
* none of it, so a plan reading "duplicate it and bind the author's photo"
|
|
243
|
+
* got the duplicate and reported Done.
|
|
244
|
+
*
|
|
245
|
+
* A copy that cannot be read back settles nothing, and a promise this step
|
|
246
|
+
* cannot settle is reviewed by a person rather than reported as kept.
|
|
247
|
+
*/ export async function aiCopiedTemplateReview(firestore, input) {
|
|
248
|
+
const { tokens, unreadable } = aiPlannedTemplateTokens(input.plan, input.definition);
|
|
249
|
+
if (!tokens.length && !unreadable.length) return null;
|
|
250
|
+
const stored = await readAiTemplateDraftNodes(firestore, {
|
|
251
|
+
hostId: input.hostId,
|
|
252
|
+
id: input.id
|
|
253
|
+
});
|
|
254
|
+
const nodes = stored != null ? stored : {};
|
|
255
|
+
if (!nodes[CANVAS_ROOT_ELEMENT_ID]) {
|
|
256
|
+
return {
|
|
257
|
+
reason: 'doctrine',
|
|
258
|
+
message: `"${input.name}" was copied from the template the plan names, and this job could not read the copy back to check it shows what the plan gives it. Open the template and check it before you apply it.`,
|
|
259
|
+
findings: []
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
const violations = aiPlanTemplateTokenViolations(input.plan, input.definition, {
|
|
263
|
+
rootId: CANVAS_ROOT_ELEMENT_ID,
|
|
264
|
+
nodes
|
|
265
|
+
});
|
|
266
|
+
if (!violations.length) return null;
|
|
267
|
+
return aiDoctrineReview({
|
|
268
|
+
message: `"${input.name}" is a copy of the template the plan names, and a copy is all it is: ${violations[0].message}`,
|
|
269
|
+
violations
|
|
270
|
+
});
|
|
271
|
+
}
|
|
233
272
|
export function createAiJobTemplateStep(deps = {}) {
|
|
234
273
|
var _deps_readInventory, _deps_duplicate, _deps_readCollection, _deps_examples;
|
|
235
274
|
const readInventory = (_deps_readInventory = deps.readInventory) != null ? _deps_readInventory : readSiteInventory;
|
|
@@ -302,6 +341,18 @@ export function createAiJobTemplateStep(deps = {}) {
|
|
|
302
341
|
});
|
|
303
342
|
if (copy.ok) {
|
|
304
343
|
const hostSubdomain = await aiSiteSubdomain(firestore, hostId);
|
|
344
|
+
// The copy is reported with what the plan promised of it read back
|
|
345
|
+
// (AGL-3024): this branch generates nothing, so nothing else can.
|
|
346
|
+
const review = await aiCopiedTemplateReview(firestore, {
|
|
347
|
+
hostId,
|
|
348
|
+
id: copy.id,
|
|
349
|
+
name: copy.name,
|
|
350
|
+
plan,
|
|
351
|
+
definition
|
|
352
|
+
});
|
|
353
|
+
if (review) return aiUnspentOutcome(model, {
|
|
354
|
+
review
|
|
355
|
+
});
|
|
305
356
|
return aiUnspentOutcome(model, {
|
|
306
357
|
outputs: [
|
|
307
358
|
output({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-template-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 { hostCollectionKind } from '@aglyn/aglyn/app-utils/collection-kind'\nimport { normalizeScreenSlug } from '@aglyn/aglyn/app-utils/screen-route'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport { duplicateResource } from '@aglyn/tenant-data-admin/server/duplicate-resource'\nimport type { AiJob, AiJobOutput, AiJobPlan } from '../model/ai-jobs.types'\nimport {\n AI_TEMPLATE_SUBJECT_DEFINITIONS,\n AI_TEMPLATE_SUBJECTS,\n aiBindingTokensIn,\n aiTemplateAddressTokens,\n parseAiTemplateJobInputs,\n type AiTemplateSubjectDefinition,\n} from '../model/ai-template-subjects'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport {\n aiDoctrineTreeTool,\n runValidatedGeneration,\n type AiValidatedTree,\n} from '../runtime/ai-doctrine'\nimport {\n walkTree,\n type AiDoctrineNode,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { AI_PALETTE } from '../runtime/ai-palette.generated'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { aiTemplateExamplesSystemBlock } from '../runtime/ai-template-examples'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport { registerAiJobAdmission, type AiJobAdmission } from './ai-job-admission'\nimport { aiJobDraftId } from './ai-job-draft-ids'\nimport {\n aiDraftAdmissionRefusal,\n aiDraftAllowanceRefusal,\n aiSiteSubdomain,\n readAiDraft,\n writeAiDraft,\n type AiDraftRecord,\n} from './ai-job-drafts'\nimport {\n aiConfirmedPlan,\n aiDoctrineReview,\n aiGenerationSpent,\n aiJobBriefLine,\n aiLimitReview,\n aiModelNodeIds,\n aiPlacedComponentIds,\n aiPlanCreation,\n aiPlanReferenceLines,\n aiPlanReuseViolations,\n aiUnspentOutcome,\n} from './ai-job-generation'\nimport { aiPlanTemplateTokenViolations } from './ai-job-plan-conformance'\nimport type { AiJobStepRunner } from './ai-job-text-step'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The template step (AGL-2909): the generation step of a `template` job, run\n * once a member confirmed the job's plan.\n *\n * It builds ONE page template — the page a site renders once per record: a\n * content collection's entry, a product, an author — through\n * `runValidatedGeneration('template', …)`. Everything that differs per\n * record is a binding token from the subject's vocabulary\n * (`model/ai-template-subjects.ts`), which is the list the besigner's insert\n * picker offers for that page; a link or media prop may hold one of those\n * tokens whole, which the palette validator admits only because this door\n * names them. The door adds one check of its own through `extend` (rule 8):\n * no token the page does not fill, an h1 bound to the subject's title, and no\n * block that fills itself only on another subject's page.\n *\n * The model is shown the platform's starter pages as examples, in a cached\n * block (`runtime/ai-template-examples.ts`), and writes against them.\n *\n * The template lands in the site's library as a new draft\n * (`ai-job-drafts.ts`), inert until a member uses it: bound to no\n * collection, set as no product or author page, served nowhere. A plan that\n * starts from a copy of a template the site has gets that copy instead.\n */\n\n/** The longest answer a template may run to; the tree is held to the template budget either way. */\nexport const AI_JOB_TEMPLATE_MAX_TOKENS = AI_ROUTING_TABLE['job.template'].maxTokens\n\n/**\n * The template step's time (AGL-3035, AGL-3036): its two inventory-lookup\n * rounds, its answer and its re-ask at the routing table's ceiling on the tier\n * `job.template` is served from, fitted to what a beat can give a step. It\n * runs on the job beat, never at an inline door, and asks for no more of the\n * ceiling than fits that time on the model it runs.\n */\nexport const AI_JOB_TEMPLATE_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.template'],\n maxTokens: AI_JOB_TEMPLATE_MAX_TOKENS,\n})\n\n/** The least time one template step needs before it starts. */\nexport const AI_JOB_TEMPLATE_STEP_MINIMUM_MS = AI_JOB_TEMPLATE_STEP_BUDGET.minimumMs\n\n/** The template step's own instructions, cached after the doctrine and before the examples. */\nexport const AI_JOB_TEMPLATE_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n 'You build one page template: the page a website renders once for each record it keeps, such as each entry of a content collection, each product or each author. Answer with submit_template: the whole page as one flat node map.',\n 'Everything that differs from one record to the next is a binding token, never typed copy. The request names what the page is for, the tokens that page fills and the blocks that fill themselves there; bind only those tokens.',\n 'The page’s one h1 holds the title token the request names. Copy that reads the same on every record, such as a section heading, is written in the site’s voice.',\n 'A link or media prop holds exactly one token from the request’s link and media tokens, such as an Image whose src is {{entry.coverImage}}; its alt text may combine words and tokens.',\n 'The page renders inside the site’s layout, so it carries no header, navigation or footer of its own.',\n ].join('\\n'),\n },\n]\n\n/** A content collection an entry template is for, as the prompt and the draft name it. */\nexport interface AiTemplateCollection {\n id: string\n name: string\n slug: string\n}\n\n/** The content collection by that id on the site, or `null` when there is none. */\nexport async function readAiTemplateCollection(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n collectionId: string,\n): Promise<AiTemplateCollection | null> {\n const snapshot = await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('collections')\n .doc(collectionId)\n .get()\n if (!snapshot.exists) return null\n const data = (snapshot.data() ?? {}) as Record<string, unknown>\n if (hostCollectionKind(data) !== 'content') return null\n const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '')\n const slug = text(data['slug'])\n return {\n id: collectionId,\n name: text(data['displayName']) || text(data['name']) || slug || collectionId,\n slug,\n }\n}\n\n/** The template's name: the plan's, else the collection's or the subject's. */\nexport function aiTemplateDraftName(\n definition: AiTemplateSubjectDefinition,\n collection: AiTemplateCollection | null,\n planned: string | null | undefined,\n): string {\n return planned || (collection ? `${collection.name} entry template` : definition.defaultName)\n}\n\n/** The address Use template offers for the page it creates. */\nexport function aiTemplateDraftSlug(\n definition: AiTemplateSubjectDefinition,\n collection: AiTemplateCollection | null,\n): string | null {\n return (\n normalizeScreenSlug(\n collection\n ? `${collection.slug || collection.id}-entry-template`\n : `${definition.subject}-page-template`,\n ) ?? null\n )\n}\n\n/** The template job as the generation's user turn. */\nexport function aiJobTemplatePrompt(\n job: Pick<AiJob, 'brief'>,\n definition: AiTemplateSubjectDefinition,\n collection: AiTemplateCollection | null,\n plan: AiJobPlan | null,\n name: string,\n): string {\n const of = collection\n ? ` of the \"${collection.name}\" collection${collection.slug ? ` (/${collection.slug})` : ''}`\n : ''\n return [\n `Template name: ${name}`,\n `The page is for ${definition.noun}${of}.`,\n `Title token: ${definition.titleToken}`,\n `Tokens this page fills: ${definition.tokens.map((entry) => `${entry.token} ${entry.label}`).join('; ')}`,\n `Link and media tokens: ${aiTemplateAddressTokens(definition).join(', ')}`,\n definition.blocks.length\n ? `Blocks that fill themselves on this page: ${definition.blocks.join(', ')}`\n : 'No block fills itself on this page: bind the tokens.',\n aiJobBriefLine(job),\n ...aiPlanReferenceLines(plan),\n ].join('\\n')\n}\n\n/** Which subject's page each self-filling block belongs to. */\nconst BLOCK_SUBJECTS = new Map<string, AiTemplateSubjectDefinition>(\n AI_TEMPLATE_SUBJECTS.flatMap((subject) =>\n AI_TEMPLATE_SUBJECT_DEFINITIONS[subject].blocks.map(\n (block) => [block, AI_TEMPLATE_SUBJECT_DEFINITIONS[subject]] as const,\n ),\n ),\n)\n\n/** Every string a prop value holds, however deeply. */\nfunction stringsIn(value: unknown, out: string[] = []): string[] {\n if (typeof value === 'string') out.push(value)\n else if (Array.isArray(value)) for (const inner of value) stringsIn(inner, out)\n else if (value && typeof value === 'object') {\n for (const inner of Object.values(value as Record<string, unknown>)) stringsIn(inner, out)\n }\n return out\n}\n\n/** The page's title: a Typography that renders as an h1. */\nfunction isPageTitle(node: AiDoctrineNode): boolean {\n if (node.componentId !== 'muiTypography') return false\n const element = typeof node.props?.['component'] === 'string' ? String(node.props['component']) : ''\n return (element || String(node.props?.['variant'] ?? '')) === 'h1'\n}\n\n/**\n * The template door's check on a tree the doctrine admitted (rule 8): every\n * token is one the page fills, the h1 binds the subject's title, and no block\n * that fills itself on another subject's page is placed — except inside a\n * Collection Entries card, where each fills from the card's own entry.\n */\nexport function aiTemplateBindingCheck(\n definition: AiTemplateSubjectDefinition,\n): (tree: AiValidatedTree) => AiDoctrineViolation[] {\n const allowed = new Set(definition.tokens.map((entry) => entry.token))\n return (tree) => {\n const nodes = tree.nodes as unknown as Record<string, AiDoctrineNode>\n const unknown = new Set<string>()\n const unknownAt: string[] = []\n const foreign: Array<{ id: string; componentId: string; owner: AiTemplateSubjectDefinition }> = []\n const titles: string[] = []\n let titleBound = false\n for (const { id, node, ancestors } of walkTree({ rootId: tree.rootId, nodes })) {\n const tokens = stringsIn(node.props).flatMap(aiBindingTokensIn)\n const strays = tokens.filter((token) => !allowed.has(token))\n if (strays.length) {\n for (const token of strays) unknown.add(token)\n unknownAt.push(id)\n }\n const owner = BLOCK_SUBJECTS.get(node.componentId)\n const inCard = ancestors.some((ancestor) => nodes[ancestor]?.componentId === 'collectionEntries')\n if (owner && owner.subject !== definition.subject && !inCard) {\n foreign.push({ id, componentId: node.componentId, owner })\n }\n if (isPageTitle(node)) {\n titles.push(id)\n if (tokens.includes(definition.titleToken)) titleBound = true\n }\n }\n const violations: AiDoctrineViolation[] = []\n if (unknown.size) {\n violations.push({\n rule: 8,\n code: 'unknown-binding',\n message: `This binds ${[...unknown].slice(0, 3).join(', ')}, which ${definition.noun}’s page does not fill. Bind only the tokens listed for this page.`,\n nodeIds: aiModelNodeIds(unknownAt, tree.sourceIds),\n })\n }\n // The doctrine already refuses a page with no h1 or with several.\n if (titles.length === 1 && !titleBound) {\n violations.push({\n rule: 8,\n code: 'typed-title',\n message: `The page title is typed, so every record would show the same one. Put ${definition.titleToken} in the h1.`,\n nodeIds: aiModelNodeIds(titles, tree.sourceIds),\n })\n }\n if (foreign.length) {\n const [first] = foreign\n violations.push({\n rule: 8,\n code: 'foreign-block',\n message: `The ${AI_PALETTE[first.componentId]?.displayName ?? first.componentId} block fills itself only on ${first.owner.noun}’s page, and this template is for ${definition.noun}. Remove it.`,\n nodeIds: aiModelNodeIds(\n foreign.map((entry) => entry.id),\n tree.sourceIds,\n ),\n })\n }\n return violations\n }\n}\n\nexport interface AiTemplateJobAdmissionDeps {\n readCollection?: typeof readAiTemplateCollection\n}\n\n/**\n * A template job is admitted with inputs that say what the page is for, for\n * a site of the job's own org that holds the collection it names, with a\n * template to spare.\n */\nexport function createAiTemplateJobAdmission(deps: AiTemplateJobAdmissionDeps = {}): AiJobAdmission {\n const readCollection = deps.readCollection ?? readAiTemplateCollection\n return async (context) => {\n const inputs = parseAiTemplateJobInputs(context.inputs)\n if (typeof inputs === 'string') return { status: 400, error: inputs }\n return aiDraftAdmissionRefusal(context.firestore, {\n orgId: context.orgId,\n hostId: context.hostId,\n kind: 'template',\n org: context.org,\n ownCheck: async (hostId) =>\n inputs.collectionId && !(await readCollection(context.firestore, hostId, inputs.collectionId))\n ? { status: 404, error: 'That content collection is not on this site' }\n : null,\n })\n }\n}\n\nexport interface AiJobTemplateStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** The platform's duplicate module, for a plan that starts from a copy. */\n duplicate?: typeof duplicateResource\n readCollection?: typeof readAiTemplateCollection\n /** The starter examples block; built from the starters once per process otherwise. */\n examples?: () => AiSystemBlock\n}\n\nexport function createAiJobTemplateStep(deps: AiJobTemplateStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const duplicate = deps.duplicate ?? duplicateResource\n const readCollection = deps.readCollection ?? readAiTemplateCollection\n const examples = deps.examples ?? aiTemplateExamplesSystemBlock\n return async ({ job, now, signal, firestore, modelFor }) => {\n const hostId = job.hostId\n if (!hostId) throw new Error('a template job names no site, and its admission refuses one')\n const inputs = parseAiTemplateJobInputs(job.inputs)\n if (typeof inputs === 'string') {\n throw new Error(`a template job's inputs no longer read as they were admitted: ${inputs}`)\n }\n const definition = AI_TEMPLATE_SUBJECT_DEFINITIONS[inputs.subject]\n const output = (draft: AiDraftRecord, load?: AiLoadEstimate | null): AiJobOutput => ({\n resource: 'template',\n id: draft.id,\n versionId: null,\n hostId,\n hostSubdomain: draft.hostSubdomain,\n label: draft.name,\n ...(load ? { load } : {}),\n })\n // The switch's answer for this job, else the routing table's (AGL-2942).\n const model = modelFor?.('job.template') ?? aiModelForStep('job.template')\n\n // A run cut off after its draft was written reports that draft, found by the id the job recorded.\n const draftId = aiJobDraftId(job, 'template')\n const written = await readAiDraft(firestore, { kind: 'template', hostId, id: draftId })\n if (written) return aiUnspentOutcome(model, { outputs: [output(written)] })\n\n const [inventory, orgSnapshot, collection] = await Promise.all([\n readInventory(job.orgId, hostId, { firestore }),\n firestore.collection('orgs').doc(job.orgId).get(),\n inputs.collectionId\n ? readCollection(firestore, hostId, inputs.collectionId)\n : Promise.resolve(null),\n ])\n if (inputs.collectionId && !collection) {\n throw new Error(`collection ${inputs.collectionId} left site ${hostId} after its template job was admitted`)\n }\n const org = (orgSnapshot.data() ?? null) as Partial<AglynOrgBilling> | null\n const plan = aiConfirmedPlan(job)\n const creation = aiPlanCreation(plan, 'template')\n const name = aiTemplateDraftName(definition, collection, creation?.name)\n\n // The plan starts from a copy of a template the site has (rule 15): the\n // copy is the draft, and nothing is generated. A source gone since the\n // plan was made is built from the brief instead.\n if (\n creation?.duplicateOf &&\n inventory.templates.some((template) => template.id === creation.duplicateOf)\n ) {\n const copy = await duplicate('template', {\n orgId: job.orgId,\n hostId,\n sourceId: creation.duplicateOf,\n name,\n uid: job.createdBy,\n org: org as Record<string, unknown> | null,\n // The same claim the page step makes (AGL-3024): a copy core mints is\n // written under core's own id, never `draftId`, so a step that runs\n // again — a pass resumed, a run cut off after the copy — would mint a\n // second. The job's recorded id makes core replay the one it made.\n attemptKey: draftId,\n })\n if (copy.ok) {\n const hostSubdomain = await aiSiteSubdomain(firestore, hostId)\n return aiUnspentOutcome(model, {\n outputs: [output({ id: copy.id, versionId: null, name: copy.name, hostSubdomain })],\n })\n }\n if (copy.ok === false && copy.status === 403) {\n return aiUnspentOutcome(model, { review: aiLimitReview(copy.error) })\n }\n }\n\n const allowance = await aiDraftAllowanceRefusal(firestore, { kind: 'template', hostId, org })\n if (allowance) return aiUnspentOutcome(model, { review: aiLimitReview(allowance) })\n\n const result = await runValidatedGeneration('template', {\n step: 'job.template',\n model,\n instructions: [...AI_JOB_TEMPLATE_INSTRUCTIONS, examples()],\n inventory,\n messages: [\n {\n role: 'user',\n content: aiJobTemplatePrompt(job, definition, collection, plan, name),\n },\n ],\n tool: aiDoctrineTreeTool('template'),\n maxTokens: AI_JOB_TEMPLATE_STEP_BUDGET.maxTokens(model),\n ...(AI_ROUTING_TABLE['job.template'].thinking ? { thinking: AI_ROUTING_TABLE['job.template'].thinking } : {}),\n ...(AI_ROUTING_TABLE['job.template'].effort ? { effort: AI_ROUTING_TABLE['job.template'].effort } : {}),\n context: { bindingTokens: aiTemplateAddressTokens(definition) },\n // Rule 8's binding check, and the confirmed plan kept in both halves: a\n // token the plan promised that the template does not bind (AGL-3143\n // §11), and a component the plan reuses that it does not place. The\n // layout and component doors hold their builds to that reuse; the\n // template door did not, so it could drop a promised component and\n // still answer `Done` (AGL-3024).\n extend: (tree) => [\n ...aiTemplateBindingCheck(definition)(tree),\n ...aiPlanTemplateTokenViolations(plan, definition, {\n rootId: tree.rootId,\n nodes: tree.nodes as unknown as Record<string, AiDoctrineNode>,\n }),\n ...aiPlanReuseViolations(inventory, plan, aiPlacedComponentIds(tree), 'template'),\n ],\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(result)\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') return { ...spent, review: aiDoctrineReview(result) }\n\n const draft = await writeAiDraft(firestore, {\n kind: 'template',\n hostId,\n id: draftId,\n uid: job.createdBy,\n org,\n name,\n nodes: result.value.nodes,\n slug: aiTemplateDraftSlug(definition, collection),\n now,\n })\n if (draft.ok === false) {\n if (draft.status === 404) throw new Error(`site ${hostId} vanished while its template was generated`)\n return { ...spent, review: aiLimitReview(draft.error) }\n }\n return { ...spent, outputs: [output(draft, result.value.load)] }\n }\n}\n\nexport const runAiJobTemplateStep = createAiJobTemplateStep()\n\n/** Registers the template step and the check a template job passes before it is created or resumed. */\nexport function registerAiTemplateJob(): void {\n registerAiJobStep('template', runAiJobTemplateStep, { minimumMs: AI_JOB_TEMPLATE_STEP_MINIMUM_MS })\n registerAiJobAdmission('template', createAiTemplateJobAdmission())\n}\n"],"names":["hostCollectionKind","normalizeScreenSlug","duplicateResource","AI_TEMPLATE_SUBJECT_DEFINITIONS","AI_TEMPLATE_SUBJECTS","aiBindingTokensIn","aiTemplateAddressTokens","parseAiTemplateJobInputs","AI_STEP_TIERS","AI_ROUTING_TABLE","aiModelForStep","aiDoctrineTreeTool","runValidatedGeneration","walkTree","AI_PALETTE","aiTemplateExamplesSystemBlock","readSiteInventory","registerAiJobAdmission","aiJobDraftId","aiDraftAdmissionRefusal","aiDraftAllowanceRefusal","aiSiteSubdomain","readAiDraft","writeAiDraft","aiConfirmedPlan","aiDoctrineReview","aiGenerationSpent","aiJobBriefLine","aiLimitReview","aiModelNodeIds","aiPlacedComponentIds","aiPlanCreation","aiPlanReferenceLines","aiPlanReuseViolations","aiUnspentOutcome","aiPlanTemplateTokenViolations","aiJobStepBudget","registerAiJobStep","AI_JOB_TEMPLATE_MAX_TOKENS","maxTokens","AI_JOB_TEMPLATE_STEP_BUDGET","tier","AI_JOB_TEMPLATE_STEP_MINIMUM_MS","minimumMs","AI_JOB_TEMPLATE_INSTRUCTIONS","text","join","readAiTemplateCollection","firestore","hostId","collectionId","snapshot","collection","doc","get","exists","data","value","trim","slug","id","name","aiTemplateDraftName","definition","planned","defaultName","aiTemplateDraftSlug","subject","aiJobTemplatePrompt","job","plan","of","noun","titleToken","tokens","map","entry","token","label","blocks","length","BLOCK_SUBJECTS","Map","flatMap","block","stringsIn","out","push","Array","isArray","inner","Object","values","isPageTitle","node","componentId","element","props","String","aiTemplateBindingCheck","allowed","Set","tree","nodes","unknown","unknownAt","foreign","titles","titleBound","ancestors","rootId","strays","filter","has","add","owner","inCard","some","ancestor","includes","violations","size","rule","code","message","slice","nodeIds","sourceIds","first","displayName","createAiTemplateJobAdmission","deps","readCollection","context","inputs","status","error","orgId","kind","org","ownCheck","createAiJobTemplateStep","readInventory","duplicate","examples","now","signal","modelFor","orgSnapshot","Error","output","draft","load","resource","versionId","hostSubdomain","model","draftId","written","outputs","inventory","Promise","all","resolve","creation","duplicateOf","templates","template","copy","sourceId","uid","createdBy","attemptKey","ok","review","allowance","result","step","instructions","messages","role","content","tool","thinking","effort","bindingTokens","extend","spent","refused","runAiJobTemplateStep","registerAiTemplateJob"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,yCAAwC;AAC3E,SAASC,mBAAmB,QAAQ,sCAAqC;AAEzE,SAASC,iBAAiB,QAAQ,qDAAoD;AAEtF,SACEC,+BAA+B,EAC/BC,oBAAoB,EACpBC,iBAAiB,EACjBC,uBAAuB,EACvBC,wBAAwB,QAEnB,mCAA+B;AACtC,SAASC,aAAa,QAAQ,0BAAsB;AACpD,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,0BAAsB;AACvE,SACEC,kBAAkB,EAClBC,sBAAsB,QAEjB,4BAAwB;AAC/B,SACEC,QAAQ,QAGH,uCAAmC;AAE1C,SAASC,UAAU,QAAQ,qCAAiC;AAE5D,SAASC,6BAA6B,QAAQ,qCAAiC;AAC/E,SAASC,iBAAiB,QAAQ,+BAA2B;AAC7D,SAASC,sBAAsB,QAA6B,wBAAoB;AAChF,SAASC,YAAY,QAAQ,wBAAoB;AACjD,SACEC,uBAAuB,EACvBC,uBAAuB,EACvBC,eAAe,EACfC,WAAW,EACXC,YAAY,QAEP,qBAAiB;AACxB,SACEC,eAAe,EACfC,gBAAgB,EAChBC,iBAAiB,EACjBC,cAAc,EACdC,aAAa,EACbC,cAAc,EACdC,oBAAoB,EACpBC,cAAc,EACdC,oBAAoB,EACpBC,qBAAqB,EACrBC,gBAAgB,QACX,yBAAqB;AAC5B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uBACGtE,sBAAsB+H,WAAW1F,MAAMxC,qBAAqBwE,OAAO;iBACvE;WACG4C,SAAS;YAAEA;QAAO,IAAI,CAAC;QAE7B,MAAMyC,QAAQjK,kBAAkBsJ;QAChC,IAAIA,OAAOzC,MAAM,KAAK,WAAW,OAAO,aAAKoD;YAAOC,SAAS;;QAC7D,IAAIZ,OAAOzC,MAAM,KAAK,eAAe,OAAO,aAAKoD;YAAOb,QAAQrJ,iBAAiBuJ;;QAEjF,MAAMzB,QAAQ,MAAMhI,aAAayB,WAAW;YAC1C0F,MAAM;YACNzF;YACAW,IAAIiG;YACJa,KAAKrG,IAAIsG,SAAS;YAClBhC;YACA9E;YACA0C,OAAOyE,OAAOvH,KAAK,CAAC8C,KAAK;YACzB5C,MAAMO,oBAAoBH,YAAYX;YACtC6F;QACF;QACA,IAAIM,MAAMsB,EAAE,KAAK,OAAO;YACtB,IAAItB,MAAMhB,MAAM,KAAK,KAAK,MAAM,IAAIc,MAAM,CAAC,KAAK,EAAEpG,OAAO,0CAA0C,CAAC;YACpG,OAAO,aAAK0I;gBAAOb,QAAQlJ,cAAc2H,MAAMf,KAAK;;QACtD;QACA,OAAO,aAAKmD;YAAO5B,SAAS;gBAACT,OAAOC,OAAOyB,OAAOvH,KAAK,CAAC+F,IAAI;aAAE;;IAChE;AACF;AAEA,OAAO,MAAMqC,uBAAuBhD,0BAAyB;AAE7D,qGAAqG,GACrG,OAAO,SAASiD;IACdzJ,kBAAkB,YAAYwJ,sBAAsB;QAAElJ,WAAWD;IAAgC;IACjGzB,uBAAuB,YAAYiH;AACrC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-template-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 { hostCollectionKind } from '@aglyn/aglyn/app-utils/collection-kind'\nimport { normalizeScreenSlug } from '@aglyn/aglyn/app-utils/screen-route'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport { duplicateResource } from '@aglyn/tenant-data-admin/server/duplicate-resource'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type { AiJob, AiJobOutput, AiJobPlan, AiJobReview } from '../model/ai-jobs.types'\nimport {\n AI_TEMPLATE_SUBJECT_DEFINITIONS,\n AI_TEMPLATE_SUBJECTS,\n aiBindingTokensIn,\n aiTemplateAddressTokens,\n parseAiTemplateJobInputs,\n type AiTemplateSubjectDefinition,\n} from '../model/ai-template-subjects'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport {\n aiDoctrineTreeTool,\n runValidatedGeneration,\n type AiValidatedTree,\n} from '../runtime/ai-doctrine'\nimport {\n walkTree,\n type AiDoctrineNode,\n type AiDoctrineViolation,\n} from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { AI_PALETTE } from '../runtime/ai-palette.generated'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { aiTemplateExamplesSystemBlock } from '../runtime/ai-template-examples'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport { registerAiJobAdmission, type AiJobAdmission } from './ai-job-admission'\nimport { aiJobDraftId } from './ai-job-draft-ids'\nimport {\n aiDraftAdmissionRefusal,\n aiDraftAllowanceRefusal,\n aiSiteSubdomain,\n readAiDraft,\n readAiTemplateDraftNodes,\n writeAiDraft,\n type AiDraftRecord,\n} from './ai-job-drafts'\nimport {\n aiConfirmedPlan,\n aiDoctrineReview,\n aiGenerationSpent,\n aiJobBriefLine,\n aiLimitReview,\n aiModelNodeIds,\n aiPlacedComponentIds,\n aiPlanCreation,\n aiPlanReferenceLines,\n aiPlanReuseViolations,\n aiUnspentOutcome,\n} from './ai-job-generation'\nimport { aiPlannedTemplateTokens, aiPlanTemplateTokenViolations } from './ai-job-plan-conformance'\nimport type { AiJobStepRunner } from './ai-job-text-step'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The template step (AGL-2909): the generation step of a `template` job, run\n * once a member confirmed the job's plan.\n *\n * It builds ONE page template — the page a site renders once per record: a\n * content collection's entry, a product, an author — through\n * `runValidatedGeneration('template', …)`. Everything that differs per\n * record is a binding token from the subject's vocabulary\n * (`model/ai-template-subjects.ts`), which is the list the besigner's insert\n * picker offers for that page; a link or media prop may hold one of those\n * tokens whole, which the palette validator admits only because this door\n * names them. The door adds one check of its own through `extend` (rule 8):\n * no token the page does not fill, an h1 bound to the subject's title, and no\n * block that fills itself only on another subject's page.\n *\n * The model is shown the platform's starter pages as examples, in a cached\n * block (`runtime/ai-template-examples.ts`), and writes against them.\n *\n * The template lands in the site's library as a new draft\n * (`ai-job-drafts.ts`), inert until a member uses it: bound to no\n * collection, set as no product or author page, served nowhere. A plan that\n * starts from a copy of a template the site has gets that copy instead.\n */\n\n/** The longest answer a template may run to; the tree is held to the template budget either way. */\nexport const AI_JOB_TEMPLATE_MAX_TOKENS = AI_ROUTING_TABLE['job.template'].maxTokens\n\n/**\n * The template step's time (AGL-3035, AGL-3036): its two inventory-lookup\n * rounds, its answer and its re-ask at the routing table's ceiling on the tier\n * `job.template` is served from, fitted to what a beat can give a step. It\n * runs on the job beat, never at an inline door, and asks for no more of the\n * ceiling than fits that time on the model it runs.\n */\nexport const AI_JOB_TEMPLATE_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.template'],\n maxTokens: AI_JOB_TEMPLATE_MAX_TOKENS,\n})\n\n/** The least time one template step needs before it starts. */\nexport const AI_JOB_TEMPLATE_STEP_MINIMUM_MS = AI_JOB_TEMPLATE_STEP_BUDGET.minimumMs\n\n/** The template step's own instructions, cached after the doctrine and before the examples. */\nexport const AI_JOB_TEMPLATE_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n 'You build one page template: the page a website renders once for each record it keeps, such as each entry of a content collection, each product or each author. Answer with submit_template: the whole page as one flat node map.',\n 'Everything that differs from one record to the next is a binding token, never typed copy. The request names what the page is for, the tokens that page fills and the blocks that fill themselves there; bind only those tokens.',\n 'The page’s one h1 holds the title token the request names. Copy that reads the same on every record, such as a section heading, is written in the site’s voice.',\n 'A link or media prop holds exactly one token from the request’s link and media tokens, such as an Image whose src is {{entry.coverImage}}; its alt text may combine words and tokens.',\n 'The page renders inside the site’s layout, so it carries no header, navigation or footer of its own.',\n ].join('\\n'),\n },\n]\n\n/** A content collection an entry template is for, as the prompt and the draft name it. */\nexport interface AiTemplateCollection {\n id: string\n name: string\n slug: string\n}\n\n/** The content collection by that id on the site, or `null` when there is none. */\nexport async function readAiTemplateCollection(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n collectionId: string,\n): Promise<AiTemplateCollection | null> {\n const snapshot = await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('collections')\n .doc(collectionId)\n .get()\n if (!snapshot.exists) return null\n const data = (snapshot.data() ?? {}) as Record<string, unknown>\n if (hostCollectionKind(data) !== 'content') return null\n const text = (value: unknown) => (typeof value === 'string' ? value.trim() : '')\n const slug = text(data['slug'])\n return {\n id: collectionId,\n name: text(data['displayName']) || text(data['name']) || slug || collectionId,\n slug,\n }\n}\n\n/** The template's name: the plan's, else the collection's or the subject's. */\nexport function aiTemplateDraftName(\n definition: AiTemplateSubjectDefinition,\n collection: AiTemplateCollection | null,\n planned: string | null | undefined,\n): string {\n return planned || (collection ? `${collection.name} entry template` : definition.defaultName)\n}\n\n/** The address Use template offers for the page it creates. */\nexport function aiTemplateDraftSlug(\n definition: AiTemplateSubjectDefinition,\n collection: AiTemplateCollection | null,\n): string | null {\n return (\n normalizeScreenSlug(\n collection\n ? `${collection.slug || collection.id}-entry-template`\n : `${definition.subject}-page-template`,\n ) ?? null\n )\n}\n\n/** The template job as the generation's user turn. */\nexport function aiJobTemplatePrompt(\n job: Pick<AiJob, 'brief'>,\n definition: AiTemplateSubjectDefinition,\n collection: AiTemplateCollection | null,\n plan: AiJobPlan | null,\n name: string,\n): string {\n const of = collection\n ? ` of the \"${collection.name}\" collection${collection.slug ? ` (/${collection.slug})` : ''}`\n : ''\n return [\n `Template name: ${name}`,\n `The page is for ${definition.noun}${of}.`,\n `Title token: ${definition.titleToken}`,\n `Tokens this page fills: ${definition.tokens.map((entry) => `${entry.token} ${entry.label}`).join('; ')}`,\n `Link and media tokens: ${aiTemplateAddressTokens(definition).join(', ')}`,\n definition.blocks.length\n ? `Blocks that fill themselves on this page: ${definition.blocks.join(', ')}`\n : 'No block fills itself on this page: bind the tokens.',\n aiJobBriefLine(job),\n ...aiPlanReferenceLines(plan),\n ].join('\\n')\n}\n\n/** Which subject's page each self-filling block belongs to. */\nconst BLOCK_SUBJECTS = new Map<string, AiTemplateSubjectDefinition>(\n AI_TEMPLATE_SUBJECTS.flatMap((subject) =>\n AI_TEMPLATE_SUBJECT_DEFINITIONS[subject].blocks.map(\n (block) => [block, AI_TEMPLATE_SUBJECT_DEFINITIONS[subject]] as const,\n ),\n ),\n)\n\n/** Every string a prop value holds, however deeply. */\nfunction stringsIn(value: unknown, out: string[] = []): string[] {\n if (typeof value === 'string') out.push(value)\n else if (Array.isArray(value)) for (const inner of value) stringsIn(inner, out)\n else if (value && typeof value === 'object') {\n for (const inner of Object.values(value as Record<string, unknown>)) stringsIn(inner, out)\n }\n return out\n}\n\n/** The page's title: a Typography that renders as an h1. */\nfunction isPageTitle(node: AiDoctrineNode): boolean {\n if (node.componentId !== 'muiTypography') return false\n const element = typeof node.props?.['component'] === 'string' ? String(node.props['component']) : ''\n return (element || String(node.props?.['variant'] ?? '')) === 'h1'\n}\n\n/**\n * The template door's check on a tree the doctrine admitted (rule 8): every\n * token is one the page fills, the h1 binds the subject's title, and no block\n * that fills itself on another subject's page is placed — except inside a\n * Collection Entries card, where each fills from the card's own entry.\n */\nexport function aiTemplateBindingCheck(\n definition: AiTemplateSubjectDefinition,\n): (tree: AiValidatedTree) => AiDoctrineViolation[] {\n const allowed = new Set(definition.tokens.map((entry) => entry.token))\n return (tree) => {\n const nodes = tree.nodes as unknown as Record<string, AiDoctrineNode>\n const unknown = new Set<string>()\n const unknownAt: string[] = []\n const foreign: Array<{ id: string; componentId: string; owner: AiTemplateSubjectDefinition }> = []\n const titles: string[] = []\n let titleBound = false\n for (const { id, node, ancestors } of walkTree({ rootId: tree.rootId, nodes })) {\n const tokens = stringsIn(node.props).flatMap(aiBindingTokensIn)\n const strays = tokens.filter((token) => !allowed.has(token))\n if (strays.length) {\n for (const token of strays) unknown.add(token)\n unknownAt.push(id)\n }\n const owner = BLOCK_SUBJECTS.get(node.componentId)\n const inCard = ancestors.some((ancestor) => nodes[ancestor]?.componentId === 'collectionEntries')\n if (owner && owner.subject !== definition.subject && !inCard) {\n foreign.push({ id, componentId: node.componentId, owner })\n }\n if (isPageTitle(node)) {\n titles.push(id)\n if (tokens.includes(definition.titleToken)) titleBound = true\n }\n }\n const violations: AiDoctrineViolation[] = []\n if (unknown.size) {\n violations.push({\n rule: 8,\n code: 'unknown-binding',\n message: `This binds ${[...unknown].slice(0, 3).join(', ')}, which ${definition.noun}’s page does not fill. Bind only the tokens listed for this page.`,\n nodeIds: aiModelNodeIds(unknownAt, tree.sourceIds),\n })\n }\n // The doctrine already refuses a page with no h1 or with several.\n if (titles.length === 1 && !titleBound) {\n violations.push({\n rule: 8,\n code: 'typed-title',\n message: `The page title is typed, so every record would show the same one. Put ${definition.titleToken} in the h1.`,\n nodeIds: aiModelNodeIds(titles, tree.sourceIds),\n })\n }\n if (foreign.length) {\n const [first] = foreign\n violations.push({\n rule: 8,\n code: 'foreign-block',\n message: `The ${AI_PALETTE[first.componentId]?.displayName ?? first.componentId} block fills itself only on ${first.owner.noun}’s page, and this template is for ${definition.noun}. Remove it.`,\n nodeIds: aiModelNodeIds(\n foreign.map((entry) => entry.id),\n tree.sourceIds,\n ),\n })\n }\n return violations\n }\n}\n\nexport interface AiTemplateJobAdmissionDeps {\n readCollection?: typeof readAiTemplateCollection\n}\n\n/**\n * A template job is admitted with inputs that say what the page is for, for\n * a site of the job's own org that holds the collection it names, with a\n * template to spare.\n */\nexport function createAiTemplateJobAdmission(deps: AiTemplateJobAdmissionDeps = {}): AiJobAdmission {\n const readCollection = deps.readCollection ?? readAiTemplateCollection\n return async (context) => {\n const inputs = parseAiTemplateJobInputs(context.inputs)\n if (typeof inputs === 'string') return { status: 400, error: inputs }\n return aiDraftAdmissionRefusal(context.firestore, {\n orgId: context.orgId,\n hostId: context.hostId,\n kind: 'template',\n org: context.org,\n ownCheck: async (hostId) =>\n inputs.collectionId && !(await readCollection(context.firestore, hostId, inputs.collectionId))\n ? { status: 404, error: 'That content collection is not on this site' }\n : null,\n })\n }\n}\n\nexport interface AiJobTemplateStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** The platform's duplicate module, for a plan that starts from a copy. */\n duplicate?: typeof duplicateResource\n readCollection?: typeof readAiTemplateCollection\n /** The starter examples block; built from the starters once per process otherwise. */\n examples?: () => AiSystemBlock\n}\n\n/**\n * The binding tokens the confirmed plan gives the template, against the\n * template a COPY actually produced (AGL-3024); `null` when the copy keeps\n * the plan, or when the plan promised no token to keep.\n *\n * The same hole as `aiCopiedLayoutReview` and `aiCopiedPageReview`, on the\n * third kind that can start from a duplicate. The generate path already holds\n * a built template to `aiPlanTemplateTokenViolations`; the copy path reached\n * none of it, so a plan reading \"duplicate it and bind the author's photo\"\n * got the duplicate and reported Done.\n *\n * A copy that cannot be read back settles nothing, and a promise this step\n * cannot settle is reviewed by a person rather than reported as kept.\n */\nexport async function aiCopiedTemplateReview(\n firestore: FirebaseFirestore.Firestore,\n input: {\n hostId: string\n id: string\n name: string\n plan: AiJobPlan | null\n definition: AiTemplateSubjectDefinition\n },\n): Promise<AiJobReview | null> {\n const { tokens, unreadable } = aiPlannedTemplateTokens(input.plan, input.definition)\n if (!tokens.length && !unreadable.length) return null\n const stored = await readAiTemplateDraftNodes(firestore, {\n hostId: input.hostId,\n id: input.id,\n })\n const nodes = (stored ?? {}) as unknown as Record<string, AiDoctrineNode>\n if (!nodes[CANVAS_ROOT_ELEMENT_ID]) {\n return {\n reason: 'doctrine',\n message: `\"${input.name}\" was copied from the template the plan names, and this job could not read the copy back to check it shows what the plan gives it. Open the template and check it before you apply it.`,\n findings: [],\n }\n }\n const violations = aiPlanTemplateTokenViolations(input.plan, input.definition, {\n rootId: CANVAS_ROOT_ELEMENT_ID,\n nodes,\n })\n if (!violations.length) return null\n return aiDoctrineReview({\n message: `\"${input.name}\" is a copy of the template the plan names, and a copy is all it is: ${violations[0].message}`,\n violations,\n })\n}\n\nexport function createAiJobTemplateStep(deps: AiJobTemplateStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const duplicate = deps.duplicate ?? duplicateResource\n const readCollection = deps.readCollection ?? readAiTemplateCollection\n const examples = deps.examples ?? aiTemplateExamplesSystemBlock\n return async ({ job, now, signal, firestore, modelFor }) => {\n const hostId = job.hostId\n if (!hostId) throw new Error('a template job names no site, and its admission refuses one')\n const inputs = parseAiTemplateJobInputs(job.inputs)\n if (typeof inputs === 'string') {\n throw new Error(`a template job's inputs no longer read as they were admitted: ${inputs}`)\n }\n const definition = AI_TEMPLATE_SUBJECT_DEFINITIONS[inputs.subject]\n const output = (draft: AiDraftRecord, load?: AiLoadEstimate | null): AiJobOutput => ({\n resource: 'template',\n id: draft.id,\n versionId: null,\n hostId,\n hostSubdomain: draft.hostSubdomain,\n label: draft.name,\n ...(load ? { load } : {}),\n })\n // The switch's answer for this job, else the routing table's (AGL-2942).\n const model = modelFor?.('job.template') ?? aiModelForStep('job.template')\n\n // A run cut off after its draft was written reports that draft, found by the id the job recorded.\n const draftId = aiJobDraftId(job, 'template')\n const written = await readAiDraft(firestore, { kind: 'template', hostId, id: draftId })\n if (written) return aiUnspentOutcome(model, { outputs: [output(written)] })\n\n const [inventory, orgSnapshot, collection] = await Promise.all([\n readInventory(job.orgId, hostId, { firestore }),\n firestore.collection('orgs').doc(job.orgId).get(),\n inputs.collectionId\n ? readCollection(firestore, hostId, inputs.collectionId)\n : Promise.resolve(null),\n ])\n if (inputs.collectionId && !collection) {\n throw new Error(`collection ${inputs.collectionId} left site ${hostId} after its template job was admitted`)\n }\n const org = (orgSnapshot.data() ?? null) as Partial<AglynOrgBilling> | null\n const plan = aiConfirmedPlan(job)\n const creation = aiPlanCreation(plan, 'template')\n const name = aiTemplateDraftName(definition, collection, creation?.name)\n\n // The plan starts from a copy of a template the site has (rule 15): the\n // copy is the draft, and nothing is generated. A source gone since the\n // plan was made is built from the brief instead.\n if (\n creation?.duplicateOf &&\n inventory.templates.some((template) => template.id === creation.duplicateOf)\n ) {\n const copy = await duplicate('template', {\n orgId: job.orgId,\n hostId,\n sourceId: creation.duplicateOf,\n name,\n uid: job.createdBy,\n org: org as Record<string, unknown> | null,\n // The same claim the page step makes (AGL-3024): a copy core mints is\n // written under core's own id, never `draftId`, so a step that runs\n // again — a pass resumed, a run cut off after the copy — would mint a\n // second. The job's recorded id makes core replay the one it made.\n attemptKey: draftId,\n })\n if (copy.ok) {\n const hostSubdomain = await aiSiteSubdomain(firestore, hostId)\n // The copy is reported with what the plan promised of it read back\n // (AGL-3024): this branch generates nothing, so nothing else can.\n const review = await aiCopiedTemplateReview(firestore, {\n hostId,\n id: copy.id,\n name: copy.name,\n plan,\n definition,\n })\n if (review) return aiUnspentOutcome(model, { review })\n return aiUnspentOutcome(model, {\n outputs: [output({ id: copy.id, versionId: null, name: copy.name, hostSubdomain })],\n })\n }\n if (copy.ok === false && copy.status === 403) {\n return aiUnspentOutcome(model, { review: aiLimitReview(copy.error) })\n }\n }\n\n const allowance = await aiDraftAllowanceRefusal(firestore, { kind: 'template', hostId, org })\n if (allowance) return aiUnspentOutcome(model, { review: aiLimitReview(allowance) })\n\n const result = await runValidatedGeneration('template', {\n step: 'job.template',\n model,\n instructions: [...AI_JOB_TEMPLATE_INSTRUCTIONS, examples()],\n inventory,\n messages: [\n {\n role: 'user',\n content: aiJobTemplatePrompt(job, definition, collection, plan, name),\n },\n ],\n tool: aiDoctrineTreeTool('template'),\n maxTokens: AI_JOB_TEMPLATE_STEP_BUDGET.maxTokens(model),\n ...(AI_ROUTING_TABLE['job.template'].thinking ? { thinking: AI_ROUTING_TABLE['job.template'].thinking } : {}),\n ...(AI_ROUTING_TABLE['job.template'].effort ? { effort: AI_ROUTING_TABLE['job.template'].effort } : {}),\n context: { bindingTokens: aiTemplateAddressTokens(definition) },\n // Rule 8's binding check, and the confirmed plan kept in both halves: a\n // token the plan promised that the template does not bind (AGL-3143\n // §11), and a component the plan reuses that it does not place. The\n // layout and component doors hold their builds to that reuse; the\n // template door did not, so it could drop a promised component and\n // still answer `Done` (AGL-3024).\n extend: (tree) => [\n ...aiTemplateBindingCheck(definition)(tree),\n ...aiPlanTemplateTokenViolations(plan, definition, {\n rootId: tree.rootId,\n nodes: tree.nodes as unknown as Record<string, AiDoctrineNode>,\n }),\n ...aiPlanReuseViolations(inventory, plan, aiPlacedComponentIds(tree), 'template'),\n ],\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(result)\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') return { ...spent, review: aiDoctrineReview(result) }\n\n const draft = await writeAiDraft(firestore, {\n kind: 'template',\n hostId,\n id: draftId,\n uid: job.createdBy,\n org,\n name,\n nodes: result.value.nodes,\n slug: aiTemplateDraftSlug(definition, collection),\n now,\n })\n if (draft.ok === false) {\n if (draft.status === 404) throw new Error(`site ${hostId} vanished while its template was generated`)\n return { ...spent, review: aiLimitReview(draft.error) }\n }\n return { ...spent, outputs: [output(draft, result.value.load)] }\n }\n}\n\nexport const runAiJobTemplateStep = createAiJobTemplateStep()\n\n/** Registers the template step and the check a template job passes before it is created or resumed. */\nexport function registerAiTemplateJob(): void {\n registerAiJobStep('template', runAiJobTemplateStep, { minimumMs: AI_JOB_TEMPLATE_STEP_MINIMUM_MS })\n registerAiJobAdmission('template', createAiTemplateJobAdmission())\n}\n"],"names":["hostCollectionKind","normalizeScreenSlug","duplicateResource","CANVAS_ROOT_ELEMENT_ID","AI_TEMPLATE_SUBJECT_DEFINITIONS","AI_TEMPLATE_SUBJECTS","aiBindingTokensIn","aiTemplateAddressTokens","parseAiTemplateJobInputs","AI_STEP_TIERS","AI_ROUTING_TABLE","aiModelForStep","aiDoctrineTreeTool","runValidatedGeneration","walkTree","AI_PALETTE","aiTemplateExamplesSystemBlock","readSiteInventory","registerAiJobAdmission","aiJobDraftId","aiDraftAdmissionRefusal","aiDraftAllowanceRefusal","aiSiteSubdomain","readAiDraft","readAiTemplateDraftNodes","writeAiDraft","aiConfirmedPlan","aiDoctrineReview","aiGenerationSpent","aiJobBriefLine","aiLimitReview","aiModelNodeIds","aiPlacedComponentIds","aiPlanCreation","aiPlanReferenceLines","aiPlanReuseViolations","aiUnspentOutcome","aiPlannedTemplateTokens","aiPlanTemplateTokenViolations","aiJobStepBudget","registerAiJobStep","AI_JOB_TEMPLATE_MAX_TOKENS","maxTokens","AI_JOB_TEMPLATE_STEP_BUDGET","tier","AI_JOB_TEMPLATE_STEP_MINIMUM_MS","minimumMs","AI_JOB_TEMPLATE_INSTRUCTIONS","text","join","readAiTemplateCollection","firestore","hostId","collectionId","snapshot","collection","doc","get","exists","data","value","trim","slug","id","name","aiTemplateDraftName","definition","planned","defaultName","aiTemplateDraftSlug","subject","aiJobTemplatePrompt","job","plan","of","noun","titleToken","tokens","map","entry","token","label","blocks","length","BLOCK_SUBJECTS","Map","flatMap","block","stringsIn","out","push","Array","isArray","inner","Object","values","isPageTitle","node","componentId","element","props","String","aiTemplateBindingCheck","allowed","Set","tree","nodes","unknown","unknownAt","foreign","titles","titleBound","ancestors","rootId","strays","filter","has","add","owner","inCard","some","ancestor","includes","violations","size","rule","code","message","slice","nodeIds","sourceIds","first","displayName","createAiTemplateJobAdmission","deps","readCollection","context","inputs","status","error","orgId","kind","org","ownCheck","aiCopiedTemplateReview","input","unreadable","stored","reason","findings","createAiJobTemplateStep","readInventory","duplicate","examples","now","signal","modelFor","orgSnapshot","Error","output","draft","load","resource","versionId","hostSubdomain","model","draftId","written","outputs","inventory","Promise","all","resolve","creation","duplicateOf","templates","template","copy","sourceId","uid","createdBy","attemptKey","ok","review","allowance","result","step","instructions","messages","role","content","tool","thinking","effort","bindingTokens","extend","spent","refused","runAiJobTemplateStep","registerAiTemplateJob"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAAQ,yCAAwC;AAC3E,SAASC,mBAAmB,QAAQ,sCAAqC;AAEzE,SAASC,iBAAiB,QAAQ,qDAAoD;AACtF,SAASC,sBAAsB,QAAQ,2CAA0C;AAEjF,SACEC,+BAA+B,EAC/BC,oBAAoB,EACpBC,iBAAiB,EACjBC,uBAAuB,EACvBC,wBAAwB,QAEnB,mCAA+B;AACtC,SAASC,aAAa,QAAQ,0BAAsB;AACpD,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,0BAAsB;AACvE,SACEC,kBAAkB,EAClBC,sBAAsB,QAEjB,4BAAwB;AAC/B,SACEC,QAAQ,QAGH,uCAAmC;AAE1C,SAASC,UAAU,QAAQ,qCAAiC;AAE5D,SAASC,6BAA6B,QAAQ,qCAAiC;AAC/E,SAASC,iBAAiB,QAAQ,+BAA2B;AAC7D,SAASC,sBAAsB,QAA6B,wBAAoB;AAChF,SAASC,YAAY,QAAQ,wBAAoB;AACjD,SACEC,uBAAuB,EACvBC,uBAAuB,EACvBC,eAAe,EACfC,WAAW,EACXC,wBAAwB,EACxBC,YAA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uC;uBACnCnE,8BAA8BmC,MAAMP,YAAY;wBACjD+C,QAAQR,KAAKQ,MAAM;wBACnBP,OAAOD,KAAKC,KAAK;oBACnB;uBACGvE,sBAAsBsI,WAAWhG,MAAMzC,qBAAqByE,OAAO;iBACvE;WACGkD,SAAS;YAAEA;QAAO,IAAI,CAAC;QAE7B,MAAMyC,QAAQxK,kBAAkB6J;QAChC,IAAIA,OAAO/C,MAAM,KAAK,WAAW,OAAO,aAAK0D;YAAOC,SAAS;;QAC7D,IAAIZ,OAAO/C,MAAM,KAAK,eAAe,OAAO,aAAK0D;YAAOb,QAAQ5J,iBAAiB8J;;QAEjF,MAAMzB,QAAQ,MAAMvI,aAAa0B,WAAW;YAC1C0F,MAAM;YACNzF;YACAW,IAAIuG;YACJa,KAAK3G,IAAI4G,SAAS;YAClBtC;YACA9E;YACA0C,OAAO+E,OAAO7H,KAAK,CAAC8C,KAAK;YACzB5C,MAAMO,oBAAoBH,YAAYX;YACtCmG;QACF;QACA,IAAIM,MAAMsB,EAAE,KAAK,OAAO;YACtB,IAAItB,MAAMtB,MAAM,KAAK,KAAK,MAAM,IAAIoB,MAAM,CAAC,KAAK,EAAE1G,OAAO,0CAA0C,CAAC;YACpG,OAAO,aAAKgJ;gBAAOb,QAAQzJ,cAAckI,MAAMrB,KAAK;;QACtD;QACA,OAAO,aAAKyD;YAAO5B,SAAS;gBAACT,OAAOC,OAAOyB,OAAO7H,KAAK,CAACqG,IAAI;aAAE;;IAChE;AACF;AAEA,OAAO,MAAMqC,uBAAuBhD,0BAAyB;AAE7D,qGAAqG,GACrG,OAAO,SAASiD;IACd/J,kBAAkB,YAAY8J,sBAAsB;QAAExJ,WAAWD;IAAgC;IACjG3B,uBAAuB,YAAYmH;AACrC"}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
import type { AiBuildPlan } from '../../model/ai-build-plan';
|
|
17
|
+
import type { AiBuildPlan, AiBuildPlanSection } from '../../model/ai-build-plan';
|
|
18
18
|
import type { AiPageType } from '../../model/ai-page-job';
|
|
19
19
|
import { type AiSiteInventory } from '../../model/ai-site-inventory';
|
|
20
20
|
/**
|
|
@@ -68,6 +68,22 @@ export interface AiPageBriefFixture {
|
|
|
68
68
|
description: string;
|
|
69
69
|
};
|
|
70
70
|
}
|
|
71
|
+
interface Built {
|
|
72
|
+
answer: AiGoldenSection;
|
|
73
|
+
section: AiBuildPlanSection;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* One section of cards on a workspace that keeps reusable components, written
|
|
77
|
+
* once and written out, for the check to draw one into the other (AGL-3024).
|
|
78
|
+
*/
|
|
79
|
+
export declare const AI_INSTANCE_CARDS_FIXTURE: {
|
|
80
|
+
once: Built;
|
|
81
|
+
full: Built;
|
|
82
|
+
items: {
|
|
83
|
+
title: string;
|
|
84
|
+
summary: string;
|
|
85
|
+
}[];
|
|
86
|
+
};
|
|
71
87
|
export declare const AI_PAGE_BRIEF_FIXTURES: readonly AiPageBriefFixture[];
|
|
72
88
|
/**
|
|
73
89
|
* A page brief for a workspace that keeps no reusable components, answered the
|
|
@@ -144,3 +160,4 @@ export interface AiTwoPersonPageFixture extends AiPageBriefFixture {
|
|
|
144
160
|
roomier: AiGoldenSection;
|
|
145
161
|
}
|
|
146
162
|
export declare const AI_TWO_PERSON_PAGE_FIXTURE: AiTwoPersonPageFixture;
|
|
163
|
+
export {};
|