@aglyn/plugins-ai 1.0.0-beta.256 → 1.0.0-beta.257
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
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/plugins-ai",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.257",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,22 +25,22 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.0.0-beta.
|
|
29
|
-
"@aglyn/shared-data-enums": "1.0.0-beta.
|
|
30
|
-
"@aglyn/shared-data-mdi": "1.0.0-beta.
|
|
31
|
-
"@aglyn/shared-data-types": "1.0.0-beta.
|
|
32
|
-
"@aglyn/shared-ui-email-campaigns": "1.0.0-beta.
|
|
33
|
-
"@aglyn/shared-ui-jsx": "1.0.0-beta.
|
|
34
|
-
"@aglyn/shared-ui-snackstack": "1.0.0-beta.
|
|
35
|
-
"@aglyn/shared-ui-theme": "1.0.0-beta.
|
|
36
|
-
"@aglyn/shared-util-email": "1.0.0-beta.
|
|
37
|
-
"@aglyn/shared-util-errors": "1.0.0-beta.
|
|
38
|
-
"@aglyn/shared-util-http": "1.0.0-beta.
|
|
39
|
-
"@aglyn/shared-util-timestamp": "1.0.0-beta.
|
|
40
|
-
"@aglyn/shared-util-tools": "1.0.0-beta.
|
|
41
|
-
"@aglyn/tenant-data-admin": "1.0.0-beta.
|
|
42
|
-
"@aglyn/tenant-feature-instance": "1.0.0-beta.
|
|
43
|
-
"@aglyn/tenant-runtime": "1.0.0-beta.
|
|
28
|
+
"@aglyn/aglyn": "1.0.0-beta.257",
|
|
29
|
+
"@aglyn/shared-data-enums": "1.0.0-beta.257",
|
|
30
|
+
"@aglyn/shared-data-mdi": "1.0.0-beta.257",
|
|
31
|
+
"@aglyn/shared-data-types": "1.0.0-beta.257",
|
|
32
|
+
"@aglyn/shared-ui-email-campaigns": "1.0.0-beta.257",
|
|
33
|
+
"@aglyn/shared-ui-jsx": "1.0.0-beta.257",
|
|
34
|
+
"@aglyn/shared-ui-snackstack": "1.0.0-beta.257",
|
|
35
|
+
"@aglyn/shared-ui-theme": "1.0.0-beta.257",
|
|
36
|
+
"@aglyn/shared-util-email": "1.0.0-beta.257",
|
|
37
|
+
"@aglyn/shared-util-errors": "1.0.0-beta.257",
|
|
38
|
+
"@aglyn/shared-util-http": "1.0.0-beta.257",
|
|
39
|
+
"@aglyn/shared-util-timestamp": "1.0.0-beta.257",
|
|
40
|
+
"@aglyn/shared-util-tools": "1.0.0-beta.257",
|
|
41
|
+
"@aglyn/tenant-data-admin": "1.0.0-beta.257",
|
|
42
|
+
"@aglyn/tenant-feature-instance": "1.0.0-beta.257",
|
|
43
|
+
"@aglyn/tenant-runtime": "1.0.0-beta.257",
|
|
44
44
|
"@swc/helpers": "0.5.23"
|
|
45
45
|
},
|
|
46
46
|
"peerDependencies": {
|
|
@@ -201,9 +201,9 @@ const LIST_NAME_MAX_CHARS = 80;
|
|
|
201
201
|
text: [
|
|
202
202
|
'You build one form for a website: the fields a visitor fills in and the button that sends them. Answer with submit_form: the whole form as one flat node map, how its submissions are routed, and what the brief asks for that a form cannot collect.',
|
|
203
203
|
'The root is one Form (form) holding its fields in the order a visitor fills them in. Each piece of a field is its own element: a field is a Form Control (muiFormControl) holding a Form Label (muiFormLabel) whose text a visitor reads, then the answer, then optionally Helper Text (muiFormHelperText). Give the form a submitLabel and a successMessage in the site’s voice. The Form draws its own button, so a Button (muiButton) with type submit is optional.',
|
|
204
|
-
'The answer is an Input (muiInput) to type in: type email for an email address, tel for a phone number, multiline true for a description; a Select (muiSelect) holding one Select Option (muiSelectOption) per choice, or a Radio Group (muiRadioGroup) holding one Choice Label (muiFormControlLabel) per choice, each holding a Radio (muiRadio) whose value is the choice, for one choice; a Choice Label holding a Checkbox (muiCheckbox) per choice, the Checkboxes sharing one name, for several;
|
|
205
|
-
'Every Input, Select, Radio Group, Checkbox and
|
|
206
|
-
'A form collects text, choices and
|
|
204
|
+
'The answer is an Input (muiInput) to type in: type email for an email address, tel for a phone number, multiline true for a description; a Select (muiSelect) holding one Select Option (muiSelectOption) per choice, or a Radio Group (muiRadioGroup) holding one Choice Label (muiFormControlLabel) per choice, each holding a Radio (muiRadio) whose value is the choice, for one choice; a Choice Label holding a Checkbox (muiCheckbox) per choice, the Checkboxes sharing one name, for several; a Rating (muiRating) for a score; a Date Picker (muiDatePicker) for a day, such as a preferred date; and a Time Picker (muiTimePicker) for a time of day. A single yes-or-no tick is a Choice Label holding one Checkbox, outside any Form Control.',
|
|
205
|
+
'Every Input, Select, Radio Group, Checkbox, Rating, Date Picker and Time Picker has a name that is unique in the form, apart from Checkboxes of one question, and says what it holds in camelCase, such as fullName, email, phone or roofType; and required only when the form cannot do its job without it.',
|
|
206
|
+
'A form collects text, choices, ratings, dates and times only. When the brief asks for something else, such as a file or photo upload, a signature or a payment, leave it out and name it in cannotCollect.',
|
|
207
207
|
'Never draw a marketing consent, newsletter or subscribe checkbox: when the form asks for an email address, the platform adds its own.',
|
|
208
208
|
'routing.kind is inbox when submissions only need to be read, lead when each one is a sales lead to follow up, and list when the people who send it should join an email list. routing.list is the list’s name only when the brief names one, and null otherwise.'
|
|
209
209
|
].join('\n')
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-form-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 { throwIfAiJobCanceled } from './ai-job-cancel'\nimport {\n checkFormContract,\n formFieldsCanYieldAnEmail,\n} from '@aglyn/aglyn/app-utils/form-contract'\nimport {\n collectFormFieldNodeIds,\n FORM_COMPONENT_ID,\n FORM_ID_PROP,\n FORM_INPUT_ELEMENT_IDS,\n formFieldDeclsFromNodes,\n formInputName,\n formNodeIdIn,\n isMarketingConsentFieldName,\n MARKETING_CONSENT_FORM_FIELD,\n type FormDocument,\n type FormFieldDecl,\n type FormRouting,\n} from '@aglyn/aglyn/app-utils/forms'\nimport { decodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport { NodeType, type NodesMap } from '@aglyn/aglyn/types/nodes'\nimport { duplicateResource } from '@aglyn/tenant-data-admin/server/duplicate-resource'\nimport type { AiJob, AiJobOutput, AiJobPlan, AiJobReview } from '../model/ai-jobs.types'\nimport { aiSiteSubmissions, aiSiteWords, type AiSiteSubmissions } from '../model/ai-site-job'\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 type { AiDoctrineTree, AiDoctrineViolation } from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { AI_PALETTE } from '../runtime/ai-palette.generated'\nimport type { AiSystemBlock, AiTool } from '../runtime/ai-runtime'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport { registerAiJobAdmission, type AiJobAdmission } from './ai-job-admission'\nimport {\n AI_FORM_DATASET_MADE_INPUT,\n aiBindFormToDataset,\n aiFormDatasetNote,\n aiFormDatasetPromptLine,\n aiReadFormDataset,\n type AiFormDataset,\n type AiFormDatasetBinding,\n type AiFormDatasetReadDeps,\n} from './ai-job-form-dataset'\nimport { aiJobPlanCreationsRefusal } from './ai-job-plan-creations'\nimport { aiJobDraftId } from './ai-job-draft-ids'\nimport {\n aiDraftAdmissionRefusal,\n aiDraftAllowanceRefusal,\n aiSiteSubdomain,\n readAiDraft,\n readAiDraftBandTakenSince,\n writeAiDraft,\n type AiDraftRecord,\n} from './ai-job-drafts'\nimport { AI_FORM_REUSED_NOTE, aiSiblingJobForm } from './ai-job-form-reuse'\nimport {\n aiBracketedFactsNote,\n aiConfirmedPlan,\n aiDoctrineReview,\n aiGenerationSpent,\n aiJobBriefLine,\n aiLimitReview,\n aiModelNodeIds,\n aiPlanCreation,\n aiPlanReferenceLines,\n aiUnspentOutcome,\n} from './ai-job-generation'\nimport type { AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The form step (AGL-2913): the generation step of a `form` job, run once a\n * member confirmed the job's plan.\n *\n * A form is two halves that must agree for its submissions to arrive: the\n * DESIGN a visitor fills in (`rootId`, `nodes`) and the DECLARATION the submit\n * route reads (`fields`, `consentFieldName`, `routing`). `checkFormContract`\n * is the rule that holds them together when a form is published. So the model\n * writes only the design, through `runValidatedGeneration('form', …)`, and\n * everything else is derived from it with the functions the publish paths\n * use:\n *\n * - `fields` is `formFieldDeclsFromNodes` over the design;\n * - a form that can yield an email address gets the platform's marketing\n * consent field (`aiFormConsentNodes`: a Choice Label holding one Checkbox,\n * worded as the Forms editor preset's option) in place of any consent-like\n * field the model drew, named as its `consentFieldName`;\n * - `routing` is `{ lead: true }` when the answer proposes a lead, and\n * nothing otherwise. The stored routing has no place for an email list,\n * so a list proposal leaves the form on the Inbox and says, in the output's\n * `note`, how to enroll the people who tick consent — naming a list only\n * when the brief named one. The step reads no list, contact, CRM record or\n * submission, and sends none.\n *\n * The design is then stamped the way the Forms page's Create stamps one — the\n * form node bound to the new form's id, a canvas root above it — and\n * `checkFormContract` runs on it through `extend`, beside the doctrine's own\n * checks, so a design the contract would refuse at publish is asked for again\n * with the violation named.\n *\n * The form lands as a new draft (`ai-job-drafts.ts`) that no page places and\n * nothing promotes. A plan that starts from a copy of a form the site has gets\n * that copy, through the platform's duplicate module, and nothing generated —\n * and because that path reaches no model, `extend` never runs on it, so the\n * step asks `checkFormContract` of the stored copy itself before it reports\n * one (AGL-3024). A copy still bound to the form it was copied from is a\n * failure, never an output.\n *\n * A site that holds every form its plan includes refuses the draft\n * (AGL-3765). A form the step builds for a page (a unit of a page job, a\n * guided start or a build) then places the form another AI job made on the\n * site moments before (`ai-job-form-reuse.ts`), as two jobs started from one\n * brief race to. Failing that, a site that still had room when the plan was\n * confirmed stops the job on our side, its credits given back; one that was\n * already full is the workspace's limit, for the member to change.\n *\n * Like the other generation steps, it runs on the job beat, never at an inline\n * door: it registers the least time its lookup rounds, its answer and its\n * re-ask need (AGL-3035), and runs without extended thinking under the routing\n * table's ceiling for a form, which is the doctrine's own.\n */\n\n/**\n * The longest answer a form may run to: the routing table's `job.form`\n * ceiling, which holds the largest form the output budget admits\n * (`ai-job-form-step.spec.ts` measures it) and is the doctrine's ceiling for\n * the form kind.\n */\nexport const AI_JOB_FORM_MAX_TOKENS = AI_ROUTING_TABLE['job.form'].maxTokens\n\n/**\n * The form step's time (AGL-3035, AGL-3036): its two inventory-lookup rounds,\n * its answer and its re-ask at that ceiling on the tier `job.form` is served\n * from, fitted to what a beat can give a step.\n */\nexport const AI_JOB_FORM_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.form'],\n maxTokens: AI_JOB_FORM_MAX_TOKENS,\n})\n\n/** The least time one form step needs before it starts. */\nexport const AI_JOB_FORM_STEP_MINIMUM_MS = AI_JOB_FORM_STEP_BUDGET.minimumMs\n\n/** A form's name when the plan names none. */\nexport const AI_JOB_FORM_DEFAULT_NAME = 'New form'\n\n/** Where a proposal routes a form's submissions. */\nexport const AI_FORM_ROUTING_KINDS = ['inbox', 'list', 'lead'] as const\n\nexport type AiFormRoutingKind = (typeof AI_FORM_ROUTING_KINDS)[number]\n\n/** The most things a note says the brief asked for and a form cannot collect. */\nexport const AI_FORM_CANNOT_COLLECT_MAX = 3\n\nconst CANNOT_COLLECT_MAX_CHARS = 60\nconst LIST_NAME_MAX_CHARS = 80\n\n/**\n * The node id the platform's consent field takes in a generated design: the\n * Choice Label that holds its Checkbox.\n */\nexport const AI_FORM_CONSENT_NODE_ID = 'marketingConsentField'\n\n/** The node id of the consent field's Checkbox, inside {@link AI_FORM_CONSENT_NODE_ID}. */\nexport const AI_FORM_CONSENT_CHECKBOX_NODE_ID = 'marketingConsentCheckbox'\n\n/** The name the consent Checkbox submits under, and the form's `consentFieldName`. */\nexport const AI_FORM_CONSENT_FIELD_NAME = MARKETING_CONSENT_FORM_FIELD.fieldName\n\n/** What a ticked consent Checkbox posts: an affirmative value `isConsentCheckboxTicked` reads as the tick. */\nexport const AI_FORM_CONSENT_VALUE = 'Yes'\n\n/**\n * The platform's marketing consent field as MUI's separate elements: a Choice\n * Label whose words say what the person agrees to — the Forms editor preset's\n * own option text — holding one unticked, unrequired Checkbox named\n * `marketingConsent`. Ids are fixed, so a re-asked design gets the same nodes.\n */\nexport function aiFormConsentNodes(formNodeId: string): NodesMap[string][] {\n const { choiceLabel, checkbox } = FORM_INPUT_ELEMENT_IDS\n return [\n {\n $id: AI_FORM_CONSENT_NODE_ID,\n type: NodeType.NODE,\n componentId: choiceLabel,\n pluginId: AI_PALETTE[choiceLabel]?.pluginId,\n parentId: formNodeId,\n nodes: [AI_FORM_CONSENT_CHECKBOX_NODE_ID],\n props: { label: MARKETING_CONSENT_FORM_FIELD.options },\n } as NodesMap[string],\n {\n $id: AI_FORM_CONSENT_CHECKBOX_NODE_ID,\n type: NodeType.NODE,\n componentId: checkbox,\n pluginId: AI_PALETTE[checkbox]?.pluginId,\n parentId: AI_FORM_CONSENT_NODE_ID,\n nodes: [],\n props: { name: AI_FORM_CONSENT_FIELD_NAME, value: AI_FORM_CONSENT_VALUE },\n } as NodesMap[string],\n ]\n}\n\n/**\n * The node to remove for a consent input the model drew: the input itself,\n * or the Choice Label and Form Control around it when they frame nothing but\n * consent — so no empty label or orphaned Form Label is left behind. The\n * all-in-one Form Field of an older design is its own frame.\n */\nfunction consentWrapperId(nodes: NodesMap, inputId: string, formNodeId: string): string {\n const framing = new Set<string>([FORM_INPUT_ELEMENT_IDS.choiceLabel, FORM_INPUT_ELEMENT_IDS.formControl])\n let outer = inputId\n let parentId = String(nodes[inputId]?.parentId ?? '')\n while (parentId && parentId !== formNodeId) {\n const parent = nodes[parentId]\n if (!parent || !framing.has(String(parent.componentId))) break\n const answers = collectFormFieldNodeIds(nodes as never, parentId)\n if (!answers.every((id) => isMarketingConsentFieldName(formInputName(nodes[id] as never)))) break\n outer = parentId\n parentId = String(parent.parentId ?? '')\n }\n return outer\n}\n\n/** Removes a node and everything under it, and its id from its parent's children. */\nfunction removeSubtree(nodes: NodesMap, id: string): void {\n const parent = nodes[String(nodes[id]?.parentId ?? '')]\n if (parent && Array.isArray(parent.nodes)) {\n parent.nodes = (parent.nodes as string[]).filter((child) => child !== id)\n }\n const stack = [id]\n while (stack.length) {\n const next = stack.pop() as string\n const node = nodes[next]\n if (!node) continue\n if (Array.isArray(node.nodes)) stack.push(...(node.nodes as string[]))\n delete nodes[next]\n }\n}\n\n/** The form step's own instructions, cached after the doctrine. */\nexport const AI_JOB_FORM_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n 'You build one form for a website: the fields a visitor fills in and the button that sends them. Answer with submit_form: the whole form as one flat node map, how its submissions are routed, and what the brief asks for that a form cannot collect.',\n 'The root is one Form (form) holding its fields in the order a visitor fills them in. Each piece of a field is its own element: a field is a Form Control (muiFormControl) holding a Form Label (muiFormLabel) whose text a visitor reads, then the answer, then optionally Helper Text (muiFormHelperText). Give the form a submitLabel and a successMessage in the site’s voice. The Form draws its own button, so a Button (muiButton) with type submit is optional.',\n 'The answer is an Input (muiInput) to type in: type email for an email address, tel for a phone number, multiline true for a description; a Select (muiSelect) holding one Select Option (muiSelectOption) per choice, or a Radio Group (muiRadioGroup) holding one Choice Label (muiFormControlLabel) per choice, each holding a Radio (muiRadio) whose value is the choice, for one choice; a Choice Label holding a Checkbox (muiCheckbox) per choice, the Checkboxes sharing one name, for several; and a Rating (muiRating) for a score. A single yes-or-no tick is a Choice Label holding one Checkbox, outside any Form Control.',\n 'Every Input, Select, Radio Group, Checkbox and Rating has a name that is unique in the form, apart from Checkboxes of one question, and says what it holds in camelCase, such as fullName, email, phone or roofType; and required only when the form cannot do its job without it.',\n 'A form collects text, choices and ratings only. When the brief asks for something else, such as a file or photo upload, a signature or a payment, leave it out and name it in cannotCollect.',\n 'Never draw a marketing consent, newsletter or subscribe checkbox: when the form asks for an email address, the platform adds its own.',\n 'routing.kind is inbox when submissions only need to be read, lead when each one is a sales lead to follow up, and list when the people who send it should join an email list. routing.list is the list’s name only when the brief names one, and null otherwise.',\n ].join('\\n'),\n },\n]\n\nconst TREE_TOOL = aiDoctrineTreeTool('form')\n\n/**\n * The doctrine's form tree tool, with the two things a design cannot say: the\n * routing it proposes and what the brief asked for that no field can collect.\n * Structured fields only, so the step writes every sentence a person reads.\n */\nexport const AI_JOB_FORM_TOOL: AiTool = {\n name: TREE_TOOL.name,\n description:\n 'Submit the form as one flat node map, how its submissions are routed, and what the brief asks for that a form cannot collect.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['tree', 'routing', 'cannotCollect'],\n properties: {\n tree: (TREE_TOOL.inputSchema['properties'] as Record<string, unknown>)['tree'],\n routing: {\n type: 'object',\n additionalProperties: false,\n required: ['kind', 'list'],\n properties: {\n kind: {\n type: 'string',\n enum: [...AI_FORM_ROUTING_KINDS],\n description:\n 'inbox: submissions are read in the Inbox. lead: each submission with an email address is a sales lead. list: the people who send it should join an email list.',\n },\n list: {\n anyOf: [{ type: 'string' }, { type: 'null' }],\n description: 'The email list the brief names, as it names it; null when it names none.',\n },\n },\n },\n cannotCollect: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'What the brief asks the form to collect that its field types cannot, a few words each, such as \"photo upload\"; empty when there is nothing.',\n },\n },\n },\n}\n\n/** The routing and the gaps an answer proposes, read defensively. */\nexport interface AiFormAnswer {\n routing: { kind: AiFormRoutingKind; list: string | null }\n cannotCollect: string[]\n}\n\n/**\n * What the person already decided about this form, where they were asked\n * (AGL-2918).\n *\n * Only the guided start asks, so only a scaffold's form unit carries one.\n * Whether a submission is a note to read or a lead to chase is a fact about\n * how a business runs, not something readable off a brief, so an answer here\n * BINDS the routing instead of joining the evidence the model weighs: a\n * person who said \"the Inbox\" and got a form filing leads would have been\n * asked a question for nothing.\n */\nexport interface AiFormDecisions {\n /** Where submissions go; `null` where nobody was asked. */\n submissions: AiSiteSubmissions | null\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction oneLine(value: string, max: number): string {\n return value.replace(/\\s+/g, ' ').trim().slice(0, max).trim()\n}\n\n/**\n * An answer's routing and gaps: an unknown kind is the Inbox, and the rest is\n * trimmed and capped. Where the person was asked where submissions go, their\n * answer replaces the model's proposal — the whole of the difference a\n * question makes.\n */\nexport function parseAiFormAnswer(\n answer: Record<string, unknown>,\n decisions: AiFormDecisions = { submissions: null },\n): AiFormAnswer {\n const routing = isRecord(answer['routing']) ? answer['routing'] : {}\n const proposed = (AI_FORM_ROUTING_KINDS as readonly unknown[]).includes(routing['kind'])\n ? (routing['kind'] as AiFormRoutingKind)\n : 'inbox'\n const kind: AiFormRoutingKind = decisions.submissions ?? proposed\n const list = typeof routing['list'] === 'string' ? oneLine(routing['list'], LIST_NAME_MAX_CHARS) : ''\n const seen = new Set<string>()\n const cannotCollect: string[] = []\n for (const entry of Array.isArray(answer['cannotCollect']) ? answer['cannotCollect'] : []) {\n if (typeof entry !== 'string') continue\n const text = oneLine(entry, CANNOT_COLLECT_MAX_CHARS)\n if (!text || seen.has(text.toLowerCase())) continue\n seen.add(text.toLowerCase())\n cannotCollect.push(text)\n if (cannotCollect.length === AI_FORM_CANNOT_COLLECT_MAX) break\n }\n return { routing: { kind, list: kind === 'list' && list ? list : null }, cannotCollect }\n}\n\n/** A generated form as its draft is written: the stamped design and what it declares. */\nexport interface AiFormDraft {\n /** The design as the Forms page's Create stores one: a canvas root above the bound form. */\n nodes: NodesMap\n rootId: string\n formNodeId: string\n fields: FormFieldDecl[]\n consentFieldName: string | null\n routing: FormRouting | null\n answer: AiFormAnswer\n /** The dataset its submissions are also written to, and what was bound (AGL-3616). */\n dataset?: { dataset: AiFormDataset; binding: AiFormDatasetBinding }\n}\n\n/**\n * The draft a validated design and its answer make: the form node bound to\n * `formId` and captioned `name`, the platform's consent field when the\n * fields can yield an email address, the canvas root above, and the\n * declaration read off the result. A dataset binding is made only where the\n * plan said the form writes to one this step may bind (`identity.dataset`,\n * AGL-3616); any the model drew is dropped. Pure; the input tree is not\n * changed.\n */\nexport function aiFormDraft(\n tree: Pick<AiValidatedTree, 'rootId' | 'nodes'>,\n answer: Record<string, unknown>,\n identity: { formId: string; name: string; decisions?: AiFormDecisions; dataset?: AiFormDataset | null },\n): AiFormDraft {\n const parsed = parseAiFormAnswer(answer, identity.decisions ?? { submissions: null })\n const formNodeId = tree.rootId\n const nodes: NodesMap = {}\n for (const [id, node] of Object.entries(tree.nodes)) {\n nodes[id] = {\n ...node,\n props: { ...(node.props ?? {}) },\n nodes: Array.isArray(node.nodes) ? [...(node.nodes as string[])] : [],\n }\n }\n const form = nodes[formNodeId]\n let consentFieldName: string | null = null\n if (form?.componentId === FORM_COMPONENT_ID) {\n const props = form.props as Record<string, unknown>\n // A dataset binding decides where every submission is also written: the\n // plan's to say (AGL-3616), bound below, never the model's to draw.\n delete props['datasetId']\n delete props['datasetName']\n props[FORM_ID_PROP] = identity.formId\n props['formName'] = identity.name\n\n for (const id of collectFormFieldNodeIds(nodes as never, formNodeId)) {\n if (!nodes[id] || !isMarketingConsentFieldName(formInputName(nodes[id] as never))) continue\n removeSubtree(nodes, consentWrapperId(nodes, id, formNodeId))\n }\n if (formFieldsCanYieldAnEmail(formFieldDeclsFromNodes(nodes as never, formNodeId))) {\n for (const node of aiFormConsentNodes(formNodeId)) nodes[node.$id as string] = node\n form.nodes = [...(form.nodes as string[]), AI_FORM_CONSENT_NODE_ID]\n consentFieldName = AI_FORM_CONSENT_FIELD_NAME\n }\n form.parentId = CANVAS_ROOT_ELEMENT_ID\n }\n // The dataset the plan says the form writes to (AGL-3616), bound as the\n // Form element binds one.\n const dataset =\n identity.dataset && form?.componentId === FORM_COMPONENT_ID\n ? { dataset: identity.dataset, binding: aiBindFormToDataset(nodes, formNodeId, identity.dataset) }\n : undefined\n nodes[CANVAS_ROOT_ELEMENT_ID] = {\n $id: CANVAS_ROOT_ELEMENT_ID,\n componentId: 'div',\n nodes: [formNodeId],\n } as NodesMap[string]\n return {\n nodes,\n rootId: CANVAS_ROOT_ELEMENT_ID,\n formNodeId,\n fields: formFieldDeclsFromNodes(nodes as never, formNodeId),\n consentFieldName,\n routing: parsed.routing.kind === 'lead' ? { lead: true } : null,\n answer: parsed,\n ...(dataset ? { dataset } : {}),\n }\n}\n\n/**\n * What a draft would break once published, as building-rule violations\n * (rule 3: a form is built with its fields, validation, consent and routing\n * together): the form contract's findings, a form with no field, and a list\n * proposal on a form that asks for no email address. Offending nodes are\n * named by the ids the model wrote.\n */\nexport function aiFormDraftViolations(\n draft: AiFormDraft,\n formId: string,\n sourceIds: Readonly<Record<string, string>>,\n): AiDoctrineViolation[] {\n const violations: AiDoctrineViolation[] = checkFormContract({\n form: {\n ...(draft.routing ? { routing: draft.routing } : {}),\n ...(draft.consentFieldName ? { consentFieldName: draft.consentFieldName } : {}),\n },\n formId,\n nodes: draft.nodes as never,\n formNodeId: draft.formNodeId,\n }).map((violation) => ({\n rule: 3 as const,\n code: violation.code,\n message: violation.message,\n ...(violation.nodeId ? { nodeIds: aiModelNodeIds([violation.nodeId], sourceIds) } : {}),\n }))\n if (!draft.fields.length) {\n violations.push({\n rule: 3,\n code: 'form-has-no-fields',\n message:\n 'This form has no named fields, so a visitor has nothing to fill in. Draw the fields the brief asks for.',\n })\n }\n if (draft.answer.routing.kind === 'list' && !formFieldsCanYieldAnEmail(draft.fields)) {\n violations.push({\n rule: 3,\n code: 'list-routing-has-no-email-field',\n message:\n 'This form proposes adding the people who send it to an email list, and it asks for no email address. Add an email field, or route its submissions to the Inbox.',\n paths: ['routing.kind'],\n })\n }\n return violations\n}\n\n/**\n * The door's check for `extend`, and the draft each admitted tree made: the\n * tree a generation returns is the object its last check saw, so the step\n * writes exactly the draft the contract passed.\n */\nexport function aiFormDraftCheck(identity: {\n formId: string\n name: string\n decisions?: AiFormDecisions\n dataset?: AiFormDataset | null\n}): {\n extend: (tree: AiValidatedTree, answer: Record<string, unknown>) => AiDoctrineViolation[]\n draftFor: (tree: AiValidatedTree) => AiFormDraft | undefined\n} {\n const drafts = new WeakMap<AiValidatedTree, AiFormDraft>()\n return {\n extend: (tree, answer) => {\n const draft = aiFormDraft(tree, answer, identity)\n drafts.set(tree, draft)\n return aiFormDraftViolations(draft, identity.formId, tree.sourceIds)\n },\n draftFor: (tree) => drafts.get(tree),\n }\n}\n\n/**\n * What a job says when the copy it asked for came back naming the form it\n * was copied FROM (AGL-3024). The contract's own sentence follows it and\n * names the consequence; this one names what to do about it.\n */\nexport const AI_FORM_COPY_UNBOUND_FAILURE =\n 'The copy of that form did not take on an identity of its own, so it is on ' +\n 'the site and not safe to collect with — delete it in Forms and try again.'\n\n/**\n * Whether the copy the platform just wrote is bound to ITSELF, asked of the\n * document rather than of the answer — `null` when it is, and the sentence a\n * person reads when it is not.\n *\n * ## Why a step that generated nothing still has something to check\n *\n * A \"creates X from a copy of Y\" plan reaches no model: the copy IS the\n * output, so there is no answer for the doctrine to refuse and `extend`\n * never runs. That left the one thing a copy can get wrong unasked. A form's\n * design names its own form inside itself, and a copy that kept the source's\n * name files every submission under the source — the console's form page\n * banners exactly this, and the job reported Done beside it.\n *\n * So the check is `checkFormContract`, the SAME function the console's\n * banner and the promotion route ask, run here on the stored copy. Not a\n * second predicate shaped like it: a copy this one passed and that one\n * refused would be a form the job called finished and the console called\n * broken, which is the state this exists to make impossible.\n *\n * Narrowed to `form-id-unbound`, and only that, because it is the one\n * violation duplication CAUSES. Every other code the contract can report —\n * an unnamed field, a consent field the design lost — the copy inherited\n * from a form the site already has and the member chose to copy; refusing\n * those would be refusing to copy a form they can already see.\n */\nexport async function aiFormCopyUnboundFailure(\n firestore: FirebaseFirestore.Firestore,\n copy: { hostId: string; formId: string },\n): Promise<string | null> {\n const snapshot = await firestore\n .collection('hosts')\n .doc(copy.hostId)\n .collection('forms')\n .doc(copy.formId)\n .get()\n const form = (snapshot.data() ?? null) as Partial<FormDocument> | null\n const nodes = decodeStoredNodes(form?.nodes)\n const unbound = checkFormContract({\n form,\n formId: copy.formId,\n nodes: nodes as never,\n formNodeId: formNodeIdIn(nodes as never),\n }).find((violation) => violation.code === 'form-id-unbound')\n return unbound ? `${AI_FORM_COPY_UNBOUND_FAILURE} ${unbound.message}` : null\n}\n\n/**\n * The fields the confirmed plan gives the form, against the form a COPY\n * actually produced (AGL-3024); `null` when the copy keeps the plan, or when\n * the plan promised no field to keep.\n *\n * The fourth kind to need this, after the layout, the page and the component.\n * `aiFormCopyUnboundFailure` above already refuses the one violation\n * duplication CAUSES; this refuses the one duplication HIDES — a plan reading\n * \"start from the consultation form and add a case-type question\" getting the\n * consultation form and nothing else, reported as built.\n *\n * A field the plan names is matched on its name alone: a copy that collects\n * the answer under a different label is still collecting it, and this check\n * has no way to tell a renamed field from a missing one without guessing.\n */\nexport async function aiCopiedFormReview(\n firestore: FirebaseFirestore.Firestore,\n input: { hostId: string; formId: string; name: string; plan: AiJobPlan | null },\n): Promise<AiJobReview | null> {\n const promised = (aiPlanCreation(input.plan, 'form')?.fields ?? [])\n .map((field) => field.split(':')[0]?.trim().toLowerCase())\n .filter((field): field is string => Boolean(field))\n if (!promised.length) return null\n const snapshot = await firestore\n .collection('hosts')\n .doc(input.hostId)\n .collection('forms')\n .doc(input.formId)\n .get()\n if (!snapshot.exists) {\n return {\n reason: 'doctrine',\n message: `\"${input.name}\" was copied from the form the plan names, and this job could not read the copy back to check it collects what the plan gives it. Open the form and check it before you put it on a page.`,\n findings: [],\n }\n }\n const fields = (snapshot.get('fields') ?? []) as unknown[]\n const collected = new Set(\n fields\n .map((field) =>\n field && typeof field === 'object'\n ? String((field as Record<string, unknown>)['fieldName'] ?? (field as Record<string, unknown>)['name'] ?? '')\n : '',\n )\n .filter(Boolean)\n .map((name) => name.toLowerCase()),\n )\n const missing = promised.filter((name) => !collected.has(name))\n if (!missing.length) return null\n const one = missing.length === 1\n return aiDoctrineReview({\n message: `\"${input.name}\" is a copy of the form the plan names, and a copy is all it is: the plan gives it ${\n one ? 'a field' : 'fields'\n } the copy does not collect.`,\n violations: [\n {\n rule: null,\n code: 'plan-fields-missing',\n message: `The confirmed plan says this form collects ${missing.join(', ')}, and the copy collects ${\n collected.size ? [...collected].join(', ') : 'nothing'\n }. Add ${one ? 'it' : 'each of them'}, or the copy is the form it was copied from.`,\n },\n ],\n })\n}\n\n/**\n * What the form a short copy would have started from collects, as the build\n * that replaces the copy is told it (AGL-3143 §14): every field it asks for,\n * so the build keeps them beside what the plan adds. Empty when the form\n * cannot be read.\n */\nexport async function aiFormSourceLines(\n firestore: FirebaseFirestore.Firestore,\n input: { hostId: string; id: string; name: string },\n): Promise<string[]> {\n const snapshot = await firestore.collection('hosts').doc(input.hostId).collection('forms').doc(input.id).get()\n const fields = snapshot.exists ? ((snapshot.get('fields') ?? []) as unknown[]) : []\n const asked = fields.flatMap((field) => {\n if (!field || typeof field !== 'object') return []\n const row = field as Record<string, unknown>\n const name = String(row['fieldName'] ?? row['name'] ?? '').trim()\n if (!name) return []\n const fieldType = row['fieldType'] ?? row['type']\n const type = typeof fieldType === 'string' ? ` (${fieldType}${row['required'] ? ', required' : ''})` : ''\n return [`${name}${type}`]\n })\n if (!asked.length) return []\n return [\n `The plan starts from a copy of the form \"${input.name}\", which lacks part of what the plan gives it. Build from it: it collects ${asked.join(', ')}. Keep each of those, and add what the plan adds.`,\n ]\n}\n\nfunction listOf(items: readonly string[]): string {\n return items.length < 2\n ? items.join('')\n : `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`\n}\n\n/**\n * What the person decides next, in words the step writes itself: a lead\n * routing to keep or switch off, the list a proposal could not store, and what\n * the brief asked for that a form cannot collect. `null` when there is none.\n */\nexport function aiFormOutputNote(answer: AiFormAnswer): string | null {\n const sentences: string[] = []\n if (answer.routing.kind === 'lead') {\n sentences.push(\n 'Each submission with an email address also files a lead in CRM → Leads; you can switch that off on the form’s page.',\n )\n }\n if (answer.routing.kind === 'list') {\n const list = answer.routing.list ? `your \"${answer.routing.list}\" list` : 'an email list'\n sentences.push(\n `Submissions arrive in the Inbox. To add the people who tick \"${MARKETING_CONSENT_FORM_FIELD.options}\" to ${list}, add an action on form submissions in Automation that enrolls them.`,\n )\n }\n if (answer.cannotCollect.length) {\n sentences.push(\n `Forms cannot collect ${listOf(answer.cannotCollect)} yet, so this form leaves ${\n answer.cannotCollect.length === 1 ? 'it' : 'them'\n } out.`,\n )\n }\n return sentences.length ? sentences.join(' ') : null\n}\n\n/**\n * The form job as the generation's user turn: the name, who fills the form\n * in, the brief, and the confirmed plan.\n *\n * Who the form is for (AGL-2918) is the answer a contact form's FIELDS turn\n * on — a trades business asks where the work is, a practice asks what the\n * appointment is about — and it is not something a brief about a whole site\n * says in a place the form can find. It rides here, in the turn, because it\n * is one site's own words.\n *\n * Where submissions go rides here too, and it is NOT a hint: the step binds\n * the routing to it whatever the model answers. It is stated so the model\n * does not spend its answer proposing something that will be replaced, and\n * so a form told its submissions are leads asks for the address that makes\n * one.\n */\nexport function aiJobFormPrompt(\n job: Pick<AiJob, 'brief'>,\n plan: AiJobPlan | null,\n name: string,\n context: { audience?: string; submissions?: AiSiteSubmissions | null } = {},\n): string {\n const audience = (context.audience ?? '').trim()\n return [\n `Form name: ${name}`,\n audience ? `The people who fill it in: ${audience}` : '',\n context.submissions ? `Where its submissions go: ${SUBMISSION_WORDS[context.submissions]}` : '',\n aiJobBriefLine(job),\n ...aiPlanReferenceLines(plan),\n ]\n .filter(Boolean)\n .join('\\n')\n}\n\n/** What each decided routing is, said to the model the way the tool says it. */\nconst SUBMISSION_WORDS: Record<AiSiteSubmissions, string> = {\n inbox: 'the Inbox, to be read — routing.kind is inbox',\n lead: 'the Inbox, and each one with an email address is a sales lead — routing.kind is lead',\n}\n\n/**\n * A form job is admitted for a site of the job's own org whose plan has\n * forms, with a form to spare, and confirmed only for a plan that creates\n * nothing but the form: a form places nothing another job builds\n * (AGL-3143 §15).\n */\nexport const aiFormJobAdmission: AiJobAdmission = (context) =>\n aiDraftAdmissionRefusal(context.firestore, {\n orgId: context.orgId,\n hostId: context.hostId,\n kind: 'form',\n org: context.org,\n ownCheck: (hostId) => aiJobPlanCreationsRefusal('form', context, hostId),\n })\n\n/**\n * What a form step says when the site's last form was taken after its plan\n * was confirmed (AGL-3765): by another build running beside it, or by a\n * member. The failure is ours, so what the job spent is given back.\n */\nexport const AI_FORM_BAND_TAKEN_COPY =\n 'Another build on this site used the last form your plan includes while this one was running, so this one stopped. Describe it again to build it with the form the site has now.'\n\nexport interface AiJobFormStepDeps {\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 /** The data plugin's writer lookup the form's dataset is read through (AGL-3616); specs hand in a fake. */\n datasetWriterFor?: AiFormDatasetReadDeps['writerFor']\n /** The form another build just made that a refused unit places (AGL-3765); specs hand in a fake. */\n siblingForm?: typeof aiSiblingJobForm\n}\n\nexport function createAiJobFormStep(deps: AiJobFormStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const duplicate = deps.duplicate ?? duplicateResource\n const siblingForm = deps.siblingForm ?? aiSiblingJobForm\n return async ({ job, now, signal, firestore, modelFor }) => {\n const hostId = job.hostId\n if (!hostId) throw new Error('a form job names no site, and its admission refuses one')\n const output = (\n draft: AiDraftRecord,\n extra: { load?: AiLoadEstimate | null; note?: string | null } = {},\n ): AiJobOutput => ({\n resource: 'form',\n id: draft.id,\n versionId: draft.versionId,\n hostId,\n hostSubdomain: draft.hostSubdomain,\n label: draft.name,\n ...(extra.load ? { load: extra.load } : {}),\n ...(extra.note ? { note: extra.note } : {}),\n })\n // The switch's answer for this job, else the routing table's (AGL-2942).\n const model = modelFor?.('job.form') ?? aiModelForStep('job.form')\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, 'form')\n const written = await readAiDraft(firestore, { kind: 'form', hostId, id: draftId })\n if (written) return aiUnspentOutcome(model, { outputs: [output(written)] })\n\n const [inventory, orgSnapshot] = await Promise.all([\n readInventory(job.orgId, hostId, { firestore }),\n firestore.collection('orgs').doc(job.orgId).get(),\n ])\n const org = (orgSnapshot.data() ?? null) as Partial<AglynOrgBilling> | null\n const plan = aiConfirmedPlan(job)\n const creation = aiPlanCreation(plan, 'form')\n const name = creation?.name || AI_JOB_FORM_DEFAULT_NAME\n // The site holds every form its plan includes (AGL-3765). A unit places a\n // form another build on this site just made, as its page would place any\n // form the site has. Otherwise a site that had room when the plan was\n // confirmed and was filled since stopped this job on our side, given\n // back; one that was already full is the workspace's limit to change. A\n // lookup that fails leaves the refusal as it was.\n const refused = async (\n refusal: string,\n spent: Pick<AiJobStepOutcome, 'outputs' | 'usage' | 'estCostUsd' | 'model' | 'stopReason'>,\n ): Promise<AiJobStepOutcome> => {\n const lookup = async <T>(read: () => Promise<T>, fallback: T): Promise<T> => {\n try {\n return await read()\n } catch (error) {\n console.error('ai form step: band refusal lookup failed', { jobId: job.$id, hostId, error })\n return fallback\n }\n }\n const reused = await lookup(() => siblingForm(firestore, { job, now }), null)\n if (reused) return { ...spent, outputs: [output(reused, { note: AI_FORM_REUSED_NOTE })] }\n const taken = await lookup(\n () => readAiDraftBandTakenSince(firestore, { kind: 'form', hostId, org, since: plan?.confirmedAt }),\n false,\n )\n if (taken) return { ...spent, failure: AI_FORM_BAND_TAKEN_COPY }\n return { ...spent, review: aiLimitReview(refusal) }\n }\n\n // The plan starts from a copy of a form the site has (rule 15): the copy\n // is the draft, and nothing is generated. A source gone since the plan\n // was made is built from the brief instead, and one that does not collect\n // a field the plan gives the form is built from the plan, told what the\n // source collects (AGL-3143 §14): copying it could only end in the review\n // below. A source this step cannot read still copies.\n const source = creation?.duplicateOf\n ? inventory.forms.find((form) => form.id === creation.duplicateOf)\n : undefined\n const sourceReview = source\n ? await aiCopiedFormReview(firestore, { hostId, formId: source.id, name: source.name, plan })\n : null\n const sourceShort = Boolean(sourceReview?.findings.length)\n const sourceLines =\n source && sourceShort ? await aiFormSourceLines(firestore, { hostId, id: source.id, name: source.name }) : []\n if (creation?.duplicateOf && source && !sourceShort) {\n const copy = await duplicate('form', {\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 // The copy is the whole output, so the contract is asked of it here\n // or nowhere: a copy still bound to its source is not a form this\n // job may report as built (AGL-3024).\n const unbound = await aiFormCopyUnboundFailure(firestore, { hostId, formId: copy.id })\n if (unbound) return { ...aiUnspentOutcome(model), failure: unbound }\n const hostSubdomain = await aiSiteSubdomain(firestore, hostId)\n // And the one duplication hides: what the plan promised of the copy,\n // read back (AGL-3024). This branch generates nothing, so nothing\n // else can answer for it.\n const review = await aiCopiedFormReview(firestore, {\n hostId,\n formId: copy.id,\n name: copy.name,\n plan,\n })\n if (review) return aiUnspentOutcome(model, { review })\n return aiUnspentOutcome(model, {\n outputs: [output({ id: copy.id, versionId: copy.versionId, name: copy.name, hostSubdomain })],\n })\n }\n if (copy.ok === false && copy.status === 403) {\n return refused(copy.error, aiUnspentOutcome(model))\n }\n }\n\n const allowance = await aiDraftAllowanceRefusal(firestore, { kind: 'form', hostId, org })\n if (allowance) return refused(allowance, aiUnspentOutcome(model))\n\n // What the person answered about this form, where they were asked\n // (AGL-2918): a scaffold's form unit carries the guided start's inputs.\n const decisions: AiFormDecisions = { submissions: aiSiteSubmissions(job.inputs) }\n const { audience } = aiSiteWords(job.inputs)\n // The dataset the plan says the form writes to (AGL-3616), where this\n // workspace may bind one; otherwise the form is the form it always was.\n const dataset = await aiReadFormDataset(\n {\n hostId,\n id: creation?.writesTo,\n org,\n inventory,\n madeId: job.inputs?.[AI_FORM_DATASET_MADE_INPUT],\n },\n deps.datasetWriterFor ? { writerFor: deps.datasetWriterFor } : {},\n )\n const check = aiFormDraftCheck({ formId: draftId, name, decisions, dataset })\n const result = await runValidatedGeneration('form', {\n step: 'job.form',\n model,\n instructions: AI_JOB_FORM_INSTRUCTIONS,\n inventory,\n messages: [\n {\n role: 'user',\n content: [\n aiJobFormPrompt(job, plan, name, {\n audience,\n submissions: decisions.submissions,\n }),\n ...sourceLines,\n ...(dataset ? [aiFormDatasetPromptLine(dataset)] : []),\n ].join('\\n'),\n },\n ],\n tool: AI_JOB_FORM_TOOL,\n maxTokens: AI_JOB_FORM_STEP_BUDGET.maxTokens(model),\n thinking: 'off',\n extend: check.extend,\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 = check.draftFor(result.value)\n if (!draft) throw new Error('a form the doctrine admitted has no draft from its check')\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const write = await writeAiDraft(firestore, {\n kind: 'form',\n hostId,\n id: draftId,\n uid: job.createdBy,\n org,\n name,\n nodes: draft.nodes,\n form: {\n rootId: draft.rootId,\n formNodeId: draft.formNodeId,\n fields: draft.fields,\n consentFieldName: draft.consentFieldName,\n routing: draft.routing,\n },\n now,\n })\n if (write.ok === false) {\n if (write.status === 404) throw new Error(`site ${hostId} vanished while its form was generated`)\n return refused(write.error, spent)\n }\n // What the person decides next, then the facts the brief did not give (AGL-3056).\n const note = [\n aiFormOutputNote(draft.answer),\n draft.dataset ? aiFormDatasetNote(draft.dataset.dataset, draft.dataset.binding) : null,\n aiBracketedFactsNote({\n tree: { rootId: result.value.rootId, nodes: result.value.nodes as unknown as AiDoctrineTree['nodes'] },\n inventory,\n }),\n ]\n .filter(Boolean)\n .join(' ')\n return {\n ...spent,\n outputs: [output(write, { load: result.value.load, note })],\n }\n }\n}\n\nexport const runAiJobFormStep = createAiJobFormStep()\n\n/** Registers the form step and the check a form job passes before it is created or resumed. */\nexport function registerAiFormJob(): void {\n registerAiJobStep('form', runAiJobFormStep, { minimumMs: AI_JOB_FORM_STEP_MINIMUM_MS })\n registerAiJobAdmission('form', aiFormJobAdmission)\n}\n"],"names":["throwIfAiJobCanceled","checkFormContract","formFieldsCanYieldAnEmail","collectFormFieldNodeIds","FORM_COMPONENT_ID","FORM_ID_PROP","FORM_INPUT_ELEMENT_IDS","formFieldDeclsFromNodes","formInputName","formNodeIdIn","isMarketingConsentFieldName","MARKETING_CONSENT_FORM_FIELD","decodeStoredNodes","CANVAS_ROOT_ELEMENT_ID","NodeType","duplicateResource","aiSiteSubmissions","aiSiteWords","AI_STEP_TIERS","AI_ROUTING_TABLE","aiModelForStep","aiDoctrineTreeTool","runValidatedGeneration","AI_PALETTE","readSiteInventory","registerAiJobAdmission","AI_FORM_DATASET_MADE_INPUT","aiBindFormToDataset","aiFormDatasetNote","aiFormDatasetPromptLine","aiReadFormDataset","aiJobPlanCreationsRefusal","aiJobDraftId","aiDraftAdmissionRefusal","aiDraftAllowanceRefusal","aiSiteSubdomain","readAiDraft","readAiDraftBandTakenSince","writeAiDraft","AI_FORM_REUSED_NOTE","aiSiblingJobForm","aiBracketedFactsNote","aiConfirmedPlan","aiDoctrineReview","aiGenerationSpent","aiJobBriefLine","aiLimitReview","aiModelNodeIds","aiPlanCreation","aiPlanReferenceLines","aiUnspentOutcome","aiJobStepBudget","registerAiJobStep","AI_JOB_FORM_MAX_TOKENS","maxTokens","AI_JOB_FORM_STEP_BUDGET","tier","AI_JOB_FORM_STEP_MINIMUM_MS","minimumMs","AI_JOB_FORM_DEFAULT_NAME","AI_FORM_ROUTING_KINDS","AI_FORM_CANNOT_COLLECT_MAX","CANNOT_COLLECT_MAX_CHARS","LIST_NAME_MAX_CHARS","AI_FORM_CONSENT_NODE_ID","AI_FORM_CONSENT_CHECKBOX_NODE_ID","AI_FORM_CONSENT_FIELD_NAME","fieldName","AI_FORM_CONSENT_VALUE","aiFormConsentNodes","formNodeId","choiceLabel","checkbox","$id","type","NODE","componentId","pluginId","parentId","nodes","props","label","options","name","value","consentWrapperId","inputId","framing","Set","formControl","outer","String","parent","has","answers","every","id","removeSubtree","Array","isArray","filter","child","stack","length","next","pop","node","push","AI_JOB_FORM_INSTRUCTIONS","text","join","TREE_TOOL","AI_JOB_FORM_TOOL","description","strict","inputSchema","additionalProperties","required","properties","tree","routing","kind","enum","list","anyOf","cannotCollect","items","isRecord","oneLine","max","replace","trim","slice","parseAiFormAnswer","answer","decisions","submissions","proposed","includes","seen","entry","toLowerCase","add","aiFormDraft","identity","parsed","rootId","Object","entries","form","consentFieldName","formId","dataset","binding","undefined","fields","lead","aiFormDraftViolations","draft","sourceIds","violations","map","violation","rule","code","message","nodeId","nodeIds","paths","aiFormDraftCheck","drafts","WeakMap","extend","set","draftFor","get","AI_FORM_COPY_UNBOUND_FAILURE","aiFormCopyUnboundFailure","firestore","copy","snapshot","collection","doc","hostId","data","unbound","find","aiCopiedFormReview","input","promised","plan","field","split","Boolean","exists","reason","findings","collected","missing","one","size","aiFormSourceLines","asked","flatMap","row","fieldType","listOf","aiFormOutputNote","sentences","aiJobFormPrompt","job","context","audience","SUBMISSION_WORDS","inbox","aiFormJobAdmission","orgId","org","ownCheck","AI_FORM_BAND_TAKEN_COPY","createAiJobFormStep","deps","readInventory","duplicate","siblingForm","now","signal","modelFor","orgSnapshot","Error","output","extra","resource","versionId","hostSubdomain","load","note","model","draftId","written","outputs","inventory","Promise","all","creation","refused","refusal","spent","lookup","read","fallback","error","console","jobId","reused","taken","since","confirmedAt","failure","review","source","duplicateOf","forms","sourceReview","sourceShort","sourceLines","sourceId","uid","createdBy","attemptKey","ok","status","allowance","inputs","writesTo","madeId","datasetWriterFor","writerFor","check","result","step","instructions","messages","role","content","tool","thinking","write","runAiJobFormStep","registerAiFormJob"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,qBAAiB;AACtD,SACEC,iBAAiB,EACjBC,yBAAyB,QACpB,uCAAsC;AAC7C,SACEC,uBAAuB,EACvBC,iBAAiB,EACjBC,YAAY,EACZC,sBAAsB,EACtBC,uBAAuB,EACvBC,aAAa,EACbC,YAAY,EACZC,2BAA2B,EAC3BC,4BAA4B,QAIvB,+BAA8B;AACrC,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SAASC,sBAAsB,QAAQ,2CAA0C;AAEjF,SAASC,QAAQ,QAAuB,2BAA0B;AAClE,SAASC,iBAAiB,QAAQ,qDAAoD;AAEtF,SAASC,iBAAiB,EAAEC,WAAW,QAAgC,0BAAsB;AAC7F,SAASC,aAAa,QAAQ,0BAAsB;AACpD,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,0BAAsB;AACvE,SACEC,kBAAkB,EAClBC,sBAAsB,QAEjB,4BAAwB;AAG/B,SAASC,UAAU,QAAQ,qCAAiC;AAE5D,SAASC,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AAK,OAAO;YACtB,IAAIiB,MAAMhB,MAAM,KAAK,KAAK,MAAM,IAAI1C,MAAM,CAAC,KAAK,EAAE9C,OAAO,sCAAsC,CAAC;YAChG,OAAO8D,QAAQ0C,MAAMpC,KAAK,EAAEJ;QAC9B;QACA,kFAAkF;QAClF,MAAMX,OAAO;YACX7B,iBAAiBjD,MAAMxB,MAAM;YAC7BwB,MAAMN,OAAO,GAAG5H,kBAAkBkI,MAAMN,OAAO,CAACA,OAAO,EAAEM,MAAMN,OAAO,CAACC,OAAO,IAAI;YAClFhH,qBAAqB;gBACnB8E,MAAM;oBAAE2B,QAAQqI,OAAOnM,KAAK,CAAC8D,MAAM;oBAAEnE,OAAOwM,OAAOnM,KAAK,CAACL,KAAK;gBAAuC;gBACrGkK;YACF;SACD,CACE7I,MAAM,CAAC6F,SACPnF,IAAI,CAAC;QACR,OAAO,aACFyI;YACHP,SAAS;gBAACV,OAAOyD,OAAO;oBAAEpD,MAAM4C,OAAOnM,KAAK,CAACuJ,IAAI;oBAAEC;gBAAK;aAAG;;IAE/D;AACF;AAEA,OAAO,MAAMoD,mBAAmBpE,sBAAqB;AAErD,6FAA6F,GAC7F,OAAO,SAASqE;IACd7O,kBAAkB,QAAQ4O,kBAAkB;QAAEtO,WAAWD;IAA4B;IACrFhC,uBAAuB,QAAQ8L;AACjC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-form-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 { throwIfAiJobCanceled } from './ai-job-cancel'\nimport {\n checkFormContract,\n formFieldsCanYieldAnEmail,\n} from '@aglyn/aglyn/app-utils/form-contract'\nimport {\n collectFormFieldNodeIds,\n FORM_COMPONENT_ID,\n FORM_ID_PROP,\n FORM_INPUT_ELEMENT_IDS,\n formFieldDeclsFromNodes,\n formInputName,\n formNodeIdIn,\n isMarketingConsentFieldName,\n MARKETING_CONSENT_FORM_FIELD,\n type FormDocument,\n type FormFieldDecl,\n type FormRouting,\n} from '@aglyn/aglyn/app-utils/forms'\nimport { decodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport { NodeType, type NodesMap } from '@aglyn/aglyn/types/nodes'\nimport { duplicateResource } from '@aglyn/tenant-data-admin/server/duplicate-resource'\nimport type { AiJob, AiJobOutput, AiJobPlan, AiJobReview } from '../model/ai-jobs.types'\nimport { aiSiteSubmissions, aiSiteWords, type AiSiteSubmissions } from '../model/ai-site-job'\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 type { AiDoctrineTree, AiDoctrineViolation } from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport { AI_PALETTE } from '../runtime/ai-palette.generated'\nimport type { AiSystemBlock, AiTool } from '../runtime/ai-runtime'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport { registerAiJobAdmission, type AiJobAdmission } from './ai-job-admission'\nimport {\n AI_FORM_DATASET_MADE_INPUT,\n aiBindFormToDataset,\n aiFormDatasetNote,\n aiFormDatasetPromptLine,\n aiReadFormDataset,\n type AiFormDataset,\n type AiFormDatasetBinding,\n type AiFormDatasetReadDeps,\n} from './ai-job-form-dataset'\nimport { aiJobPlanCreationsRefusal } from './ai-job-plan-creations'\nimport { aiJobDraftId } from './ai-job-draft-ids'\nimport {\n aiDraftAdmissionRefusal,\n aiDraftAllowanceRefusal,\n aiSiteSubdomain,\n readAiDraft,\n readAiDraftBandTakenSince,\n writeAiDraft,\n type AiDraftRecord,\n} from './ai-job-drafts'\nimport { AI_FORM_REUSED_NOTE, aiSiblingJobForm } from './ai-job-form-reuse'\nimport {\n aiBracketedFactsNote,\n aiConfirmedPlan,\n aiDoctrineReview,\n aiGenerationSpent,\n aiJobBriefLine,\n aiLimitReview,\n aiModelNodeIds,\n aiPlanCreation,\n aiPlanReferenceLines,\n aiUnspentOutcome,\n} from './ai-job-generation'\nimport type { AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The form step (AGL-2913): the generation step of a `form` job, run once a\n * member confirmed the job's plan.\n *\n * A form is two halves that must agree for its submissions to arrive: the\n * DESIGN a visitor fills in (`rootId`, `nodes`) and the DECLARATION the submit\n * route reads (`fields`, `consentFieldName`, `routing`). `checkFormContract`\n * is the rule that holds them together when a form is published. So the model\n * writes only the design, through `runValidatedGeneration('form', …)`, and\n * everything else is derived from it with the functions the publish paths\n * use:\n *\n * - `fields` is `formFieldDeclsFromNodes` over the design;\n * - a form that can yield an email address gets the platform's marketing\n * consent field (`aiFormConsentNodes`: a Choice Label holding one Checkbox,\n * worded as the Forms editor preset's option) in place of any consent-like\n * field the model drew, named as its `consentFieldName`;\n * - `routing` is `{ lead: true }` when the answer proposes a lead, and\n * nothing otherwise. The stored routing has no place for an email list,\n * so a list proposal leaves the form on the Inbox and says, in the output's\n * `note`, how to enroll the people who tick consent — naming a list only\n * when the brief named one. The step reads no list, contact, CRM record or\n * submission, and sends none.\n *\n * The design is then stamped the way the Forms page's Create stamps one — the\n * form node bound to the new form's id, a canvas root above it — and\n * `checkFormContract` runs on it through `extend`, beside the doctrine's own\n * checks, so a design the contract would refuse at publish is asked for again\n * with the violation named.\n *\n * The form lands as a new draft (`ai-job-drafts.ts`) that no page places and\n * nothing promotes. A plan that starts from a copy of a form the site has gets\n * that copy, through the platform's duplicate module, and nothing generated —\n * and because that path reaches no model, `extend` never runs on it, so the\n * step asks `checkFormContract` of the stored copy itself before it reports\n * one (AGL-3024). A copy still bound to the form it was copied from is a\n * failure, never an output.\n *\n * A site that holds every form its plan includes refuses the draft\n * (AGL-3765). A form the step builds for a page (a unit of a page job, a\n * guided start or a build) then places the form another AI job made on the\n * site moments before (`ai-job-form-reuse.ts`), as two jobs started from one\n * brief race to. Failing that, a site that still had room when the plan was\n * confirmed stops the job on our side, its credits given back; one that was\n * already full is the workspace's limit, for the member to change.\n *\n * Like the other generation steps, it runs on the job beat, never at an inline\n * door: it registers the least time its lookup rounds, its answer and its\n * re-ask need (AGL-3035), and runs without extended thinking under the routing\n * table's ceiling for a form, which is the doctrine's own.\n */\n\n/**\n * The longest answer a form may run to: the routing table's `job.form`\n * ceiling, which holds the largest form the output budget admits\n * (`ai-job-form-step.spec.ts` measures it) and is the doctrine's ceiling for\n * the form kind.\n */\nexport const AI_JOB_FORM_MAX_TOKENS = AI_ROUTING_TABLE['job.form'].maxTokens\n\n/**\n * The form step's time (AGL-3035, AGL-3036): its two inventory-lookup rounds,\n * its answer and its re-ask at that ceiling on the tier `job.form` is served\n * from, fitted to what a beat can give a step.\n */\nexport const AI_JOB_FORM_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.form'],\n maxTokens: AI_JOB_FORM_MAX_TOKENS,\n})\n\n/** The least time one form step needs before it starts. */\nexport const AI_JOB_FORM_STEP_MINIMUM_MS = AI_JOB_FORM_STEP_BUDGET.minimumMs\n\n/** A form's name when the plan names none. */\nexport const AI_JOB_FORM_DEFAULT_NAME = 'New form'\n\n/** Where a proposal routes a form's submissions. */\nexport const AI_FORM_ROUTING_KINDS = ['inbox', 'list', 'lead'] as const\n\nexport type AiFormRoutingKind = (typeof AI_FORM_ROUTING_KINDS)[number]\n\n/** The most things a note says the brief asked for and a form cannot collect. */\nexport const AI_FORM_CANNOT_COLLECT_MAX = 3\n\nconst CANNOT_COLLECT_MAX_CHARS = 60\nconst LIST_NAME_MAX_CHARS = 80\n\n/**\n * The node id the platform's consent field takes in a generated design: the\n * Choice Label that holds its Checkbox.\n */\nexport const AI_FORM_CONSENT_NODE_ID = 'marketingConsentField'\n\n/** The node id of the consent field's Checkbox, inside {@link AI_FORM_CONSENT_NODE_ID}. */\nexport const AI_FORM_CONSENT_CHECKBOX_NODE_ID = 'marketingConsentCheckbox'\n\n/** The name the consent Checkbox submits under, and the form's `consentFieldName`. */\nexport const AI_FORM_CONSENT_FIELD_NAME = MARKETING_CONSENT_FORM_FIELD.fieldName\n\n/** What a ticked consent Checkbox posts: an affirmative value `isConsentCheckboxTicked` reads as the tick. */\nexport const AI_FORM_CONSENT_VALUE = 'Yes'\n\n/**\n * The platform's marketing consent field as MUI's separate elements: a Choice\n * Label whose words say what the person agrees to — the Forms editor preset's\n * own option text — holding one unticked, unrequired Checkbox named\n * `marketingConsent`. Ids are fixed, so a re-asked design gets the same nodes.\n */\nexport function aiFormConsentNodes(formNodeId: string): NodesMap[string][] {\n const { choiceLabel, checkbox } = FORM_INPUT_ELEMENT_IDS\n return [\n {\n $id: AI_FORM_CONSENT_NODE_ID,\n type: NodeType.NODE,\n componentId: choiceLabel,\n pluginId: AI_PALETTE[choiceLabel]?.pluginId,\n parentId: formNodeId,\n nodes: [AI_FORM_CONSENT_CHECKBOX_NODE_ID],\n props: { label: MARKETING_CONSENT_FORM_FIELD.options },\n } as NodesMap[string],\n {\n $id: AI_FORM_CONSENT_CHECKBOX_NODE_ID,\n type: NodeType.NODE,\n componentId: checkbox,\n pluginId: AI_PALETTE[checkbox]?.pluginId,\n parentId: AI_FORM_CONSENT_NODE_ID,\n nodes: [],\n props: { name: AI_FORM_CONSENT_FIELD_NAME, value: AI_FORM_CONSENT_VALUE },\n } as NodesMap[string],\n ]\n}\n\n/**\n * The node to remove for a consent input the model drew: the input itself,\n * or the Choice Label and Form Control around it when they frame nothing but\n * consent — so no empty label or orphaned Form Label is left behind. The\n * all-in-one Form Field of an older design is its own frame.\n */\nfunction consentWrapperId(nodes: NodesMap, inputId: string, formNodeId: string): string {\n const framing = new Set<string>([FORM_INPUT_ELEMENT_IDS.choiceLabel, FORM_INPUT_ELEMENT_IDS.formControl])\n let outer = inputId\n let parentId = String(nodes[inputId]?.parentId ?? '')\n while (parentId && parentId !== formNodeId) {\n const parent = nodes[parentId]\n if (!parent || !framing.has(String(parent.componentId))) break\n const answers = collectFormFieldNodeIds(nodes as never, parentId)\n if (!answers.every((id) => isMarketingConsentFieldName(formInputName(nodes[id] as never)))) break\n outer = parentId\n parentId = String(parent.parentId ?? '')\n }\n return outer\n}\n\n/** Removes a node and everything under it, and its id from its parent's children. */\nfunction removeSubtree(nodes: NodesMap, id: string): void {\n const parent = nodes[String(nodes[id]?.parentId ?? '')]\n if (parent && Array.isArray(parent.nodes)) {\n parent.nodes = (parent.nodes as string[]).filter((child) => child !== id)\n }\n const stack = [id]\n while (stack.length) {\n const next = stack.pop() as string\n const node = nodes[next]\n if (!node) continue\n if (Array.isArray(node.nodes)) stack.push(...(node.nodes as string[]))\n delete nodes[next]\n }\n}\n\n/** The form step's own instructions, cached after the doctrine. */\nexport const AI_JOB_FORM_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n 'You build one form for a website: the fields a visitor fills in and the button that sends them. Answer with submit_form: the whole form as one flat node map, how its submissions are routed, and what the brief asks for that a form cannot collect.',\n 'The root is one Form (form) holding its fields in the order a visitor fills them in. Each piece of a field is its own element: a field is a Form Control (muiFormControl) holding a Form Label (muiFormLabel) whose text a visitor reads, then the answer, then optionally Helper Text (muiFormHelperText). Give the form a submitLabel and a successMessage in the site’s voice. The Form draws its own button, so a Button (muiButton) with type submit is optional.',\n 'The answer is an Input (muiInput) to type in: type email for an email address, tel for a phone number, multiline true for a description; a Select (muiSelect) holding one Select Option (muiSelectOption) per choice, or a Radio Group (muiRadioGroup) holding one Choice Label (muiFormControlLabel) per choice, each holding a Radio (muiRadio) whose value is the choice, for one choice; a Choice Label holding a Checkbox (muiCheckbox) per choice, the Checkboxes sharing one name, for several; a Rating (muiRating) for a score; a Date Picker (muiDatePicker) for a day, such as a preferred date; and a Time Picker (muiTimePicker) for a time of day. A single yes-or-no tick is a Choice Label holding one Checkbox, outside any Form Control.',\n 'Every Input, Select, Radio Group, Checkbox, Rating, Date Picker and Time Picker has a name that is unique in the form, apart from Checkboxes of one question, and says what it holds in camelCase, such as fullName, email, phone or roofType; and required only when the form cannot do its job without it.',\n 'A form collects text, choices, ratings, dates and times only. When the brief asks for something else, such as a file or photo upload, a signature or a payment, leave it out and name it in cannotCollect.',\n 'Never draw a marketing consent, newsletter or subscribe checkbox: when the form asks for an email address, the platform adds its own.',\n 'routing.kind is inbox when submissions only need to be read, lead when each one is a sales lead to follow up, and list when the people who send it should join an email list. routing.list is the list’s name only when the brief names one, and null otherwise.',\n ].join('\\n'),\n },\n]\n\nconst TREE_TOOL = aiDoctrineTreeTool('form')\n\n/**\n * The doctrine's form tree tool, with the two things a design cannot say: the\n * routing it proposes and what the brief asked for that no field can collect.\n * Structured fields only, so the step writes every sentence a person reads.\n */\nexport const AI_JOB_FORM_TOOL: AiTool = {\n name: TREE_TOOL.name,\n description:\n 'Submit the form as one flat node map, how its submissions are routed, and what the brief asks for that a form cannot collect.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['tree', 'routing', 'cannotCollect'],\n properties: {\n tree: (TREE_TOOL.inputSchema['properties'] as Record<string, unknown>)['tree'],\n routing: {\n type: 'object',\n additionalProperties: false,\n required: ['kind', 'list'],\n properties: {\n kind: {\n type: 'string',\n enum: [...AI_FORM_ROUTING_KINDS],\n description:\n 'inbox: submissions are read in the Inbox. lead: each submission with an email address is a sales lead. list: the people who send it should join an email list.',\n },\n list: {\n anyOf: [{ type: 'string' }, { type: 'null' }],\n description: 'The email list the brief names, as it names it; null when it names none.',\n },\n },\n },\n cannotCollect: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'What the brief asks the form to collect that its field types cannot, a few words each, such as \"photo upload\"; empty when there is nothing.',\n },\n },\n },\n}\n\n/** The routing and the gaps an answer proposes, read defensively. */\nexport interface AiFormAnswer {\n routing: { kind: AiFormRoutingKind; list: string | null }\n cannotCollect: string[]\n}\n\n/**\n * What the person already decided about this form, where they were asked\n * (AGL-2918).\n *\n * Only the guided start asks, so only a scaffold's form unit carries one.\n * Whether a submission is a note to read or a lead to chase is a fact about\n * how a business runs, not something readable off a brief, so an answer here\n * BINDS the routing instead of joining the evidence the model weighs: a\n * person who said \"the Inbox\" and got a form filing leads would have been\n * asked a question for nothing.\n */\nexport interface AiFormDecisions {\n /** Where submissions go; `null` where nobody was asked. */\n submissions: AiSiteSubmissions | null\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction oneLine(value: string, max: number): string {\n return value.replace(/\\s+/g, ' ').trim().slice(0, max).trim()\n}\n\n/**\n * An answer's routing and gaps: an unknown kind is the Inbox, and the rest is\n * trimmed and capped. Where the person was asked where submissions go, their\n * answer replaces the model's proposal — the whole of the difference a\n * question makes.\n */\nexport function parseAiFormAnswer(\n answer: Record<string, unknown>,\n decisions: AiFormDecisions = { submissions: null },\n): AiFormAnswer {\n const routing = isRecord(answer['routing']) ? answer['routing'] : {}\n const proposed = (AI_FORM_ROUTING_KINDS as readonly unknown[]).includes(routing['kind'])\n ? (routing['kind'] as AiFormRoutingKind)\n : 'inbox'\n const kind: AiFormRoutingKind = decisions.submissions ?? proposed\n const list = typeof routing['list'] === 'string' ? oneLine(routing['list'], LIST_NAME_MAX_CHARS) : ''\n const seen = new Set<string>()\n const cannotCollect: string[] = []\n for (const entry of Array.isArray(answer['cannotCollect']) ? answer['cannotCollect'] : []) {\n if (typeof entry !== 'string') continue\n const text = oneLine(entry, CANNOT_COLLECT_MAX_CHARS)\n if (!text || seen.has(text.toLowerCase())) continue\n seen.add(text.toLowerCase())\n cannotCollect.push(text)\n if (cannotCollect.length === AI_FORM_CANNOT_COLLECT_MAX) break\n }\n return { routing: { kind, list: kind === 'list' && list ? list : null }, cannotCollect }\n}\n\n/** A generated form as its draft is written: the stamped design and what it declares. */\nexport interface AiFormDraft {\n /** The design as the Forms page's Create stores one: a canvas root above the bound form. */\n nodes: NodesMap\n rootId: string\n formNodeId: string\n fields: FormFieldDecl[]\n consentFieldName: string | null\n routing: FormRouting | null\n answer: AiFormAnswer\n /** The dataset its submissions are also written to, and what was bound (AGL-3616). */\n dataset?: { dataset: AiFormDataset; binding: AiFormDatasetBinding }\n}\n\n/**\n * The draft a validated design and its answer make: the form node bound to\n * `formId` and captioned `name`, the platform's consent field when the\n * fields can yield an email address, the canvas root above, and the\n * declaration read off the result. A dataset binding is made only where the\n * plan said the form writes to one this step may bind (`identity.dataset`,\n * AGL-3616); any the model drew is dropped. Pure; the input tree is not\n * changed.\n */\nexport function aiFormDraft(\n tree: Pick<AiValidatedTree, 'rootId' | 'nodes'>,\n answer: Record<string, unknown>,\n identity: { formId: string; name: string; decisions?: AiFormDecisions; dataset?: AiFormDataset | null },\n): AiFormDraft {\n const parsed = parseAiFormAnswer(answer, identity.decisions ?? { submissions: null })\n const formNodeId = tree.rootId\n const nodes: NodesMap = {}\n for (const [id, node] of Object.entries(tree.nodes)) {\n nodes[id] = {\n ...node,\n props: { ...(node.props ?? {}) },\n nodes: Array.isArray(node.nodes) ? [...(node.nodes as string[])] : [],\n }\n }\n const form = nodes[formNodeId]\n let consentFieldName: string | null = null\n if (form?.componentId === FORM_COMPONENT_ID) {\n const props = form.props as Record<string, unknown>\n // A dataset binding decides where every submission is also written: the\n // plan's to say (AGL-3616), bound below, never the model's to draw.\n delete props['datasetId']\n delete props['datasetName']\n props[FORM_ID_PROP] = identity.formId\n props['formName'] = identity.name\n\n for (const id of collectFormFieldNodeIds(nodes as never, formNodeId)) {\n if (!nodes[id] || !isMarketingConsentFieldName(formInputName(nodes[id] as never))) continue\n removeSubtree(nodes, consentWrapperId(nodes, id, formNodeId))\n }\n if (formFieldsCanYieldAnEmail(formFieldDeclsFromNodes(nodes as never, formNodeId))) {\n for (const node of aiFormConsentNodes(formNodeId)) nodes[node.$id as string] = node\n form.nodes = [...(form.nodes as string[]), AI_FORM_CONSENT_NODE_ID]\n consentFieldName = AI_FORM_CONSENT_FIELD_NAME\n }\n form.parentId = CANVAS_ROOT_ELEMENT_ID\n }\n // The dataset the plan says the form writes to (AGL-3616), bound as the\n // Form element binds one.\n const dataset =\n identity.dataset && form?.componentId === FORM_COMPONENT_ID\n ? { dataset: identity.dataset, binding: aiBindFormToDataset(nodes, formNodeId, identity.dataset) }\n : undefined\n nodes[CANVAS_ROOT_ELEMENT_ID] = {\n $id: CANVAS_ROOT_ELEMENT_ID,\n componentId: 'div',\n nodes: [formNodeId],\n } as NodesMap[string]\n return {\n nodes,\n rootId: CANVAS_ROOT_ELEMENT_ID,\n formNodeId,\n fields: formFieldDeclsFromNodes(nodes as never, formNodeId),\n consentFieldName,\n routing: parsed.routing.kind === 'lead' ? { lead: true } : null,\n answer: parsed,\n ...(dataset ? { dataset } : {}),\n }\n}\n\n/**\n * What a draft would break once published, as building-rule violations\n * (rule 3: a form is built with its fields, validation, consent and routing\n * together): the form contract's findings, a form with no field, and a list\n * proposal on a form that asks for no email address. Offending nodes are\n * named by the ids the model wrote.\n */\nexport function aiFormDraftViolations(\n draft: AiFormDraft,\n formId: string,\n sourceIds: Readonly<Record<string, string>>,\n): AiDoctrineViolation[] {\n const violations: AiDoctrineViolation[] = checkFormContract({\n form: {\n ...(draft.routing ? { routing: draft.routing } : {}),\n ...(draft.consentFieldName ? { consentFieldName: draft.consentFieldName } : {}),\n },\n formId,\n nodes: draft.nodes as never,\n formNodeId: draft.formNodeId,\n }).map((violation) => ({\n rule: 3 as const,\n code: violation.code,\n message: violation.message,\n ...(violation.nodeId ? { nodeIds: aiModelNodeIds([violation.nodeId], sourceIds) } : {}),\n }))\n if (!draft.fields.length) {\n violations.push({\n rule: 3,\n code: 'form-has-no-fields',\n message:\n 'This form has no named fields, so a visitor has nothing to fill in. Draw the fields the brief asks for.',\n })\n }\n if (draft.answer.routing.kind === 'list' && !formFieldsCanYieldAnEmail(draft.fields)) {\n violations.push({\n rule: 3,\n code: 'list-routing-has-no-email-field',\n message:\n 'This form proposes adding the people who send it to an email list, and it asks for no email address. Add an email field, or route its submissions to the Inbox.',\n paths: ['routing.kind'],\n })\n }\n return violations\n}\n\n/**\n * The door's check for `extend`, and the draft each admitted tree made: the\n * tree a generation returns is the object its last check saw, so the step\n * writes exactly the draft the contract passed.\n */\nexport function aiFormDraftCheck(identity: {\n formId: string\n name: string\n decisions?: AiFormDecisions\n dataset?: AiFormDataset | null\n}): {\n extend: (tree: AiValidatedTree, answer: Record<string, unknown>) => AiDoctrineViolation[]\n draftFor: (tree: AiValidatedTree) => AiFormDraft | undefined\n} {\n const drafts = new WeakMap<AiValidatedTree, AiFormDraft>()\n return {\n extend: (tree, answer) => {\n const draft = aiFormDraft(tree, answer, identity)\n drafts.set(tree, draft)\n return aiFormDraftViolations(draft, identity.formId, tree.sourceIds)\n },\n draftFor: (tree) => drafts.get(tree),\n }\n}\n\n/**\n * What a job says when the copy it asked for came back naming the form it\n * was copied FROM (AGL-3024). The contract's own sentence follows it and\n * names the consequence; this one names what to do about it.\n */\nexport const AI_FORM_COPY_UNBOUND_FAILURE =\n 'The copy of that form did not take on an identity of its own, so it is on ' +\n 'the site and not safe to collect with — delete it in Forms and try again.'\n\n/**\n * Whether the copy the platform just wrote is bound to ITSELF, asked of the\n * document rather than of the answer — `null` when it is, and the sentence a\n * person reads when it is not.\n *\n * ## Why a step that generated nothing still has something to check\n *\n * A \"creates X from a copy of Y\" plan reaches no model: the copy IS the\n * output, so there is no answer for the doctrine to refuse and `extend`\n * never runs. That left the one thing a copy can get wrong unasked. A form's\n * design names its own form inside itself, and a copy that kept the source's\n * name files every submission under the source — the console's form page\n * banners exactly this, and the job reported Done beside it.\n *\n * So the check is `checkFormContract`, the SAME function the console's\n * banner and the promotion route ask, run here on the stored copy. Not a\n * second predicate shaped like it: a copy this one passed and that one\n * refused would be a form the job called finished and the console called\n * broken, which is the state this exists to make impossible.\n *\n * Narrowed to `form-id-unbound`, and only that, because it is the one\n * violation duplication CAUSES. Every other code the contract can report —\n * an unnamed field, a consent field the design lost — the copy inherited\n * from a form the site already has and the member chose to copy; refusing\n * those would be refusing to copy a form they can already see.\n */\nexport async function aiFormCopyUnboundFailure(\n firestore: FirebaseFirestore.Firestore,\n copy: { hostId: string; formId: string },\n): Promise<string | null> {\n const snapshot = await firestore\n .collection('hosts')\n .doc(copy.hostId)\n .collection('forms')\n .doc(copy.formId)\n .get()\n const form = (snapshot.data() ?? null) as Partial<FormDocument> | null\n const nodes = decodeStoredNodes(form?.nodes)\n const unbound = checkFormContract({\n form,\n formId: copy.formId,\n nodes: nodes as never,\n formNodeId: formNodeIdIn(nodes as never),\n }).find((violation) => violation.code === 'form-id-unbound')\n return unbound ? `${AI_FORM_COPY_UNBOUND_FAILURE} ${unbound.message}` : null\n}\n\n/**\n * The fields the confirmed plan gives the form, against the form a COPY\n * actually produced (AGL-3024); `null` when the copy keeps the plan, or when\n * the plan promised no field to keep.\n *\n * The fourth kind to need this, after the layout, the page and the component.\n * `aiFormCopyUnboundFailure` above already refuses the one violation\n * duplication CAUSES; this refuses the one duplication HIDES — a plan reading\n * \"start from the consultation form and add a case-type question\" getting the\n * consultation form and nothing else, reported as built.\n *\n * A field the plan names is matched on its name alone: a copy that collects\n * the answer under a different label is still collecting it, and this check\n * has no way to tell a renamed field from a missing one without guessing.\n */\nexport async function aiCopiedFormReview(\n firestore: FirebaseFirestore.Firestore,\n input: { hostId: string; formId: string; name: string; plan: AiJobPlan | null },\n): Promise<AiJobReview | null> {\n const promised = (aiPlanCreation(input.plan, 'form')?.fields ?? [])\n .map((field) => field.split(':')[0]?.trim().toLowerCase())\n .filter((field): field is string => Boolean(field))\n if (!promised.length) return null\n const snapshot = await firestore\n .collection('hosts')\n .doc(input.hostId)\n .collection('forms')\n .doc(input.formId)\n .get()\n if (!snapshot.exists) {\n return {\n reason: 'doctrine',\n message: `\"${input.name}\" was copied from the form the plan names, and this job could not read the copy back to check it collects what the plan gives it. Open the form and check it before you put it on a page.`,\n findings: [],\n }\n }\n const fields = (snapshot.get('fields') ?? []) as unknown[]\n const collected = new Set(\n fields\n .map((field) =>\n field && typeof field === 'object'\n ? String((field as Record<string, unknown>)['fieldName'] ?? (field as Record<string, unknown>)['name'] ?? '')\n : '',\n )\n .filter(Boolean)\n .map((name) => name.toLowerCase()),\n )\n const missing = promised.filter((name) => !collected.has(name))\n if (!missing.length) return null\n const one = missing.length === 1\n return aiDoctrineReview({\n message: `\"${input.name}\" is a copy of the form the plan names, and a copy is all it is: the plan gives it ${\n one ? 'a field' : 'fields'\n } the copy does not collect.`,\n violations: [\n {\n rule: null,\n code: 'plan-fields-missing',\n message: `The confirmed plan says this form collects ${missing.join(', ')}, and the copy collects ${\n collected.size ? [...collected].join(', ') : 'nothing'\n }. Add ${one ? 'it' : 'each of them'}, or the copy is the form it was copied from.`,\n },\n ],\n })\n}\n\n/**\n * What the form a short copy would have started from collects, as the build\n * that replaces the copy is told it (AGL-3143 §14): every field it asks for,\n * so the build keeps them beside what the plan adds. Empty when the form\n * cannot be read.\n */\nexport async function aiFormSourceLines(\n firestore: FirebaseFirestore.Firestore,\n input: { hostId: string; id: string; name: string },\n): Promise<string[]> {\n const snapshot = await firestore.collection('hosts').doc(input.hostId).collection('forms').doc(input.id).get()\n const fields = snapshot.exists ? ((snapshot.get('fields') ?? []) as unknown[]) : []\n const asked = fields.flatMap((field) => {\n if (!field || typeof field !== 'object') return []\n const row = field as Record<string, unknown>\n const name = String(row['fieldName'] ?? row['name'] ?? '').trim()\n if (!name) return []\n const fieldType = row['fieldType'] ?? row['type']\n const type = typeof fieldType === 'string' ? ` (${fieldType}${row['required'] ? ', required' : ''})` : ''\n return [`${name}${type}`]\n })\n if (!asked.length) return []\n return [\n `The plan starts from a copy of the form \"${input.name}\", which lacks part of what the plan gives it. Build from it: it collects ${asked.join(', ')}. Keep each of those, and add what the plan adds.`,\n ]\n}\n\nfunction listOf(items: readonly string[]): string {\n return items.length < 2\n ? items.join('')\n : `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`\n}\n\n/**\n * What the person decides next, in words the step writes itself: a lead\n * routing to keep or switch off, the list a proposal could not store, and what\n * the brief asked for that a form cannot collect. `null` when there is none.\n */\nexport function aiFormOutputNote(answer: AiFormAnswer): string | null {\n const sentences: string[] = []\n if (answer.routing.kind === 'lead') {\n sentences.push(\n 'Each submission with an email address also files a lead in CRM → Leads; you can switch that off on the form’s page.',\n )\n }\n if (answer.routing.kind === 'list') {\n const list = answer.routing.list ? `your \"${answer.routing.list}\" list` : 'an email list'\n sentences.push(\n `Submissions arrive in the Inbox. To add the people who tick \"${MARKETING_CONSENT_FORM_FIELD.options}\" to ${list}, add an action on form submissions in Automation that enrolls them.`,\n )\n }\n if (answer.cannotCollect.length) {\n sentences.push(\n `Forms cannot collect ${listOf(answer.cannotCollect)} yet, so this form leaves ${\n answer.cannotCollect.length === 1 ? 'it' : 'them'\n } out.`,\n )\n }\n return sentences.length ? sentences.join(' ') : null\n}\n\n/**\n * The form job as the generation's user turn: the name, who fills the form\n * in, the brief, and the confirmed plan.\n *\n * Who the form is for (AGL-2918) is the answer a contact form's FIELDS turn\n * on — a trades business asks where the work is, a practice asks what the\n * appointment is about — and it is not something a brief about a whole site\n * says in a place the form can find. It rides here, in the turn, because it\n * is one site's own words.\n *\n * Where submissions go rides here too, and it is NOT a hint: the step binds\n * the routing to it whatever the model answers. It is stated so the model\n * does not spend its answer proposing something that will be replaced, and\n * so a form told its submissions are leads asks for the address that makes\n * one.\n */\nexport function aiJobFormPrompt(\n job: Pick<AiJob, 'brief'>,\n plan: AiJobPlan | null,\n name: string,\n context: { audience?: string; submissions?: AiSiteSubmissions | null } = {},\n): string {\n const audience = (context.audience ?? '').trim()\n return [\n `Form name: ${name}`,\n audience ? `The people who fill it in: ${audience}` : '',\n context.submissions ? `Where its submissions go: ${SUBMISSION_WORDS[context.submissions]}` : '',\n aiJobBriefLine(job),\n ...aiPlanReferenceLines(plan),\n ]\n .filter(Boolean)\n .join('\\n')\n}\n\n/** What each decided routing is, said to the model the way the tool says it. */\nconst SUBMISSION_WORDS: Record<AiSiteSubmissions, string> = {\n inbox: 'the Inbox, to be read — routing.kind is inbox',\n lead: 'the Inbox, and each one with an email address is a sales lead — routing.kind is lead',\n}\n\n/**\n * A form job is admitted for a site of the job's own org whose plan has\n * forms, with a form to spare, and confirmed only for a plan that creates\n * nothing but the form: a form places nothing another job builds\n * (AGL-3143 §15).\n */\nexport const aiFormJobAdmission: AiJobAdmission = (context) =>\n aiDraftAdmissionRefusal(context.firestore, {\n orgId: context.orgId,\n hostId: context.hostId,\n kind: 'form',\n org: context.org,\n ownCheck: (hostId) => aiJobPlanCreationsRefusal('form', context, hostId),\n })\n\n/**\n * What a form step says when the site's last form was taken after its plan\n * was confirmed (AGL-3765): by another build running beside it, or by a\n * member. The failure is ours, so what the job spent is given back.\n */\nexport const AI_FORM_BAND_TAKEN_COPY =\n 'Another build on this site used the last form your plan includes while this one was running, so this one stopped. Describe it again to build it with the form the site has now.'\n\nexport interface AiJobFormStepDeps {\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 /** The data plugin's writer lookup the form's dataset is read through (AGL-3616); specs hand in a fake. */\n datasetWriterFor?: AiFormDatasetReadDeps['writerFor']\n /** The form another build just made that a refused unit places (AGL-3765); specs hand in a fake. */\n siblingForm?: typeof aiSiblingJobForm\n}\n\nexport function createAiJobFormStep(deps: AiJobFormStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const duplicate = deps.duplicate ?? duplicateResource\n const siblingForm = deps.siblingForm ?? aiSiblingJobForm\n return async ({ job, now, signal, firestore, modelFor }) => {\n const hostId = job.hostId\n if (!hostId) throw new Error('a form job names no site, and its admission refuses one')\n const output = (\n draft: AiDraftRecord,\n extra: { load?: AiLoadEstimate | null; note?: string | null } = {},\n ): AiJobOutput => ({\n resource: 'form',\n id: draft.id,\n versionId: draft.versionId,\n hostId,\n hostSubdomain: draft.hostSubdomain,\n label: draft.name,\n ...(extra.load ? { load: extra.load } : {}),\n ...(extra.note ? { note: extra.note } : {}),\n })\n // The switch's answer for this job, else the routing table's (AGL-2942).\n const model = modelFor?.('job.form') ?? aiModelForStep('job.form')\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, 'form')\n const written = await readAiDraft(firestore, { kind: 'form', hostId, id: draftId })\n if (written) return aiUnspentOutcome(model, { outputs: [output(written)] })\n\n const [inventory, orgSnapshot] = await Promise.all([\n readInventory(job.orgId, hostId, { firestore }),\n firestore.collection('orgs').doc(job.orgId).get(),\n ])\n const org = (orgSnapshot.data() ?? null) as Partial<AglynOrgBilling> | null\n const plan = aiConfirmedPlan(job)\n const creation = aiPlanCreation(plan, 'form')\n const name = creation?.name || AI_JOB_FORM_DEFAULT_NAME\n // The site holds every form its plan includes (AGL-3765). A unit places a\n // form another build on this site just made, as its page would place any\n // form the site has. Otherwise a site that had room when the plan was\n // confirmed and was filled since stopped this job on our side, given\n // back; one that was already full is the workspace's limit to change. A\n // lookup that fails leaves the refusal as it was.\n const refused = async (\n refusal: string,\n spent: Pick<AiJobStepOutcome, 'outputs' | 'usage' | 'estCostUsd' | 'model' | 'stopReason'>,\n ): Promise<AiJobStepOutcome> => {\n const lookup = async <T>(read: () => Promise<T>, fallback: T): Promise<T> => {\n try {\n return await read()\n } catch (error) {\n console.error('ai form step: band refusal lookup failed', { jobId: job.$id, hostId, error })\n return fallback\n }\n }\n const reused = await lookup(() => siblingForm(firestore, { job, now }), null)\n if (reused) return { ...spent, outputs: [output(reused, { note: AI_FORM_REUSED_NOTE })] }\n const taken = await lookup(\n () => readAiDraftBandTakenSince(firestore, { kind: 'form', hostId, org, since: plan?.confirmedAt }),\n false,\n )\n if (taken) return { ...spent, failure: AI_FORM_BAND_TAKEN_COPY }\n return { ...spent, review: aiLimitReview(refusal) }\n }\n\n // The plan starts from a copy of a form the site has (rule 15): the copy\n // is the draft, and nothing is generated. A source gone since the plan\n // was made is built from the brief instead, and one that does not collect\n // a field the plan gives the form is built from the plan, told what the\n // source collects (AGL-3143 §14): copying it could only end in the review\n // below. A source this step cannot read still copies.\n const source = creation?.duplicateOf\n ? inventory.forms.find((form) => form.id === creation.duplicateOf)\n : undefined\n const sourceReview = source\n ? await aiCopiedFormReview(firestore, { hostId, formId: source.id, name: source.name, plan })\n : null\n const sourceShort = Boolean(sourceReview?.findings.length)\n const sourceLines =\n source && sourceShort ? await aiFormSourceLines(firestore, { hostId, id: source.id, name: source.name }) : []\n if (creation?.duplicateOf && source && !sourceShort) {\n const copy = await duplicate('form', {\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 // The copy is the whole output, so the contract is asked of it here\n // or nowhere: a copy still bound to its source is not a form this\n // job may report as built (AGL-3024).\n const unbound = await aiFormCopyUnboundFailure(firestore, { hostId, formId: copy.id })\n if (unbound) return { ...aiUnspentOutcome(model), failure: unbound }\n const hostSubdomain = await aiSiteSubdomain(firestore, hostId)\n // And the one duplication hides: what the plan promised of the copy,\n // read back (AGL-3024). This branch generates nothing, so nothing\n // else can answer for it.\n const review = await aiCopiedFormReview(firestore, {\n hostId,\n formId: copy.id,\n name: copy.name,\n plan,\n })\n if (review) return aiUnspentOutcome(model, { review })\n return aiUnspentOutcome(model, {\n outputs: [output({ id: copy.id, versionId: copy.versionId, name: copy.name, hostSubdomain })],\n })\n }\n if (copy.ok === false && copy.status === 403) {\n return refused(copy.error, aiUnspentOutcome(model))\n }\n }\n\n const allowance = await aiDraftAllowanceRefusal(firestore, { kind: 'form', hostId, org })\n if (allowance) return refused(allowance, aiUnspentOutcome(model))\n\n // What the person answered about this form, where they were asked\n // (AGL-2918): a scaffold's form unit carries the guided start's inputs.\n const decisions: AiFormDecisions = { submissions: aiSiteSubmissions(job.inputs) }\n const { audience } = aiSiteWords(job.inputs)\n // The dataset the plan says the form writes to (AGL-3616), where this\n // workspace may bind one; otherwise the form is the form it always was.\n const dataset = await aiReadFormDataset(\n {\n hostId,\n id: creation?.writesTo,\n org,\n inventory,\n madeId: job.inputs?.[AI_FORM_DATASET_MADE_INPUT],\n },\n deps.datasetWriterFor ? { writerFor: deps.datasetWriterFor } : {},\n )\n const check = aiFormDraftCheck({ formId: draftId, name, decisions, dataset })\n const result = await runValidatedGeneration('form', {\n step: 'job.form',\n model,\n instructions: AI_JOB_FORM_INSTRUCTIONS,\n inventory,\n messages: [\n {\n role: 'user',\n content: [\n aiJobFormPrompt(job, plan, name, {\n audience,\n submissions: decisions.submissions,\n }),\n ...sourceLines,\n ...(dataset ? [aiFormDatasetPromptLine(dataset)] : []),\n ].join('\\n'),\n },\n ],\n tool: AI_JOB_FORM_TOOL,\n maxTokens: AI_JOB_FORM_STEP_BUDGET.maxTokens(model),\n thinking: 'off',\n extend: check.extend,\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 = check.draftFor(result.value)\n if (!draft) throw new Error('a form the doctrine admitted has no draft from its check')\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const write = await writeAiDraft(firestore, {\n kind: 'form',\n hostId,\n id: draftId,\n uid: job.createdBy,\n org,\n name,\n nodes: draft.nodes,\n form: {\n rootId: draft.rootId,\n formNodeId: draft.formNodeId,\n fields: draft.fields,\n consentFieldName: draft.consentFieldName,\n routing: draft.routing,\n },\n now,\n })\n if (write.ok === false) {\n if (write.status === 404) throw new Error(`site ${hostId} vanished while its form was generated`)\n return refused(write.error, spent)\n }\n // What the person decides next, then the facts the brief did not give (AGL-3056).\n const note = [\n aiFormOutputNote(draft.answer),\n draft.dataset ? aiFormDatasetNote(draft.dataset.dataset, draft.dataset.binding) : null,\n aiBracketedFactsNote({\n tree: { rootId: result.value.rootId, nodes: result.value.nodes as unknown as AiDoctrineTree['nodes'] },\n inventory,\n }),\n ]\n .filter(Boolean)\n .join(' ')\n return {\n ...spent,\n outputs: [output(write, { load: result.value.load, note })],\n }\n }\n}\n\nexport const runAiJobFormStep = createAiJobFormStep()\n\n/** Registers the form step and the check a form job passes before it is created or resumed. */\nexport function registerAiFormJob(): void {\n registerAiJobStep('form', runAiJobFormStep, { minimumMs: AI_JOB_FORM_STEP_MINIMUM_MS })\n registerAiJobAdmission('form', aiFormJobAdmission)\n}\n"],"names":["throwIfAiJobCanceled","checkFormContract","formFieldsCanYieldAnEmail","collectFormFieldNodeIds","FORM_COMPONENT_ID","FORM_ID_PROP","FORM_INPUT_ELEMENT_IDS","formFieldDeclsFromNodes","formInputName","formNodeIdIn","isMarketingConsentFieldName","MARKETING_CONSENT_FORM_FIELD","decodeStoredNodes","CANVAS_ROOT_ELEMENT_ID","NodeType","duplicateResource","aiSiteSubmissions","aiSiteWords","AI_STEP_TIERS","AI_ROUTING_TABLE","aiModelForStep","aiDoctrineTreeTool","runValidatedGeneration","AI_PALETTE","readSiteInventory","registerAiJobAdmission","AI_FORM_DATASET_MADE_INPUT","aiBindFormToDataset","aiFormDatasetNote","aiFormDatasetPromptLine","aiReadFormDataset","aiJobPlanCreationsRefusal","aiJobDraftId","aiDraftAdmissionRefusal","aiDraftAllowanceRefusal","aiSiteSubdomain","readAiDraft","readAiDraftBandTakenSince","writeAiDraft","AI_FORM_REUSED_NOTE","aiSiblingJobForm","aiBracketedFactsNote","aiConfirmedPlan","aiDoctrineReview","aiGenerationSpent","aiJobBriefLine","aiLimitReview","aiModelNodeIds","aiPlanCreation","aiPlanReferenceLines","aiUnspentOutcome","aiJobStepBudget","registerAiJobStep","AI_JOB_FORM_MAX_TOKENS","maxTokens","AI_JOB_FORM_STEP_BUDGET","tier","AI_JOB_FORM_STEP_MINIMUM_MS","minimumMs","AI_JOB_FORM_DEFAULT_NAME","AI_FORM_ROUTING_KINDS","AI_FORM_CANNOT_COLLECT_MAX","CANNOT_COLLECT_MAX_CHARS","LIST_NAME_MAX_CHARS","AI_FORM_CONSENT_NODE_ID","AI_FORM_CONSENT_CHECKBOX_NODE_ID","AI_FORM_CONSENT_FIELD_NAME","fieldName","AI_FORM_CONSENT_VALUE","aiFormConsentNodes","formNodeId","choiceLabel","checkbox","$id","type","NODE","componentId","pluginId","parentId","nodes","props","label","options","name","value","consentWrapperId","inputId","framing","Set","formControl","outer","String","parent","has","answers","every","id","removeSubtree","Array","isArray","filter","child","stack","length","next","pop","node","push","AI_JOB_FORM_INSTRUCTIONS","text","join","TREE_TOOL","AI_JOB_FORM_TOOL","description","strict","inputSchema","additionalProperties","required","properties","tree","routing","kind","enum","list","anyOf","cannotCollect","items","isRecord","oneLine","max","replace","trim","slice","parseAiFormAnswer","answer","decisions","submissions","proposed","includes","seen","entry","toLowerCase","add","aiFormDraft","identity","parsed","rootId","Object","entries","form","consentFieldName","formId","dataset","binding","undefined","fields","lead","aiFormDraftViolations","draft","sourceIds","violations","map","violation","rule","code","message","nodeId","nodeIds","paths","aiFormDraftCheck","drafts","WeakMap","extend","set","draftFor","get","AI_FORM_COPY_UNBOUND_FAILURE","aiFormCopyUnboundFailure","firestore","copy","snapshot","collection","doc","hostId","data","unbound","find","aiCopiedFormReview","input","promised","plan","field","split","Boolean","exists","reason","findings","collected","missing","one","size","aiFormSourceLines","asked","flatMap","row","fieldType","listOf","aiFormOutputNote","sentences","aiJobFormPrompt","job","context","audience","SUBMISSION_WORDS","inbox","aiFormJobAdmission","orgId","org","ownCheck","AI_FORM_BAND_TAKEN_COPY","createAiJobFormStep","deps","readInventory","duplicate","siblingForm","now","signal","modelFor","orgSnapshot","Error","output","extra","resource","versionId","hostSubdomain","load","note","model","draftId","written","outputs","inventory","Promise","all","creation","refused","refusal","spent","lookup","read","fallback","error","console","jobId","reused","taken","since","confirmedAt","failure","review","source","duplicateOf","forms","sourceReview","sourceShort","sourceLines","sourceId","uid","createdBy","attemptKey","ok","status","allowance","inputs","writesTo","madeId","datasetWriterFor","writerFor","check","result","step","instructions","messages","role","content","tool","thinking","write","runAiJobFormStep","registerAiFormJob"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,qBAAiB;AACtD,SACEC,iBAAiB,EACjBC,yBAAyB,QACpB,uCAAsC;AAC7C,SACEC,uBAAuB,EACvBC,iBAAiB,EACjBC,YAAY,EACZC,sBAAsB,EACtBC,uBAAuB,EACvBC,aAAa,EACbC,YAAY,EACZC,2BAA2B,EAC3BC,4BAA4B,QAIvB,+BAA8B;AACrC,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SAASC,sBAAsB,QAAQ,2CAA0C;AAEjF,SAASC,QAAQ,QAAuB,2BAA0B;AAClE,SAASC,iBAAiB,QAAQ,qDAAoD;AAEtF,SAASC,iBAAiB,EAAEC,WAAW,QAAgC,0BAAsB;AAC7F,SAASC,aAAa,QAAQ,0BAAsB;AACpD,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,0BAAsB;AACvE,SACEC,kBAAkB,EAClBC,sBAAsB,QAEjB,4BAAwB;AAG/B,SAASC,UAAU,QAAQ,qCAAiC;AAE5D,SAASC,iBAAiB,QAAQ,+BAA2B;AAC7D,SAASC,sBAAsB,QAA6B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