@aglyn/plugins-ai 1.32.0 → 1.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/package.json +17 -17
  2. package/src/lib/jobs/ai-job-campaign-step.js +1 -0
  3. package/src/lib/jobs/ai-job-campaign-step.js.map +1 -1
  4. package/src/lib/jobs/ai-job-component-step.js +2 -1
  5. package/src/lib/jobs/ai-job-component-step.js.map +1 -1
  6. package/src/lib/jobs/ai-job-drafts.d.ts +8 -0
  7. package/src/lib/jobs/ai-job-drafts.js +18 -12
  8. package/src/lib/jobs/ai-job-drafts.js.map +1 -1
  9. package/src/lib/jobs/ai-job-edit-step.d.ts +5 -0
  10. package/src/lib/jobs/ai-job-edit-step.js +16 -9
  11. package/src/lib/jobs/ai-job-edit-step.js.map +1 -1
  12. package/src/lib/jobs/ai-job-email-step.js +1 -0
  13. package/src/lib/jobs/ai-job-email-step.js.map +1 -1
  14. package/src/lib/jobs/ai-job-form-step.js +2 -1
  15. package/src/lib/jobs/ai-job-form-step.js.map +1 -1
  16. package/src/lib/jobs/ai-job-layout-step.js +4 -1
  17. package/src/lib/jobs/ai-job-layout-step.js.map +1 -1
  18. package/src/lib/jobs/ai-job-navigation-step.js +7 -3
  19. package/src/lib/jobs/ai-job-navigation-step.js.map +1 -1
  20. package/src/lib/jobs/ai-job-page-step.js +7 -1
  21. package/src/lib/jobs/ai-job-page-step.js.map +1 -1
  22. package/src/lib/jobs/ai-job-privacy-step.d.ts +2 -0
  23. package/src/lib/jobs/ai-job-privacy-step.js +7 -4
  24. package/src/lib/jobs/ai-job-privacy-step.js.map +1 -1
  25. package/src/lib/jobs/ai-job-site-store-pages.js +3 -1
  26. package/src/lib/jobs/ai-job-site-store-pages.js.map +1 -1
  27. package/src/lib/jobs/ai-job-store-links-layout.js +8 -4
  28. package/src/lib/jobs/ai-job-store-links-layout.js.map +1 -1
  29. package/src/lib/jobs/ai-job-template-step.js +2 -1
  30. package/src/lib/jobs/ai-job-template-step.js.map +1 -1
  31. package/src/lib/jobs/ai-site-import-forms.js +2 -1
  32. package/src/lib/jobs/ai-site-import-forms.js.map +1 -1
  33. package/src/lib/jobs/ai-site-import-publish.d.ts +1 -1
  34. package/src/lib/jobs/ai-site-import-publish.js.map +1 -1
  35. package/src/lib/jobs/ai-site-late-photos.js +2 -1
  36. package/src/lib/jobs/ai-site-late-photos.js.map +1 -1
  37. package/src/lib/jobs/ai-site-publish.d.ts +2 -2
  38. package/src/lib/jobs/ai-site-publish.js +23 -15
  39. package/src/lib/jobs/ai-site-publish.js.map +1 -1
  40. package/src/lib/layout-language/ai-layout-frame-source.js +1 -0
  41. package/src/lib/layout-language/ai-layout-frame-source.js.map +1 -1
  42. package/src/lib/runtime/ai-palette.generated.js +7 -0
  43. package/src/lib/runtime/ai-palette.generated.js.map +1 -1
  44. package/src/lib/server/ai-experiment-versions.js +6 -3
  45. package/src/lib/server/ai-experiment-versions.js.map +1 -1
  46. package/src/lib/server/ai-page-content.js +2 -1
  47. package/src/lib/server/ai-page-content.js.map +1 -1
  48. package/src/lib/server/ai-seo-apply.js +6 -3
  49. package/src/lib/server/ai-seo-apply.js.map +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-ai",
3
- "version": "1.32.0",
3
+ "version": "1.33.0",
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.32.0",
29
- "@aglyn/shared-data-enums": "1.32.0",
30
- "@aglyn/shared-data-mdi": "1.32.0",
31
- "@aglyn/shared-data-types": "1.32.0",
32
- "@aglyn/shared-ui-email-campaigns": "1.32.0",
33
- "@aglyn/shared-ui-jsx": "1.32.0",
34
- "@aglyn/shared-ui-snackstack": "1.32.0",
35
- "@aglyn/shared-ui-theme": "1.32.0",
36
- "@aglyn/shared-util-email": "1.32.0",
37
- "@aglyn/shared-util-errors": "1.32.0",
38
- "@aglyn/shared-util-http": "1.32.0",
39
- "@aglyn/shared-util-timestamp": "1.32.0",
40
- "@aglyn/shared-util-tools": "1.32.0",
41
- "@aglyn/tenant-data-admin": "1.32.0",
42
- "@aglyn/tenant-feature-instance": "1.32.0",
43
- "@aglyn/tenant-runtime": "1.32.0",
28
+ "@aglyn/aglyn": "1.33.0",
29
+ "@aglyn/shared-data-enums": "1.33.0",
30
+ "@aglyn/shared-data-mdi": "1.33.0",
31
+ "@aglyn/shared-data-types": "1.33.0",
32
+ "@aglyn/shared-ui-email-campaigns": "1.33.0",
33
+ "@aglyn/shared-ui-jsx": "1.33.0",
34
+ "@aglyn/shared-ui-snackstack": "1.33.0",
35
+ "@aglyn/shared-ui-theme": "1.33.0",
36
+ "@aglyn/shared-util-email": "1.33.0",
37
+ "@aglyn/shared-util-errors": "1.33.0",
38
+ "@aglyn/shared-util-http": "1.33.0",
39
+ "@aglyn/shared-util-timestamp": "1.33.0",
40
+ "@aglyn/shared-util-tools": "1.33.0",
41
+ "@aglyn/tenant-data-admin": "1.33.0",
42
+ "@aglyn/tenant-feature-instance": "1.33.0",
43
+ "@aglyn/tenant-runtime": "1.33.0",
44
44
  "@swc/helpers": "0.5.24"
45
45
  },
46
46
  "peerDependencies": {
@@ -195,6 +195,7 @@ export function createAiJobCampaignStep(deps = {}) {
195
195
  orgId: job.orgId,
196
196
  hostId,
197
197
  uid: job.createdBy,
198
+ via: `ai-job:${job.$id}`,
198
199
  org,
199
200
  now
200
201
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-campaign-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 { checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport type {\n PluginDraftRecord,\n PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport type { AiJob, AiJobOutput } from '../model/ai-jobs.types'\nimport { aiModelForStep } from '../providers/routing'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport {\n aiCampaignAudienceNote,\n readAiListSendTime,\n resolveAiEmailProducts,\n suggestAiCampaignList,\n} from './ai-email-bindings'\nimport { registerAiJobAdmission, type AiJobAdmission } from './ai-job-admission'\nimport { aiJobDraftId } from './ai-job-draft-ids'\nimport { aiSiteSubdomain } from './ai-job-drafts'\nimport {\n aiConfirmedPlan,\n aiDoctrineReview,\n aiGenerationSpent,\n aiLimitReview,\n aiUnspentOutcome,\n} from './ai-job-generation'\nimport {\n AI_EMAIL_DESIGN_RESOURCE,\n AI_EMAIL_SAVE_FAILURE_COPY,\n AI_JOB_EMAIL_STEP_BUDGETS,\n aiEmailDesignContent,\n aiEmailDesignOutput,\n aiJobInputName,\n generateAiEmail,\n type AiEmailCopy,\n} from './ai-job-email-step'\nimport {\n aiPluginDraftAdmissionRefusal,\n aiPluginDraftWriter,\n type AiPluginDraftWriterLookup,\n} from './ai-job-plugin-drafts'\nimport type { AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The campaign step (AGL-2912): one brief becomes an email design AND the\n * draft campaign that would send it.\n *\n * A campaign is an unplanned kind — there is one thing to build and a plan\n * over it would be a plan of one — so the job runs this step alone, and the\n * design it writes is the email step's, generated through `generateAiEmail`\n * so both kinds obey the same doctrine and the same email rules.\n *\n * ## Nothing is sent, and nothing is aimed\n *\n * The campaign is written `draft`, with no audience, no schedule and no\n * sender: a draft campaign is not a queued one, the scheduled processor\n * queries `status == 'scheduled'`, and the send route is the only thing that\n * mails a campaign. Choosing WHO receives it stays a person's decision, so\n * the model is never shown the org's lists, its contacts or what past sends\n * did. Code reads the list the brief names and the send time that list's own\n * history suggests, AFTER the answer, and both reach the person as the\n * output's `note` — never the prompt.\n *\n * ## Where campaign email begins\n *\n * A site whose plan sends no campaign email can still generate email designs;\n * the campaign is the part that needs somewhere to send. So the step gates on\n * the same entitlement the composer and the send route read, and stops the\n * job for a person rather than failing it. The refusal names no plan, because\n * the billing page is the one place that does.\n *\n * ## Run again and it finds its drafts\n *\n * Each write is keyed by the id the job recorded for its draft when it was\n * created, so a run cut off between them finds what it wrote: two drafts are\n * reported, a design alone is drafted into a campaign from the copy the\n * design already stores, and neither spends.\n */\n\n/** The resource the marketing plugin writes a draft campaign under. */\nexport const AI_CAMPAIGN_RESOURCE = 'campaign'\n\n/** A campaign's name when neither the job nor its subject lines give one. */\nexport const AI_JOB_CAMPAIGN_DEFAULT_NAME = 'New campaign'\n\n/** A job's failure when the site has no campaign writer. */\nexport const AI_CAMPAIGN_UNAVAILABLE_COPY = 'Campaigns are not available on this site.'\n\n/** A job's failure when a campaign whose email was written could not be drafted. */\nexport const AI_CAMPAIGN_SAVE_FAILURE_COPY =\n 'The email was written but the campaign could not be drafted. Try the job again.'\n\n/**\n * What a person is told when their plan sends no campaign email. It names the\n * page that sells the answer rather than a plan, so the one place plan names\n * are written stays the one place they are read.\n */\nexport const AI_CAMPAIGN_PLAN_REFUSAL =\n 'Campaign email is not included on this workspace’s plan. ' +\n 'Upgrade in Billing to send campaigns, or generate an email design on its own.'\n\n/** Whether this workspace may send campaign email at all: the composer's and the send route's check. */\nexport function aiCampaignPlanAllows(org: object | null): boolean {\n return checkQuota(org as Partial<AglynOrgBilling> | null, 'emailSendsPerMonth', 0).allowed\n}\n\n/** The campaign as the job's output, carrying what the person still decides. */\nexport function aiCampaignOutput(\n record: PluginDraftRecord,\n place: { hostId: string; hostSubdomain: string | null },\n note: string | null,\n): AiJobOutput {\n return {\n resource: 'campaign',\n id: record.id,\n versionId: null,\n hostId: place.hostId,\n hostSubdomain: place.hostSubdomain,\n label: record.name,\n ...(note ? { note } : {}),\n }\n}\n\n/** The subject lines and preheaders a written design already stores. */\nexport function aiCampaignCopyFromDesign(record: PluginDraftRecord): AiEmailCopy {\n const lines = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : []\n const subject = String(record.facts?.['subject'] ?? '')\n const preheader = String(record.facts?.['preheader'] ?? '')\n const subjects = lines(record.facts?.['subjectVariants'])\n const preheaders = lines(record.facts?.['preheaderVariants'])\n return {\n subjects: subjects.length ? subjects : subject ? [subject] : [],\n preheaders: preheaders.length ? preheaders : preheader ? [preheader] : [],\n }\n}\n\n/** The campaign's content: the design it sends, and the copy the send fills its headers from. */\nexport function aiCampaignDraftContent(\n designId: string,\n copy: AiEmailCopy,\n): Record<string, unknown> {\n return {\n templateScreenId: designId,\n subject: copy.subjects[0] ?? '',\n preheader: copy.preheaders[0] ?? '',\n subjectVariants: copy.subjects,\n preheaderVariants: copy.preheaders,\n }\n}\n\n/** A campaign job's name: what the member asked for, else its strongest subject line. */\nexport function aiCampaignName(job: Pick<AiJob, 'inputs'>, copy: AiEmailCopy): string {\n return aiJobInputName(job) || copy.subjects[0] || AI_JOB_CAMPAIGN_DEFAULT_NAME\n}\n\n/**\n * A campaign job is admitted for a site of its org with email and marketing\n * on, room for a design and a campaign, and a plan that sends campaign email.\n */\nexport const aiCampaignJobAdmission: AiJobAdmission = (context) =>\n aiPluginDraftAdmissionRefusal(context, {\n kind: 'campaign',\n drafts: [\n { resource: AI_EMAIL_DESIGN_RESOURCE, label: 'Email' },\n { resource: AI_CAMPAIGN_RESOURCE, label: 'Marketing' },\n ],\n ownCheck: async () =>\n aiCampaignPlanAllows(context.org)\n ? null\n : { status: 403, error: AI_CAMPAIGN_PLAN_REFUSAL },\n })\n\nexport interface AiJobCampaignStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** How a resource's draft writer is found; the core's registry otherwise. */\n writerFor?: AiPluginDraftWriterLookup\n}\n\n/** Both drafts, or the refusal that stands in for a writer the site has not got. */\nfunction writers(\n writerFor: AiPluginDraftWriterLookup,\n): { design: PluginResourceDraftWriter; campaign: PluginResourceDraftWriter } | string {\n const design = writerFor(AI_EMAIL_DESIGN_RESOURCE)\n const campaign = writerFor(AI_CAMPAIGN_RESOURCE)\n if (!design) return AI_CAMPAIGN_UNAVAILABLE_COPY\n if (!campaign) return AI_CAMPAIGN_UNAVAILABLE_COPY\n return { design, campaign }\n}\n\nexport function createAiJobCampaignStep(deps: AiJobCampaignStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const writerFor = deps.writerFor ?? aiPluginDraftWriter\n return async ({ job, now, signal, firestore, modelFor }): Promise<AiJobStepOutcome> => {\n const hostId = job.hostId\n if (!hostId) throw new Error('a campaign job names no site, and its admission refuses one')\n // The switch's answer for this job, else the routing table's (AGL-2942).\n const model = modelFor?.('job.campaign') ?? aiModelForStep('job.campaign')\n const found = writers(writerFor)\n if (typeof found === 'string') return { ...aiUnspentOutcome(model), failure: found }\n const { design, campaign } = found\n\n // What an earlier run of this same job already wrote, under the ids the job recorded.\n const designId = aiJobDraftId(job, 'email')\n const [writtenDesign, writtenCampaign, hostSubdomain] = await Promise.all([\n design.read({ hostId, id: designId }),\n campaign.read({ hostId, id: aiJobDraftId(job, 'campaign') }),\n aiSiteSubdomain(firestore, hostId),\n ])\n const place = { hostId, hostSubdomain }\n if (writtenDesign && writtenCampaign) {\n return aiUnspentOutcome(model, {\n outputs: [\n aiEmailDesignOutput(writtenDesign, place, null),\n aiCampaignOutput(writtenCampaign, place, null),\n ],\n })\n }\n\n const orgSnapshot = await firestore.collection('orgs').doc(job.orgId).get()\n const org = (orgSnapshot.data() ?? null) as Record<string, unknown> | null\n // Asked again here because a plan can change between admission and the run.\n if (!aiCampaignPlanAllows(org)) {\n return aiUnspentOutcome(model, { review: aiLimitReview(AI_CAMPAIGN_PLAN_REFUSAL) })\n }\n const context = { orgId: job.orgId, hostId, uid: job.createdBy, org, now }\n\n // Who it is for and when to send it: read from the site, told to the\n // person, and never sent to the model.\n const list = await suggestAiCampaignList({ hostId, brief: job.brief })\n const sendTime = list ? await readAiListSendTime({ ...context, listId: list.id }) : null\n const note = aiCampaignAudienceNote(list, sendTime)\n\n // A design an earlier run wrote is drafted into its campaign, unspent.\n if (writtenDesign) {\n return draftCampaign({\n campaign,\n context,\n job,\n copy: aiCampaignCopyFromDesign(writtenDesign),\n designId: writtenDesign.id,\n spent: aiUnspentOutcome(model),\n outputs: [aiEmailDesignOutput(writtenDesign, place, null)],\n place,\n note,\n })\n }\n\n const [inventory, products] = await Promise.all([\n readInventory(job.orgId, hostId, { firestore }),\n resolveAiEmailProducts({ hostId, brief: job.brief, inputs: job.inputs }),\n ])\n const refusal = await design.refusal(context)\n if (refusal) {\n return refusal.status === 403\n ? aiUnspentOutcome(model, { review: aiLimitReview(refusal.error) })\n : { ...aiUnspentOutcome(model), failure: refusal.error }\n }\n\n const asked = aiJobInputName(job)\n const generated = await generateAiEmail({\n job,\n step: 'job.campaign',\n model,\n heading: asked ? `Campaign name: ${asked}` : null,\n plan: aiConfirmedPlan(job),\n inventory,\n hostId,\n products,\n design,\n ...(signal ? { signal } : {}),\n })\n const { result } = generated\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 if (!generated.copy || !generated.nodes) return { ...spent, failure: AI_EMAIL_SAVE_FAILURE_COPY }\n\n const { copy } = generated\n const name = aiCampaignName(job, copy)\n const write = await design.write({\n ...context,\n id: designId,\n name,\n content: aiEmailDesignContent(generated.nodes, copy),\n })\n if (write.ok === false) {\n return write.status === 403\n ? { ...spent, review: aiLimitReview(write.error) }\n : { ...spent, failure: AI_EMAIL_SAVE_FAILURE_COPY }\n }\n return draftCampaign({\n campaign,\n context,\n job,\n copy,\n designId: write.id,\n spent,\n outputs: [aiEmailDesignOutput(write, place, null)],\n place,\n note,\n })\n }\n}\n\ninterface AiCampaignDraftInput {\n campaign: PluginResourceDraftWriter\n context: { orgId: string; hostId: string; uid: string; org: Record<string, unknown> | null; now: Date }\n job: AiJob\n copy: AiEmailCopy\n designId: string\n /** What the generation cost, or an unspent outcome for a run that reached no model. */\n spent: Pick<AiJobStepOutcome, 'outputs' | 'usage' | 'estCostUsd' | 'model' | 'stopReason'>\n /** The design's output, reported beside the campaign once it is drafted. */\n outputs: AiJobOutput[]\n place: { hostId: string; hostSubdomain: string | null }\n note: string\n}\n\n/**\n * Drafts the campaign around a design that exists. A campaign that cannot be\n * drafted reports NO outputs: the design on its own is not what the job was\n * asked for, and a run that names it would read as finished.\n */\nasync function draftCampaign(input: AiCampaignDraftInput): Promise<AiJobStepOutcome> {\n const write = await input.campaign.write({\n ...input.context,\n id: aiJobDraftId(input.job, 'campaign'),\n name: aiCampaignName(input.job, input.copy),\n content: aiCampaignDraftContent(input.designId, input.copy),\n })\n if (write.ok === false) {\n return write.status === 403\n ? { ...input.spent, review: aiLimitReview(write.error) }\n : { ...input.spent, failure: AI_CAMPAIGN_SAVE_FAILURE_COPY }\n }\n return {\n ...input.spent,\n outputs: [...input.outputs, aiCampaignOutput(write, input.place, input.note)],\n }\n}\n\nexport const runAiJobCampaignStep = createAiJobCampaignStep()\n\n/**\n * The least time one campaign step needs before it starts (AGL-3035): the\n * email generation it drafts the campaign's design with, on the campaign's own\n * routing row. Writing the draft campaign asks no model.\n */\nexport const AI_JOB_CAMPAIGN_STEP_MINIMUM_MS = AI_JOB_EMAIL_STEP_BUDGETS['job.campaign'].minimumMs\n\n/** Registers the campaign step and the check a campaign job passes before it is created or resumed. */\nexport function registerAiCampaignJob(): void {\n registerAiJobStep('campaign', runAiJobCampaignStep, { minimumMs: AI_JOB_CAMPAIGN_STEP_MINIMUM_MS })\n registerAiJobAdmission('campaign', aiCampaignJobAdmission)\n}\n"],"names":["checkQuota","aiModelForStep","readSiteInventory","aiCampaignAudienceNote","readAiListSendTime","resolveAiEmailProducts","suggestAiCampaignList","registerAiJobAdmission","aiJobDraftId","aiSiteSubdomain","aiConfirmedPlan","aiDoctrineReview","aiGenerationSpent","aiLimitReview","aiUnspentOutcome","AI_EMAIL_DESIGN_RESOURCE","AI_EMAIL_SAVE_FAILURE_COPY","AI_JOB_EMAIL_STEP_BUDGETS","aiEmailDesignContent","aiEmailDesignOutput","aiJobInputName","generateAiEmail","aiPluginDraftAdmissionRefusal","aiPluginDraftWriter","registerAiJobStep","AI_CAMPAIGN_RESOURCE","AI_JOB_CAMPAIGN_DEFAULT_NAME","AI_CAMPAIGN_UNAVAILABLE_COPY","AI_CAMPAIGN_SAVE_FAILURE_COPY","AI_CAMPAIGN_PLAN_REFUSAL","aiCampaignPlanAllows","org","allowed","aiCampaignOutput","record","place","note","resource","id","versionId","hostId","hostSubdomain","label","name","aiCampaignCopyFromDesign","lines","value","Array","isArray","filter","entry","subject","String","facts","preheader","subjects","preheaders","length","aiCampaignDraftContent","designId","copy","templateScreenId","subjectVariants","preheaderVariants","aiCampaignName","job","aiCampaignJobAdmission","context","kind","drafts","ownCheck","status","error","writers","writerFor","design","campaign","createAiJobCampaignStep","deps","readInventory","now","signal","firestore","modelFor","orgSnapshot","Error","model","found","failure","writtenDesign","writtenCampaign","Promise","all","read","outputs","collection","doc","orgId","get","data","review","uid","createdBy","list","brief","sendTime","listId","draftCampaign","spent","inventory","products","inputs","refusal","asked","generated","step","heading","plan","result","refused","nodes","write","content","ok","input","runAiJobCampaignStep","AI_JOB_CAMPAIGN_STEP_MINIMUM_MS","minimumMs","registerAiCampaignJob"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,2C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Y2D;AACrC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-campaign-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 { checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport type {\n PluginDraftRecord,\n PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport type { AiJob, AiJobOutput } from '../model/ai-jobs.types'\nimport { aiModelForStep } from '../providers/routing'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport {\n aiCampaignAudienceNote,\n readAiListSendTime,\n resolveAiEmailProducts,\n suggestAiCampaignList,\n} from './ai-email-bindings'\nimport { registerAiJobAdmission, type AiJobAdmission } from './ai-job-admission'\nimport { aiJobDraftId } from './ai-job-draft-ids'\nimport { aiSiteSubdomain } from './ai-job-drafts'\nimport {\n aiConfirmedPlan,\n aiDoctrineReview,\n aiGenerationSpent,\n aiLimitReview,\n aiUnspentOutcome,\n} from './ai-job-generation'\nimport {\n AI_EMAIL_DESIGN_RESOURCE,\n AI_EMAIL_SAVE_FAILURE_COPY,\n AI_JOB_EMAIL_STEP_BUDGETS,\n aiEmailDesignContent,\n aiEmailDesignOutput,\n aiJobInputName,\n generateAiEmail,\n type AiEmailCopy,\n} from './ai-job-email-step'\nimport {\n aiPluginDraftAdmissionRefusal,\n aiPluginDraftWriter,\n type AiPluginDraftWriterLookup,\n} from './ai-job-plugin-drafts'\nimport type { AiJobStepOutcome, AiJobStepRunner } from './ai-job-text-step'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The campaign step (AGL-2912): one brief becomes an email design AND the\n * draft campaign that would send it.\n *\n * A campaign is an unplanned kind — there is one thing to build and a plan\n * over it would be a plan of one — so the job runs this step alone, and the\n * design it writes is the email step's, generated through `generateAiEmail`\n * so both kinds obey the same doctrine and the same email rules.\n *\n * ## Nothing is sent, and nothing is aimed\n *\n * The campaign is written `draft`, with no audience, no schedule and no\n * sender: a draft campaign is not a queued one, the scheduled processor\n * queries `status == 'scheduled'`, and the send route is the only thing that\n * mails a campaign. Choosing WHO receives it stays a person's decision, so\n * the model is never shown the org's lists, its contacts or what past sends\n * did. Code reads the list the brief names and the send time that list's own\n * history suggests, AFTER the answer, and both reach the person as the\n * output's `note` — never the prompt.\n *\n * ## Where campaign email begins\n *\n * A site whose plan sends no campaign email can still generate email designs;\n * the campaign is the part that needs somewhere to send. So the step gates on\n * the same entitlement the composer and the send route read, and stops the\n * job for a person rather than failing it. The refusal names no plan, because\n * the billing page is the one place that does.\n *\n * ## Run again and it finds its drafts\n *\n * Each write is keyed by the id the job recorded for its draft when it was\n * created, so a run cut off between them finds what it wrote: two drafts are\n * reported, a design alone is drafted into a campaign from the copy the\n * design already stores, and neither spends.\n */\n\n/** The resource the marketing plugin writes a draft campaign under. */\nexport const AI_CAMPAIGN_RESOURCE = 'campaign'\n\n/** A campaign's name when neither the job nor its subject lines give one. */\nexport const AI_JOB_CAMPAIGN_DEFAULT_NAME = 'New campaign'\n\n/** A job's failure when the site has no campaign writer. */\nexport const AI_CAMPAIGN_UNAVAILABLE_COPY = 'Campaigns are not available on this site.'\n\n/** A job's failure when a campaign whose email was written could not be drafted. */\nexport const AI_CAMPAIGN_SAVE_FAILURE_COPY =\n 'The email was written but the campaign could not be drafted. Try the job again.'\n\n/**\n * What a person is told when their plan sends no campaign email. It names the\n * page that sells the answer rather than a plan, so the one place plan names\n * are written stays the one place they are read.\n */\nexport const AI_CAMPAIGN_PLAN_REFUSAL =\n 'Campaign email is not included on this workspace’s plan. ' +\n 'Upgrade in Billing to send campaigns, or generate an email design on its own.'\n\n/** Whether this workspace may send campaign email at all: the composer's and the send route's check. */\nexport function aiCampaignPlanAllows(org: object | null): boolean {\n return checkQuota(org as Partial<AglynOrgBilling> | null, 'emailSendsPerMonth', 0).allowed\n}\n\n/** The campaign as the job's output, carrying what the person still decides. */\nexport function aiCampaignOutput(\n record: PluginDraftRecord,\n place: { hostId: string; hostSubdomain: string | null },\n note: string | null,\n): AiJobOutput {\n return {\n resource: 'campaign',\n id: record.id,\n versionId: null,\n hostId: place.hostId,\n hostSubdomain: place.hostSubdomain,\n label: record.name,\n ...(note ? { note } : {}),\n }\n}\n\n/** The subject lines and preheaders a written design already stores. */\nexport function aiCampaignCopyFromDesign(record: PluginDraftRecord): AiEmailCopy {\n const lines = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : []\n const subject = String(record.facts?.['subject'] ?? '')\n const preheader = String(record.facts?.['preheader'] ?? '')\n const subjects = lines(record.facts?.['subjectVariants'])\n const preheaders = lines(record.facts?.['preheaderVariants'])\n return {\n subjects: subjects.length ? subjects : subject ? [subject] : [],\n preheaders: preheaders.length ? preheaders : preheader ? [preheader] : [],\n }\n}\n\n/** The campaign's content: the design it sends, and the copy the send fills its headers from. */\nexport function aiCampaignDraftContent(\n designId: string,\n copy: AiEmailCopy,\n): Record<string, unknown> {\n return {\n templateScreenId: designId,\n subject: copy.subjects[0] ?? '',\n preheader: copy.preheaders[0] ?? '',\n subjectVariants: copy.subjects,\n preheaderVariants: copy.preheaders,\n }\n}\n\n/** A campaign job's name: what the member asked for, else its strongest subject line. */\nexport function aiCampaignName(job: Pick<AiJob, 'inputs'>, copy: AiEmailCopy): string {\n return aiJobInputName(job) || copy.subjects[0] || AI_JOB_CAMPAIGN_DEFAULT_NAME\n}\n\n/**\n * A campaign job is admitted for a site of its org with email and marketing\n * on, room for a design and a campaign, and a plan that sends campaign email.\n */\nexport const aiCampaignJobAdmission: AiJobAdmission = (context) =>\n aiPluginDraftAdmissionRefusal(context, {\n kind: 'campaign',\n drafts: [\n { resource: AI_EMAIL_DESIGN_RESOURCE, label: 'Email' },\n { resource: AI_CAMPAIGN_RESOURCE, label: 'Marketing' },\n ],\n ownCheck: async () =>\n aiCampaignPlanAllows(context.org)\n ? null\n : { status: 403, error: AI_CAMPAIGN_PLAN_REFUSAL },\n })\n\nexport interface AiJobCampaignStepDeps {\n /** The inventory reader; specs hand in a fake. */\n readInventory?: typeof readSiteInventory\n /** How a resource's draft writer is found; the core's registry otherwise. */\n writerFor?: AiPluginDraftWriterLookup\n}\n\n/** Both drafts, or the refusal that stands in for a writer the site has not got. */\nfunction writers(\n writerFor: AiPluginDraftWriterLookup,\n): { design: PluginResourceDraftWriter; campaign: PluginResourceDraftWriter } | string {\n const design = writerFor(AI_EMAIL_DESIGN_RESOURCE)\n const campaign = writerFor(AI_CAMPAIGN_RESOURCE)\n if (!design) return AI_CAMPAIGN_UNAVAILABLE_COPY\n if (!campaign) return AI_CAMPAIGN_UNAVAILABLE_COPY\n return { design, campaign }\n}\n\nexport function createAiJobCampaignStep(deps: AiJobCampaignStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const writerFor = deps.writerFor ?? aiPluginDraftWriter\n return async ({ job, now, signal, firestore, modelFor }): Promise<AiJobStepOutcome> => {\n const hostId = job.hostId\n if (!hostId) throw new Error('a campaign job names no site, and its admission refuses one')\n // The switch's answer for this job, else the routing table's (AGL-2942).\n const model = modelFor?.('job.campaign') ?? aiModelForStep('job.campaign')\n const found = writers(writerFor)\n if (typeof found === 'string') return { ...aiUnspentOutcome(model), failure: found }\n const { design, campaign } = found\n\n // What an earlier run of this same job already wrote, under the ids the job recorded.\n const designId = aiJobDraftId(job, 'email')\n const [writtenDesign, writtenCampaign, hostSubdomain] = await Promise.all([\n design.read({ hostId, id: designId }),\n campaign.read({ hostId, id: aiJobDraftId(job, 'campaign') }),\n aiSiteSubdomain(firestore, hostId),\n ])\n const place = { hostId, hostSubdomain }\n if (writtenDesign && writtenCampaign) {\n return aiUnspentOutcome(model, {\n outputs: [\n aiEmailDesignOutput(writtenDesign, place, null),\n aiCampaignOutput(writtenCampaign, place, null),\n ],\n })\n }\n\n const orgSnapshot = await firestore.collection('orgs').doc(job.orgId).get()\n const org = (orgSnapshot.data() ?? null) as Record<string, unknown> | null\n // Asked again here because a plan can change between admission and the run.\n if (!aiCampaignPlanAllows(org)) {\n return aiUnspentOutcome(model, { review: aiLimitReview(AI_CAMPAIGN_PLAN_REFUSAL) })\n }\n const context = { orgId: job.orgId, hostId, uid: job.createdBy, via: `ai-job:${job.$id}`, org, now }\n\n // Who it is for and when to send it: read from the site, told to the\n // person, and never sent to the model.\n const list = await suggestAiCampaignList({ hostId, brief: job.brief })\n const sendTime = list ? await readAiListSendTime({ ...context, listId: list.id }) : null\n const note = aiCampaignAudienceNote(list, sendTime)\n\n // A design an earlier run wrote is drafted into its campaign, unspent.\n if (writtenDesign) {\n return draftCampaign({\n campaign,\n context,\n job,\n copy: aiCampaignCopyFromDesign(writtenDesign),\n designId: writtenDesign.id,\n spent: aiUnspentOutcome(model),\n outputs: [aiEmailDesignOutput(writtenDesign, place, null)],\n place,\n note,\n })\n }\n\n const [inventory, products] = await Promise.all([\n readInventory(job.orgId, hostId, { firestore }),\n resolveAiEmailProducts({ hostId, brief: job.brief, inputs: job.inputs }),\n ])\n const refusal = await design.refusal(context)\n if (refusal) {\n return refusal.status === 403\n ? aiUnspentOutcome(model, { review: aiLimitReview(refusal.error) })\n : { ...aiUnspentOutcome(model), failure: refusal.error }\n }\n\n const asked = aiJobInputName(job)\n const generated = await generateAiEmail({\n job,\n step: 'job.campaign',\n model,\n heading: asked ? `Campaign name: ${asked}` : null,\n plan: aiConfirmedPlan(job),\n inventory,\n hostId,\n products,\n design,\n ...(signal ? { signal } : {}),\n })\n const { result } = generated\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 if (!generated.copy || !generated.nodes) return { ...spent, failure: AI_EMAIL_SAVE_FAILURE_COPY }\n\n const { copy } = generated\n const name = aiCampaignName(job, copy)\n const write = await design.write({\n ...context,\n id: designId,\n name,\n content: aiEmailDesignContent(generated.nodes, copy),\n })\n if (write.ok === false) {\n return write.status === 403\n ? { ...spent, review: aiLimitReview(write.error) }\n : { ...spent, failure: AI_EMAIL_SAVE_FAILURE_COPY }\n }\n return draftCampaign({\n campaign,\n context,\n job,\n copy,\n designId: write.id,\n spent,\n outputs: [aiEmailDesignOutput(write, place, null)],\n place,\n note,\n })\n }\n}\n\ninterface AiCampaignDraftInput {\n campaign: PluginResourceDraftWriter\n context: { orgId: string; hostId: string; uid: string; org: Record<string, unknown> | null; now: Date }\n job: AiJob\n copy: AiEmailCopy\n designId: string\n /** What the generation cost, or an unspent outcome for a run that reached no model. */\n spent: Pick<AiJobStepOutcome, 'outputs' | 'usage' | 'estCostUsd' | 'model' | 'stopReason'>\n /** The design's output, reported beside the campaign once it is drafted. */\n outputs: AiJobOutput[]\n place: { hostId: string; hostSubdomain: string | null }\n note: string\n}\n\n/**\n * Drafts the campaign around a design that exists. A campaign that cannot be\n * drafted reports NO outputs: the design on its own is not what the job was\n * asked for, and a run that names it would read as finished.\n */\nasync function draftCampaign(input: AiCampaignDraftInput): Promise<AiJobStepOutcome> {\n const write = await input.campaign.write({\n ...input.context,\n id: aiJobDraftId(input.job, 'campaign'),\n name: aiCampaignName(input.job, input.copy),\n content: aiCampaignDraftContent(input.designId, input.copy),\n })\n if (write.ok === false) {\n return write.status === 403\n ? { ...input.spent, review: aiLimitReview(write.error) }\n : { ...input.spent, failure: AI_CAMPAIGN_SAVE_FAILURE_COPY }\n }\n return {\n ...input.spent,\n outputs: [...input.outputs, aiCampaignOutput(write, input.place, input.note)],\n }\n}\n\nexport const runAiJobCampaignStep = createAiJobCampaignStep()\n\n/**\n * The least time one campaign step needs before it starts (AGL-3035): the\n * email generation it drafts the campaign's design with, on the campaign's own\n * routing row. Writing the draft campaign asks no model.\n */\nexport const AI_JOB_CAMPAIGN_STEP_MINIMUM_MS = AI_JOB_EMAIL_STEP_BUDGETS['job.campaign'].minimumMs\n\n/** Registers the campaign step and the check a campaign job passes before it is created or resumed. */\nexport function registerAiCampaignJob(): void {\n registerAiJobStep('campaign', runAiJobCampaignStep, { minimumMs: AI_JOB_CAMPAIGN_STEP_MINIMUM_MS })\n registerAiJobAdmission('campaign', aiCampaignJobAdmission)\n}\n"],"names":["checkQuota","aiModelForStep","readSiteInventory","aiCampaignAudienceNote","readAiListSendTime","resolveAiEmailProducts","suggestAiCampaignList","registerAiJobAdmission","aiJobDraftId","aiSiteSubdomain","aiConfirmedPlan","aiDoctrineReview","aiGenerationSpent","aiLimitReview","aiUnspentOutcome","AI_EMAIL_DESIGN_RESOURCE","AI_EMAIL_SAVE_FAILURE_COPY","AI_JOB_EMAIL_STEP_BUDGETS","aiEmailDesignContent","aiEmailDesignOutput","aiJobInputName","generateAiEmail","aiPluginDraftAdmissionRefusal","aiPluginDraftWriter","registerAiJobStep","AI_CAMPAIGN_RESOURCE","AI_JOB_CAMPAIGN_DEFAULT_NAME","AI_CAMPAIGN_UNAVAILABLE_COPY","AI_CAMPAIGN_SAVE_FAILURE_COPY","AI_CAMPAIGN_PLAN_REFUSAL","aiCampaignPlanAllows","org","allowed","aiCampaignOutput","record","place","note","resource","id","versionId","hostId","hostSubdomain","label","name","aiCampaignCopyFromDesign","lines","value","Array","isArray","filter","entry","subject","String","facts","preheader","subjects","preheaders","length","aiCampaignDraftContent","designId","copy","templateScreenId","subjectVariants","preheaderVariants","aiCampaignName","job","aiCampaignJobAdmission","context","kind","drafts","ownCheck","status","error","writers","writerFor","design","campaign","createAiJobCampaignStep","deps","readInventory","now","signal","firestore","modelFor","orgSnapshot","Error","model","found","failure","writtenDesign","writtenCampaign","Promise","all","read","outputs","collection","doc","orgId","get","data","review","uid","createdBy","via","$id","list","brief","sendTime","listId","draftCampaign","spent","inventory","products","inputs","refusal","asked","generated","step","heading","plan","result","refused","nodes","write","content","ok","input","runAiJobCampaignStep","AI_JOB_CAMPAIGN_STEP_MINIMUM_MS","minimumMs","registerAiCampaignJob"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,2CAA0C;AAOrE,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SAASC,iBAAiB,QAAQ,+BAA2B;AAC7D,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,sBAAsB,EACtBC,qBAAqB,QAChB,yBAAqB;AAC5B,SAASC,sBAAsB,QAA6B,wBAAoB;AAChF,SAASC,YAAY,QAAQ,wBAAoB;AACjD,SAASC,eAAe,QAAQ,qBAAiB;AACjD,SACEC,eAAe,EACfC,gBAAgB,EAChBC,iBAAiB,EACjBC,aAAa,EACbC,gBAAgB,QACX,yBAAqB;AAC5B,SACEC,wBAAwB,EACxBC,0BAA0B,EAC1BC,yBAAyB,EACzBC,oBAAoB,EACpBC,mBAAmB,EACnBC,cAAc,EACdC,eAAe,QAEV,yBAAqB;AAC5B,SACEC,6BAA6B,EAC7BC,mBAAmB,QAEd,4BAAwB;AAE/B,SAASC,iBAAiB,QAAQ,eAAW;AAE7C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkCC,GAED,qEAAqE,GACrE,OAAO,MAAMC,uBAAuB,WAAU;AAE9C,2EAA2E,GAC3E,OAAO,MAAMC,+BAA+B,eAAc;AAE1D,0DAA0D,GAC1D,OAAO,MAAMC,+BAA+B,4CAA2C;AAEvF,kFAAkF,GAClF,OAAO,MAAMC,gCACX,kFAAiF;AAEnF;;;;CAIC,GACD,OAAO,MAAMC,2BACX,8DACA,gFAA+E;AAEjF,sGAAsG,GACtG,OAAO,SAASC,qBAAqBC,GAAkB;IACrD,OAAO/B,WAAW+B,KAAwC,sBAAsB,GA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MAAMhC,OAAO;YAAE7D,iBAAiB0F,OAAOG,MAAM3F,KAAK,EAAE2F,MAAM1F,IAAI;SAAE;;AAEjF;AAEA,OAAO,MAAM2F,uBAAuBlD,0BAAyB;AAE7D;;;;CAIC,GACD,OAAO,MAAMmD,kCAAkC/G,yBAAyB,CAAC,eAAe,CAACgH,SAAS,CAAA;AAElG,qGAAqG,GACrG,OAAO,SAASC;IACd1G,kBAAkB,YAAYuG,sBAAsB;QAAEE,WAAWD;IAAgC;IACjGzH,uBAAuB,YAAY2D;AACrC"}
@@ -27,7 +27,7 @@ import { aiBuildingPlanCreations, aiJobPlanCreationsRefusal, aiPlanCreationsRunM
27
27
  import { aiJobStepBudget } from "./ai-job-budget.js";
28
28
  import { aiComponentCheck, aiPlannedComponentProps } from "./ai-job-component-checks.js";
29
29
  import { aiJobDraftId } from "./ai-job-draft-ids.js";
30
- import { aiDraftAdmissionRefusal, aiDraftAllowanceRefusal, aiSiteSubdomain, readAiDraft, readAiDraftComponentProps, writeAiDraft } from "./ai-job-drafts.js";
30
+ import { aiDraftAdmissionRefusal, aiDraftAllowanceRefusal, aiSiteSubdomain, readAiDraft, readAiDraftComponentProps, aiJobContentActor, writeAiDraft } from "./ai-job-drafts.js";
31
31
  import { aiBracketedFactsNote, aiConfirmedPlan, aiDoctrineReview, aiGenerationSpent, aiJobBriefLine, aiLimitReview, aiPlanCreation, aiPlanReferenceLines, aiUnspentOutcome } from "./ai-job-generation.js";
32
32
  import { registerAiJobStep } from "./ai-jobs.js";
33
33
  /**
@@ -312,6 +312,7 @@ export function createAiJobComponentStep(deps = {}) {
312
312
  hostId,
313
313
  id: draftId,
314
314
  uid: job.createdBy,
315
+ actor: aiJobContentActor(job),
315
316
  org,
316
317
  name,
317
318
  nodes: result.value.nodes,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-component-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 type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport type { ReusableComponentProp } from '@aglyn/aglyn/foundation/definitions/platform.types'\nimport { duplicateResource } from '@aglyn/tenant-data-admin/server/duplicate-resource'\nimport { aiPlanEmbedsFor } from '../model/ai-build-plan'\nimport type { AiJob, AiJobOutput, AiJobPlan, AiJobReview } from '../model/ai-jobs.types'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport { runValidatedGeneration } from '../runtime/ai-doctrine'\nimport type { AiDoctrineTree } from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport {\n AI_COMPONENT_TOOL_NAME,\n aiComponentPropKindWords,\n aiComponentTool,\n} from '../tools/ai-component-tool'\nimport { registerAiJobAdmission, type AiJobAdmission } from './ai-job-admission'\nimport {\n aiBuildingPlanCreations,\n aiJobPlanCreationsRefusal,\n aiPlanCreationsRunMinimumMs,\n} from './ai-job-plan-creations'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiComponentCheck, aiPlannedComponentProps } from './ai-job-component-checks'\nimport { aiJobDraftId } from './ai-job-draft-ids'\nimport {\n aiDraftAdmissionRefusal,\n aiDraftAllowanceRefusal,\n aiSiteSubdomain,\n readAiDraft,\n readAiDraftComponentProps,\n writeAiDraft,\n type AiDraftRecord,\n} from './ai-job-drafts'\nimport {\n aiBracketedFactsNote,\n aiConfirmedPlan,\n aiDoctrineReview,\n aiGenerationSpent,\n aiJobBriefLine,\n aiLimitReview,\n aiPlanCreation,\n aiPlanReferenceLines,\n aiUnspentOutcome,\n} from './ai-job-generation'\nimport type { AiJobStepRunner } from './ai-job-text-step'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The component step (AGL-2908): the generation step of a `component` job,\n * run once a member confirmed the job's plan.\n *\n * It builds ONE reusable component from the brief — its tree, and the typed\n * properties each page that places it fills in — through\n * `runValidatedGeneration('component', …)`, so every building rule holds on\n * the tree before it is kept. The tree binds each property with\n * `{{prop.<name>}}`; the palette validator keeps those tokens as written\n * (`definesComponent`), and the step's own check, through `extend`, holds\n * each binding to what the Properties dialog and the Attributes panel allow\n * (`ai-job-component-checks.ts`).\n *\n * The component lands as a new draft (`ai-job-drafts.ts`) that no page\n * places, and gets its first version when a member opens it, as every\n * component created outside the besigner does. A plan that starts from a copy\n * of a component the site has gets that copy, through the platform's\n * duplicate module, and nothing generated.\n *\n * A generation step runs on the job beat, never at an inline door: it\n * registers the least time its lookup rounds, its answer and its re-ask need\n * (AGL-3035), runs without extended thinking, and asks for no more of the\n * ceiling the layout and template steps keep than fits that time on the model\n * it runs. The step's spec measures the request and the answer against it.\n */\n\n/** The longest answer a component may run to; the tree is held to the component budget either way. */\nexport const AI_JOB_COMPONENT_MAX_TOKENS = AI_ROUTING_TABLE['job.component'].maxTokens\n\n/**\n * The component step's time (AGL-3035, AGL-3036): its two inventory-lookup\n * rounds, its answer and its re-ask at the routing table's ceiling on the tier\n * `job.component` is served from, fitted to what a beat can give a step.\n */\nexport const AI_JOB_COMPONENT_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.component'],\n maxTokens: AI_JOB_COMPONENT_MAX_TOKENS,\n})\n\n/** The least time one component step needs before it starts. */\nexport const AI_JOB_COMPONENT_STEP_MINIMUM_MS = AI_JOB_COMPONENT_STEP_BUDGET.minimumMs\n\n/** A component's name when the plan names none. */\nexport const AI_JOB_COMPONENT_DEFAULT_NAME = 'Component'\n\n/** The component step's own instructions, cached after the doctrine and before the catalog. */\nexport const AI_JOB_COMPONENT_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n `You build one reusable component for a website: a block the site places on many pages, each placement filling in its own values. Answer with ${AI_COMPONENT_TOOL_NAME}: the component’s tree as one flat node map, and the properties it declares.`,\n 'The root is the document wrapper holding the component. A component is placed inside a page section, which opens with its own h2: it carries no main landmark, its headings are h3 or below, and its colors, spacing and type come from the theme.',\n 'Every value that should differ from one placement to the next is a property, bound in the tree with its token {{prop.<name>}}. Declare every property the tree binds, and bind every property you declare.',\n `Property kinds, as type (the name a page reads): ${aiComponentPropKindWords()}.`,\n 'A property binds only to a field that holds its kind of value:',\n '- text, richText and number: copy, such as a Typography’s text, an Image’s alt or a Button’s label, as the whole value or inside a sentence.',\n '- image: an Image’s src, as the whole value.',\n '- href: a screenId or an href, as the whole value.',\n '- icon: an Icon element’s iconId, as the whole value.',\n '- boolean: a switch setting such as a Button’s fullWidth, or hideIf on the part it hides, as the whole value.',\n '- choice: a setting with fixed options such as a Button’s variant, as the whole value, with every answer’s value one that setting lists.',\n 'An optional part, such as a photo, a badge or a second button, gets a boolean property labeled \"Hide <the part>\" whose default is \"false\", and the part’s own element carries \"hideIf\": \"{{prop.<name>}}\". Never hide the whole component.',\n 'A default is what the component shows until a page sets it: copy in the site’s voice from the brief, with a fact the brief does not give in square brackets; for href a page id from the site inventory, or \"\"; for image \"\", for an upload; for icon \"\", for the site owner to pick; for choice one of its answers’ values.',\n ].join('\\n'),\n },\n]\n\n/** The component job as the generation's user turn: the name, the brief, the confirmed plan. */\nexport function aiJobComponentPrompt(\n job: Pick<AiJob, 'brief'>,\n plan: AiJobPlan | null,\n name: string,\n): string {\n return [`Component name: ${name}`, aiJobBriefLine(job), ...aiPlanReferenceLines(plan)].join('\\n')\n}\n\n/**\n * The props the confirmed plan gives the component, against the component a\n * COPY actually produced (AGL-3024); `null` when the copy keeps the plan, or\n * when the plan promised no prop to keep.\n *\n * The third kind to need this, after the layout (`aiCopiedLayoutReview`) and\n * the page (`aiCopiedPageReview`), and found the same way: a duplicate branch\n * generates nothing, so it is the one place a plan's promise can go unmet\n * with no model to answer for it.\n *\n * MEASURED 2026-09-21. A plan read \"the existing card has no link target; the\n * brief needs one\", and `practice-area-link-card` came out BYTE-IDENTICAL to\n * `practice-area-card` — the same seven nodes under the same ids, the same\n * three props, no link anywhere. Its job reported the copy as built. So did\n * `practice-area-link-card-v2` the following pass. A component job can\n * therefore charge a member for a duplicate of something they already had.\n *\n * A copy that cannot be read back settles nothing, and a promise this step\n * cannot settle is reviewed by a person rather than reported as kept.\n */\nexport async function aiCopiedComponentReview(\n firestore: FirebaseFirestore.Firestore,\n input: { hostId: string; id: string; name: string; plan: AiJobPlan | null },\n): Promise<AiJobReview | null> {\n const promised = aiPlannedComponentProps(input.plan)\n if (!promised.length) return null\n const declared = await readAiDraftComponentProps(firestore, { hostId: input.hostId, id: input.id })\n if (declared === null) {\n return {\n reason: 'doctrine',\n message: `\"${input.name}\" was copied from the component the plan names, and this job could not read the copy back to check it has the properties the plan gives it. Open the component and check it before you place it.`,\n findings: [],\n }\n }\n const missing = promised.filter((name) => !declared.includes(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 component the plan names, and a copy is all it is: the plan gives it ${\n one ? 'a property' : 'properties'\n } the copy does not have.`,\n violations: [\n {\n rule: null,\n code: 'plan-props-missing',\n message: `The confirmed plan says this component has ${missing.join(', ')}, and the copy has ${\n declared.length ? declared.join(', ') : 'none of them'\n }. Add ${one ? 'it' : 'each of them'}, and use ${\n one ? 'it' : 'them'\n } in the component, or the copy is the component it was copied from.`,\n },\n ],\n })\n}\n\n/**\n * A component job is admitted for a site of the job's own org whose plan\n * includes reusable components, and confirmed only for a plan whose other\n * creations it builds (AGL-3143 §15).\n */\nexport const aiComponentJobAdmission: AiJobAdmission = (context) =>\n aiDraftAdmissionRefusal(context.firestore, {\n orgId: context.orgId,\n hostId: context.hostId,\n kind: 'component',\n org: context.org,\n ownCheck: (hostId) => aiJobPlanCreationsRefusal('component', context, hostId),\n })\n\nexport interface AiJobComponentStepDeps {\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}\n\nexport function createAiJobComponentStep(deps: AiJobComponentStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const duplicate = deps.duplicate ?? duplicateResource\n return async ({ job, now, signal, firestore, modelFor }) => {\n const hostId = job.hostId\n if (!hostId) throw new Error('a component job names no site, and its admission refuses one')\n const output = (draft: AiDraftRecord, load?: AiLoadEstimate | null, note?: string | null): AiJobOutput => ({\n resource: 'reusableComponent',\n id: draft.id,\n versionId: draft.versionId,\n hostId,\n hostSubdomain: draft.hostSubdomain,\n label: draft.name,\n ...(load ? { load } : {}),\n ...(note ? { note } : {}),\n })\n // The switch's answer for this job, else the routing table's (AGL-2942).\n const model = modelFor?.('job.component') ?? aiModelForStep('job.component')\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, 'component')\n const written = await readAiDraft(firestore, { kind: 'component', 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, 'component')\n const name = creation?.name || AI_JOB_COMPONENT_DEFAULT_NAME\n\n // The plan starts from a copy of a component the site has (rule 15): the\n // copy is the draft, and nothing is generated. A source gone since the\n // plan was made is built from the brief instead, and one that lacks a\n // property the plan gives the component is built from the plan\n // (AGL-3143 §14): copying it could only end in the review below. A source\n // this step cannot read still copies.\n const source = creation?.duplicateOf\n ? inventory.components.find((component) => component.id === creation.duplicateOf)\n : undefined\n const sourceReview = source\n ? await aiCopiedComponentReview(firestore, { hostId, id: source.id, name: source.name, plan })\n : null\n if (creation?.duplicateOf && source && !sourceReview?.findings.length) {\n const copy = await duplicate('component', {\n orgId: job.orgId,\n hostId,\n sourceId: creation.duplicateOf,\n name,\n uid: job.createdBy,\n org: org as Record<string, unknown> | null,\n // The same claim the page step makes (AGL-3024): a copy core mints is\n // written under core's own id, never `draftId`, so a step that runs\n // again — a pass resumed, a run cut off after the copy — would mint a\n // second. The job's recorded id makes core replay the one it made.\n attemptKey: draftId,\n })\n if (copy.ok) {\n const hostSubdomain = await aiSiteSubdomain(firestore, hostId)\n // The copy is reported with what the plan promised of it read back\n // (AGL-3024): this branch generates nothing, so without this a plan\n // reading \"duplicate it and add a link\" reports Done on a duplicate\n // that added nothing.\n const review = await aiCopiedComponentReview(firestore, {\n hostId,\n id: copy.id,\n name: copy.name,\n plan,\n })\n if (review) return aiUnspentOutcome(model, { review })\n return aiUnspentOutcome(model, {\n outputs: [\n output({ id: copy.id, versionId: copy.versionId ?? null, name: copy.name, hostSubdomain }),\n ],\n })\n }\n if (copy.ok === false && copy.status === 403) {\n return aiUnspentOutcome(model, { review: aiLimitReview(copy.error) })\n }\n }\n\n const allowance = await aiDraftAllowanceRefusal(firestore, { kind: 'component', hostId, org })\n if (allowance) return aiUnspentOutcome(model, { review: aiLimitReview(allowance) })\n\n let props: ReusableComponentProp[] = []\n const result = await runValidatedGeneration('component', {\n step: 'job.component',\n model,\n instructions: AI_JOB_COMPONENT_INSTRUCTIONS,\n inventory,\n messages: [{ role: 'user', content: aiJobComponentPrompt(job, plan, name) }],\n tool: aiComponentTool(),\n maxTokens: AI_JOB_COMPONENT_STEP_BUDGET.maxTokens(model),\n ...(AI_ROUTING_TABLE['job.component'].thinking\n ? { thinking: AI_ROUTING_TABLE['job.component'].thinking }\n : {}),\n ...(AI_ROUTING_TABLE['job.component'].effort\n ? { effort: AI_ROUTING_TABLE['job.component'].effort }\n : {}),\n // A third-party player the confirmed plan lists for this component is the only one it may embed (AGL-3433).\n context: {\n definesComponent: true,\n ...(creation ? { plannedEmbeds: aiPlanEmbedsFor(plan, { create: creation.name }) } : {}),\n },\n extend: aiComponentCheck({\n inventory,\n plan,\n onProps: (declared) => {\n props = declared\n },\n }),\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(result)\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') return { ...spent, review: aiDoctrineReview(result) }\n\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const draft = await writeAiDraft(firestore, {\n kind: 'component',\n hostId,\n id: draftId,\n uid: job.createdBy,\n org,\n name,\n nodes: result.value.nodes,\n rootId: result.value.rootId,\n props,\n now,\n })\n if (draft.ok === false) {\n if (draft.status === 404) throw new Error(`site ${hostId} vanished while its component was generated`)\n return { ...spent, review: aiLimitReview(draft.error) }\n }\n // The facts the brief did not give, in the tree or the defaults a page shows (AGL-3056).\n const note = aiBracketedFactsNote({\n tree: { rootId: result.value.rootId, nodes: result.value.nodes as unknown as AiDoctrineTree['nodes'] },\n inventory,\n copy: props.map((prop) => (typeof prop.defaultValue === 'string' ? prop.defaultValue : '')),\n })\n return { ...spent, outputs: [output(draft, result.value.load, note)] }\n }\n}\n\n/** The component step, building the forms and other components its plan creates first (AGL-3143 §15). */\nexport const runAiJobComponentStep = aiBuildingPlanCreations(\n 'component',\n 'job.component',\n createAiJobComponentStep(),\n)\n\n/** Registers the component step and the check a component job passes before it is created or resumed. */\nexport function registerAiComponentJob(): void {\n registerAiJobStep('component', runAiJobComponentStep, {\n minimumMs: AI_JOB_COMPONENT_STEP_MINIMUM_MS,\n minimumMsFor: aiPlanCreationsRunMinimumMs('component'),\n })\n registerAiJobAdmission('component', aiComponentJobAdmission)\n}\n"],"names":["throwIfAiJobCanceled","duplicateResource","aiPlanEmbedsFor","AI_STEP_TIERS","AI_ROUTING_TABLE","aiModelForStep","runValidatedGeneration","readSiteInventory","AI_COMPONENT_TOOL_NAME","aiComponentPropKindWords","aiComponentTool","registerAiJobAdmission","aiBuildingPlanCreations","aiJobPlanCreationsRefusal","aiPlanCreationsRunMinimumMs","aiJobStepBudget","aiComponentCheck","aiPlannedComponentProps","aiJobDraftId","aiDraftAdmissionRefusal","aiDraftAllowanceRefusal","aiSiteSubdomain","readAiDraft","readAiDraftComponentProps","writeAiDraft","aiBracketedFactsNote","aiConfirmedPlan","aiDoctrineReview","aiGenerationSpent","aiJobBriefLine","aiLimitReview","aiPlanCreation","aiPlanReferenceLines","aiUnspentOutcome","registerAiJobStep","AI_JOB_COMPONENT_MAX_TOKENS","maxTokens","AI_JOB_COMPONENT_STEP_BUDGET","tier","AI_JOB_COMPONENT_STEP_MINIMUM_MS","minimumMs","AI_JOB_COMPONENT_DEFAULT_NAME","AI_JOB_COMPONENT_INSTRUCTIONS","text","join","aiJobComponentPrompt","job","plan","name","aiCopiedComponentReview","firestore","input","promised","length","declared","hostId","id","reason","message","findings","missing","filter","includes","one","violations","rule","code","aiComponentJobAdmission","context","orgId","kind","org","ownCheck","createAiJobComponentStep","deps","readInventory","duplicate","now","signal","modelFor","orgSnapshot","Error","output","draft","load","note","resource","versionId","hostSubdomain","label","model","draftId","written","outputs","inventory","Promise","all","collection","doc","get","data","creation","source","duplicateOf","components","find","component","undefined","sourceReview","copy","sourceId","uid","createdBy","attemptKey","ok","review","status","error","allowance","props","result","step","instructions","messages","role","content","tool","thinking","effort","definesComponent","plannedEmbeds","create","extend","onProps","spent","refused","nodes","value","rootId","tree","map","prop","defaultValue","runAiJobComponentStep","registerAiComponentJob","minimumMsFor"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,qBAAiB;AAGtD,SAASC,iBAAiB,QAAQ,qDAAoD;AACtF,SAASC,eAAe,QAAQ,4BAA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,KAAK,WAAWD,KAAKC,YAAY,GAAG;QACzF;QACA,OAAO,aAAKR;YAAOzC,SAAS;gBAACX,OAAOC,OAAOqC,OAAOiB,KAAK,CAACrD,IAAI,EAAEC;aAAM;;IACtE;AACF;AAEA,uGAAuG,GACvG,OAAO,MAAM0D,wBAAwBnI,wBACnC,aACA,iBACA6D,4BACD;AAED,uGAAuG,GACvG,OAAO,SAASuE;IACd9G,kBAAkB,aAAa6G,uBAAuB;QACpDvG,WAAWD;QACX0G,cAAcnI,4BAA4B;IAC5C;IACAH,uBAAuB,aAAawD;AACtC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-component-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 type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport type { ReusableComponentProp } from '@aglyn/aglyn/foundation/definitions/platform.types'\nimport { duplicateResource } from '@aglyn/tenant-data-admin/server/duplicate-resource'\nimport { aiPlanEmbedsFor } from '../model/ai-build-plan'\nimport type { AiJob, AiJobOutput, AiJobPlan, AiJobReview } from '../model/ai-jobs.types'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport { runValidatedGeneration } from '../runtime/ai-doctrine'\nimport type { AiDoctrineTree } from '../runtime/ai-doctrine-validators'\nimport type { AiLoadEstimate } from '../runtime/ai-palette'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { readSiteInventory } from '../runtime/site-inventory'\nimport {\n AI_COMPONENT_TOOL_NAME,\n aiComponentPropKindWords,\n aiComponentTool,\n} from '../tools/ai-component-tool'\nimport { registerAiJobAdmission, type AiJobAdmission } from './ai-job-admission'\nimport {\n aiBuildingPlanCreations,\n aiJobPlanCreationsRefusal,\n aiPlanCreationsRunMinimumMs,\n} from './ai-job-plan-creations'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiComponentCheck, aiPlannedComponentProps } from './ai-job-component-checks'\nimport { aiJobDraftId } from './ai-job-draft-ids'\nimport {\n aiDraftAdmissionRefusal,\n aiDraftAllowanceRefusal,\n aiSiteSubdomain,\n readAiDraft,\n readAiDraftComponentProps,\n aiJobContentActor,\n writeAiDraft,\n type AiDraftRecord,\n} from './ai-job-drafts'\nimport {\n aiBracketedFactsNote,\n aiConfirmedPlan,\n aiDoctrineReview,\n aiGenerationSpent,\n aiJobBriefLine,\n aiLimitReview,\n aiPlanCreation,\n aiPlanReferenceLines,\n aiUnspentOutcome,\n} from './ai-job-generation'\nimport type { AiJobStepRunner } from './ai-job-text-step'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The component step (AGL-2908): the generation step of a `component` job,\n * run once a member confirmed the job's plan.\n *\n * It builds ONE reusable component from the brief — its tree, and the typed\n * properties each page that places it fills in — through\n * `runValidatedGeneration('component', …)`, so every building rule holds on\n * the tree before it is kept. The tree binds each property with\n * `{{prop.<name>}}`; the palette validator keeps those tokens as written\n * (`definesComponent`), and the step's own check, through `extend`, holds\n * each binding to what the Properties dialog and the Attributes panel allow\n * (`ai-job-component-checks.ts`).\n *\n * The component lands as a new draft (`ai-job-drafts.ts`) that no page\n * places, and gets its first version when a member opens it, as every\n * component created outside the besigner does. A plan that starts from a copy\n * of a component the site has gets that copy, through the platform's\n * duplicate module, and nothing generated.\n *\n * A generation step runs on the job beat, never at an inline door: it\n * registers the least time its lookup rounds, its answer and its re-ask need\n * (AGL-3035), runs without extended thinking, and asks for no more of the\n * ceiling the layout and template steps keep than fits that time on the model\n * it runs. The step's spec measures the request and the answer against it.\n */\n\n/** The longest answer a component may run to; the tree is held to the component budget either way. */\nexport const AI_JOB_COMPONENT_MAX_TOKENS = AI_ROUTING_TABLE['job.component'].maxTokens\n\n/**\n * The component step's time (AGL-3035, AGL-3036): its two inventory-lookup\n * rounds, its answer and its re-ask at the routing table's ceiling on the tier\n * `job.component` is served from, fitted to what a beat can give a step.\n */\nexport const AI_JOB_COMPONENT_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.component'],\n maxTokens: AI_JOB_COMPONENT_MAX_TOKENS,\n})\n\n/** The least time one component step needs before it starts. */\nexport const AI_JOB_COMPONENT_STEP_MINIMUM_MS = AI_JOB_COMPONENT_STEP_BUDGET.minimumMs\n\n/** A component's name when the plan names none. */\nexport const AI_JOB_COMPONENT_DEFAULT_NAME = 'Component'\n\n/** The component step's own instructions, cached after the doctrine and before the catalog. */\nexport const AI_JOB_COMPONENT_INSTRUCTIONS: readonly AiSystemBlock[] = [\n {\n text: [\n `You build one reusable component for a website: a block the site places on many pages, each placement filling in its own values. Answer with ${AI_COMPONENT_TOOL_NAME}: the component’s tree as one flat node map, and the properties it declares.`,\n 'The root is the document wrapper holding the component. A component is placed inside a page section, which opens with its own h2: it carries no main landmark, its headings are h3 or below, and its colors, spacing and type come from the theme.',\n 'Every value that should differ from one placement to the next is a property, bound in the tree with its token {{prop.<name>}}. Declare every property the tree binds, and bind every property you declare.',\n `Property kinds, as type (the name a page reads): ${aiComponentPropKindWords()}.`,\n 'A property binds only to a field that holds its kind of value:',\n '- text, richText and number: copy, such as a Typography’s text, an Image’s alt or a Button’s label, as the whole value or inside a sentence.',\n '- image: an Image’s src, as the whole value.',\n '- href: a screenId or an href, as the whole value.',\n '- icon: an Icon element’s iconId, as the whole value.',\n '- boolean: a switch setting such as a Button’s fullWidth, or hideIf on the part it hides, as the whole value.',\n '- choice: a setting with fixed options such as a Button’s variant, as the whole value, with every answer’s value one that setting lists.',\n 'An optional part, such as a photo, a badge or a second button, gets a boolean property labeled \"Hide <the part>\" whose default is \"false\", and the part’s own element carries \"hideIf\": \"{{prop.<name>}}\". Never hide the whole component.',\n 'A default is what the component shows until a page sets it: copy in the site’s voice from the brief, with a fact the brief does not give in square brackets; for href a page id from the site inventory, or \"\"; for image \"\", for an upload; for icon \"\", for the site owner to pick; for choice one of its answers’ values.',\n ].join('\\n'),\n },\n]\n\n/** The component job as the generation's user turn: the name, the brief, the confirmed plan. */\nexport function aiJobComponentPrompt(\n job: Pick<AiJob, 'brief'>,\n plan: AiJobPlan | null,\n name: string,\n): string {\n return [`Component name: ${name}`, aiJobBriefLine(job), ...aiPlanReferenceLines(plan)].join('\\n')\n}\n\n/**\n * The props the confirmed plan gives the component, against the component a\n * COPY actually produced (AGL-3024); `null` when the copy keeps the plan, or\n * when the plan promised no prop to keep.\n *\n * The third kind to need this, after the layout (`aiCopiedLayoutReview`) and\n * the page (`aiCopiedPageReview`), and found the same way: a duplicate branch\n * generates nothing, so it is the one place a plan's promise can go unmet\n * with no model to answer for it.\n *\n * MEASURED 2026-09-21. A plan read \"the existing card has no link target; the\n * brief needs one\", and `practice-area-link-card` came out BYTE-IDENTICAL to\n * `practice-area-card` — the same seven nodes under the same ids, the same\n * three props, no link anywhere. Its job reported the copy as built. So did\n * `practice-area-link-card-v2` the following pass. A component job can\n * therefore charge a member for a duplicate of something they already had.\n *\n * A copy that cannot be read back settles nothing, and a promise this step\n * cannot settle is reviewed by a person rather than reported as kept.\n */\nexport async function aiCopiedComponentReview(\n firestore: FirebaseFirestore.Firestore,\n input: { hostId: string; id: string; name: string; plan: AiJobPlan | null },\n): Promise<AiJobReview | null> {\n const promised = aiPlannedComponentProps(input.plan)\n if (!promised.length) return null\n const declared = await readAiDraftComponentProps(firestore, { hostId: input.hostId, id: input.id })\n if (declared === null) {\n return {\n reason: 'doctrine',\n message: `\"${input.name}\" was copied from the component the plan names, and this job could not read the copy back to check it has the properties the plan gives it. Open the component and check it before you place it.`,\n findings: [],\n }\n }\n const missing = promised.filter((name) => !declared.includes(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 component the plan names, and a copy is all it is: the plan gives it ${\n one ? 'a property' : 'properties'\n } the copy does not have.`,\n violations: [\n {\n rule: null,\n code: 'plan-props-missing',\n message: `The confirmed plan says this component has ${missing.join(', ')}, and the copy has ${\n declared.length ? declared.join(', ') : 'none of them'\n }. Add ${one ? 'it' : 'each of them'}, and use ${\n one ? 'it' : 'them'\n } in the component, or the copy is the component it was copied from.`,\n },\n ],\n })\n}\n\n/**\n * A component job is admitted for a site of the job's own org whose plan\n * includes reusable components, and confirmed only for a plan whose other\n * creations it builds (AGL-3143 §15).\n */\nexport const aiComponentJobAdmission: AiJobAdmission = (context) =>\n aiDraftAdmissionRefusal(context.firestore, {\n orgId: context.orgId,\n hostId: context.hostId,\n kind: 'component',\n org: context.org,\n ownCheck: (hostId) => aiJobPlanCreationsRefusal('component', context, hostId),\n })\n\nexport interface AiJobComponentStepDeps {\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}\n\nexport function createAiJobComponentStep(deps: AiJobComponentStepDeps = {}): AiJobStepRunner {\n const readInventory = deps.readInventory ?? readSiteInventory\n const duplicate = deps.duplicate ?? duplicateResource\n return async ({ job, now, signal, firestore, modelFor }) => {\n const hostId = job.hostId\n if (!hostId) throw new Error('a component job names no site, and its admission refuses one')\n const output = (draft: AiDraftRecord, load?: AiLoadEstimate | null, note?: string | null): AiJobOutput => ({\n resource: 'reusableComponent',\n id: draft.id,\n versionId: draft.versionId,\n hostId,\n hostSubdomain: draft.hostSubdomain,\n label: draft.name,\n ...(load ? { load } : {}),\n ...(note ? { note } : {}),\n })\n // The switch's answer for this job, else the routing table's (AGL-2942).\n const model = modelFor?.('job.component') ?? aiModelForStep('job.component')\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, 'component')\n const written = await readAiDraft(firestore, { kind: 'component', 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, 'component')\n const name = creation?.name || AI_JOB_COMPONENT_DEFAULT_NAME\n\n // The plan starts from a copy of a component the site has (rule 15): the\n // copy is the draft, and nothing is generated. A source gone since the\n // plan was made is built from the brief instead, and one that lacks a\n // property the plan gives the component is built from the plan\n // (AGL-3143 §14): copying it could only end in the review below. A source\n // this step cannot read still copies.\n const source = creation?.duplicateOf\n ? inventory.components.find((component) => component.id === creation.duplicateOf)\n : undefined\n const sourceReview = source\n ? await aiCopiedComponentReview(firestore, { hostId, id: source.id, name: source.name, plan })\n : null\n if (creation?.duplicateOf && source && !sourceReview?.findings.length) {\n const copy = await duplicate('component', {\n orgId: job.orgId,\n hostId,\n sourceId: creation.duplicateOf,\n name,\n uid: job.createdBy,\n org: org as Record<string, unknown> | null,\n // The same claim the page step makes (AGL-3024): a copy core mints is\n // written under core's own id, never `draftId`, so a step that runs\n // again — a pass resumed, a run cut off after the copy — would mint a\n // second. The job's recorded id makes core replay the one it made.\n attemptKey: draftId,\n })\n if (copy.ok) {\n const hostSubdomain = await aiSiteSubdomain(firestore, hostId)\n // The copy is reported with what the plan promised of it read back\n // (AGL-3024): this branch generates nothing, so without this a plan\n // reading \"duplicate it and add a link\" reports Done on a duplicate\n // that added nothing.\n const review = await aiCopiedComponentReview(firestore, {\n hostId,\n id: copy.id,\n name: copy.name,\n plan,\n })\n if (review) return aiUnspentOutcome(model, { review })\n return aiUnspentOutcome(model, {\n outputs: [\n output({ id: copy.id, versionId: copy.versionId ?? null, name: copy.name, hostSubdomain }),\n ],\n })\n }\n if (copy.ok === false && copy.status === 403) {\n return aiUnspentOutcome(model, { review: aiLimitReview(copy.error) })\n }\n }\n\n const allowance = await aiDraftAllowanceRefusal(firestore, { kind: 'component', hostId, org })\n if (allowance) return aiUnspentOutcome(model, { review: aiLimitReview(allowance) })\n\n let props: ReusableComponentProp[] = []\n const result = await runValidatedGeneration('component', {\n step: 'job.component',\n model,\n instructions: AI_JOB_COMPONENT_INSTRUCTIONS,\n inventory,\n messages: [{ role: 'user', content: aiJobComponentPrompt(job, plan, name) }],\n tool: aiComponentTool(),\n maxTokens: AI_JOB_COMPONENT_STEP_BUDGET.maxTokens(model),\n ...(AI_ROUTING_TABLE['job.component'].thinking\n ? { thinking: AI_ROUTING_TABLE['job.component'].thinking }\n : {}),\n ...(AI_ROUTING_TABLE['job.component'].effort\n ? { effort: AI_ROUTING_TABLE['job.component'].effort }\n : {}),\n // A third-party player the confirmed plan lists for this component is the only one it may embed (AGL-3433).\n context: {\n definesComponent: true,\n ...(creation ? { plannedEmbeds: aiPlanEmbedsFor(plan, { create: creation.name }) } : {}),\n },\n extend: aiComponentCheck({\n inventory,\n plan,\n onProps: (declared) => {\n props = declared\n },\n }),\n ...(signal ? { signal } : {}),\n })\n const spent = aiGenerationSpent(result)\n if (result.status === 'refused') return { ...spent, refused: true }\n if (result.status === 'needs_input') return { ...spent, review: aiDoctrineReview(result) }\n\n // Never written once the job is canceled (AGL-3616).\n throwIfAiJobCanceled(signal)\n const draft = await writeAiDraft(firestore, {\n kind: 'component',\n hostId,\n id: draftId,\n uid: job.createdBy,\n actor: aiJobContentActor(job),\n org,\n name,\n nodes: result.value.nodes,\n rootId: result.value.rootId,\n props,\n now,\n })\n if (draft.ok === false) {\n if (draft.status === 404) throw new Error(`site ${hostId} vanished while its component was generated`)\n return { ...spent, review: aiLimitReview(draft.error) }\n }\n // The facts the brief did not give, in the tree or the defaults a page shows (AGL-3056).\n const note = aiBracketedFactsNote({\n tree: { rootId: result.value.rootId, nodes: result.value.nodes as unknown as AiDoctrineTree['nodes'] },\n inventory,\n copy: props.map((prop) => (typeof prop.defaultValue === 'string' ? prop.defaultValue : '')),\n })\n return { ...spent, outputs: [output(draft, result.value.load, note)] }\n }\n}\n\n/** The component step, building the forms and other components its plan creates first (AGL-3143 §15). */\nexport const runAiJobComponentStep = aiBuildingPlanCreations(\n 'component',\n 'job.component',\n createAiJobComponentStep(),\n)\n\n/** Registers the component step and the check a component job passes before it is created or resumed. */\nexport function registerAiComponentJob(): void {\n registerAiJobStep('component', runAiJobComponentStep, {\n minimumMs: AI_JOB_COMPONENT_STEP_MINIMUM_MS,\n minimumMsFor: aiPlanCreationsRunMinimumMs('component'),\n })\n registerAiJobAdmission('component', aiComponentJobAdmission)\n}\n"],"names":["throwIfAiJobCanceled","duplicateResource","aiPlanEmbedsFor","AI_STEP_TIERS","AI_ROUTING_TABLE","aiModelForStep","runValidatedGeneration","readSiteInventory","AI_COMPONENT_TOOL_NAME","aiComponentPropKindWords","aiComponentTool","registerAiJobAdmission","aiBuildingPlanCreations","aiJobPlanCreationsRefusal","aiPlanCreationsRunMinimumMs","aiJobStepBudget","aiComponentCheck","aiPlannedComponentProps","aiJobDraftId","aiDraftAdmissionRefusal","aiDraftAllowanceRefusal","aiSiteSubdomain","readAiDraft","readAiDraftComponentProps","aiJobContentActor","writeAiDraft","aiBracketedFactsNote","aiConfirmedPlan","aiDoctrineReview","aiGenerationSpent","aiJobBriefLine","aiLimitReview","aiPlanCreation","aiPlanReferenceLines","aiUnspentOutcome","registerAiJobStep","AI_JOB_COMPONENT_MAX_TOKENS","maxTokens","AI_JOB_COMPONENT_STEP_BUDGET","tier","AI_JOB_COMPONENT_STEP_MINIMUM_MS","minimumMs","AI_JOB_COMPONENT_DEFAULT_NAME","AI_JOB_COMPONENT_INSTRUCTIONS","text","join","aiJobComponentPrompt","job","plan","name","aiCopiedComponentReview","firestore","input","promised","length","declared","hostId","id","reason","message","findings","missing","filter","includes","one","violations","rule","code","aiComponentJobAdmission","context","orgId","kind","org","ownCheck","createAiJobComponentStep","deps","readInventory","duplicate","now","signal","modelFor","orgSnapshot","Error","output","draft","load","note","resource","versionId","hostSubdomain","label","model","draftId","written","outputs","inventory","Promise","all","collection","doc","get","data","creation","source","duplicateOf","components","find","component","undefined","sourceReview","copy","sourceId","uid","createdBy","attemptKey","ok","review","status","error","allowance","props","result","step","instructions","messages","role","content","tool","thinking","effort","definesComponent","plannedEmbeds","create","extend","onProps","spent","refused","actor","nodes","value","rootId","tree","map","prop","defaultValue","runAiJobComponentStep","registerAiComponentJob","minimumMsFor"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,qBAAiB;AAGtD,SAASC,iBAAiB,QAAQ,qDAAoD;AACtF,SAASC,eAAe,QAAQ,4BAAwB;AAExD,SAASC,aAAa,QAAQ,0BAAsB;AACpD,SAASC,gBAAgB,EAAEC,cAAc,QAAQ,0BAAsB;AACvE,SAASC,sBAAsB,QAAQ,4BAAwB;AAI/D,SAASC,iBAAiB,QAAQ,+BAA2B;AAC7D,SACEC,sBAAsB,EACtBC,wBAAwB,EACxBC,eAAe,QACV,gCAA4B;AACnC,SAASC,sBAAsB,QAA6B,wBAAoB;AAChF,SACEC,uBAAuB,EACvBC,yBAAyB,EACzBC,2BAA2B,QACtB,6BAAyB;AAChC,SAASC,eAAe,QAAQ,qBAAiB;AACjD,SAASC,gBAAgB,EAAEC,uBAAuB,QAAQ,+BAA2B;AACrF,SAASC,YAAY,QAAQ,wBAAoB;AACjD,SACEC,uBAAuB,EACvBC,uBAAuB,EACvBC,eAAe,EACfC,WAAW,EACXC,yBAAyB,EACzBC,iBAAiB,EACjBC,YAAY,QAEP,qBAAiB;AACxB,SACEC,oBAAoB,EACpBC,eAAe,EACfC,gBAAgB,EAChBC,iBAAiB,EACjBC,cAAc,EACdC,aAAa,EACbC,cAAc,EACdC,oBAAoB,EACpBC,gBAAgB,QACX,yBAA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OjH,kBAAkBuB;YACzByB;YACAvB;YACAyF,OAAOjB,OAAOkB,KAAK,CAACD,KAAK;YACzBE,QAAQnB,OAAOkB,KAAK,CAACC,MAAM;YAC3BpB;YACA1C;QACF;QACA,IAAIM,MAAM+B,EAAE,KAAK,OAAO;YACtB,IAAI/B,MAAMiC,MAAM,KAAK,KAAK,MAAM,IAAInC,MAAM,CAAC,KAAK,EAAE1B,OAAO,2CAA2C,CAAC;YACrG,OAAO,aAAK+E;gBAAOnB,QAAQrF,cAAcqD,MAAMkC,KAAK;;QACtD;QACA,yFAAyF;QACzF,MAAMhC,OAAO5D,qBAAqB;YAChCmH,MAAM;gBAAED,QAAQnB,OAAOkB,KAAK,CAACC,MAAM;gBAAEF,OAAOjB,OAAOkB,KAAK,CAACD,KAAK;YAAuC;YACrG3C;YACAe,MAAMU,MAAMsB,GAAG,CAAC,CAACC,OAAU,OAAOA,KAAKC,YAAY,KAAK,WAAWD,KAAKC,YAAY,GAAG;QACzF;QACA,OAAO,aAAKT;YAAOzC,SAAS;gBAACX,OAAOC,OAAOqC,OAAOkB,KAAK,CAACtD,IAAI,EAAEC;aAAM;;IACtE;AACF;AAEA,uGAAuG,GACvG,OAAO,MAAM2D,wBAAwBrI,wBACnC,aACA,iBACA8D,4BACD;AAED,uGAAuG,GACvG,OAAO,SAASwE;IACd/G,kBAAkB,aAAa8G,uBAAuB;QACpDxG,WAAWD;QACX2G,cAAcrI,4BAA4B;IAC5C;IACAH,uBAAuB,aAAayD;AACtC"}
@@ -15,12 +15,16 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  import { type FormFieldDecl, type FormRouting } from '@aglyn/aglyn/app-utils/forms';
18
+ import { type ContentWriteActor } from '@aglyn/aglyn/app-utils/content-write-stamp';
18
19
  import type { HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens';
19
20
  import type { AglynOrgBilling, OrgFeatureFlags } from '@aglyn/aglyn/foundation/definitions/org-billing.types';
20
21
  import { HostScreenVisibility, type ReusableComponentProp } from '@aglyn/aglyn/foundation/definitions/platform.types';
21
22
  import type { NodesMap } from '@aglyn/aglyn/types/nodes';
22
23
  import { type AiPlanCapabilities } from '../model/ai-plan-capabilities';
24
+ import type { AiJob } from '../model/ai-jobs.types';
23
25
  import type { AiJobAdmissionRefusal } from './ai-job-admission';
26
+ /** Who a job's write to a site's pages is for: the person who started it, by way of the job. */
27
+ export declare function aiJobContentActor(job: Pick<AiJob, '$id' | 'createdBy'>): ContentWriteActor;
24
28
  /**
25
29
  * Where a generation job's layout, page template, form, reusable component
26
30
  * or page lands (AGL-2909, AGL-2913, AGL-2908, AGL-2907): a new draft, made
@@ -309,6 +313,8 @@ export interface AiDraftInput {
309
313
  * names the site job, not the unit's derived id.
310
314
  */
311
315
  aiJobId?: string | null;
316
+ /** Who the write is for, stamped on a layout, page or component and its first version. */
317
+ actor: ContentWriteActor;
312
318
  now: Date;
313
319
  }
314
320
  /** What a form draft declares beside its design, read off that design. */
@@ -355,6 +361,7 @@ export declare function updateAiDraftNodes(firestore: Firestore, input: {
355
361
  kind: AiVersionedDraftKind;
356
362
  hostId: string;
357
363
  id: string;
364
+ actor: ContentWriteActor;
358
365
  now: Date;
359
366
  update: (nodes: NodesMap) => NodesMap | null;
360
367
  }): Promise<AiDraftNodesUpdate>;
@@ -369,6 +376,7 @@ export declare function writeAiDraftScreenSeo(firestore: Firestore, input: {
369
376
  title?: string | null;
370
377
  description?: string | null;
371
378
  };
379
+ actor: ContentWriteActor;
372
380
  now: Date;
373
381
  }): Promise<void>;
374
382
  /** The site's subdomain, which a console link names the site by. */
@@ -18,6 +18,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
18
18
  import { uniqueDuplicateName } from "@aglyn/aglyn/app-utils/duplicate-resource";
19
19
  import { FORM_COMPONENT_ID, newFormListFields, normalizeFormSlug } from "@aglyn/aglyn/app-utils/forms";
20
20
  import { artifactCreateListKeys } from "@aglyn/aglyn/app-utils/artifact-list-keys";
21
+ import { contentEditStamp } from "@aglyn/aglyn/app-utils/content-write-stamp";
21
22
  import { checkDatasetQuota, checkEntitlement, checkQuota, resolveEffectivePlan, resolveOrgEntitlements } from "@aglyn/aglyn/app-utils/plan-entitlements";
22
23
  import { billableScreenIds, SCREEN_ROOT_PATH } from "@aglyn/aglyn/app-utils/screen-route";
23
24
  import { decodeStoredNodes, encodeStoredNodes } from "@aglyn/aglyn/app-utils/stored-nodes";
@@ -25,6 +26,12 @@ import { draftScreenSlug } from "@aglyn/aglyn/app-utils/draft-screen-slug";
25
26
  import { HostScreenVisibility } from "@aglyn/aglyn/foundation/definitions/platform.types";
26
27
  import { resolveOrgIdForHost } from "@aglyn/tenant-data-admin/server/organizations";
27
28
  import { aiUnrestrictedPlanCapabilities } from "../model/ai-plan-capabilities.js";
29
+ /** Who a job's write to a site's pages is for: the person who started it, by way of the job. */ export function aiJobContentActor(job) {
30
+ return {
31
+ uid: job.createdBy,
32
+ via: `ai-job:${job.$id}`
33
+ };
34
+ }
28
35
  /** The console host resources route's allow-list for each kind. */ export const AI_DRAFT_FIELDS = {
29
36
  layout: [
30
37
  'displayName',
@@ -497,6 +504,8 @@ function recordOf(id, draft, host) {
497
504
  updatedAt: input.now,
498
505
  createdBy: input.uid
499
506
  };
507
+ // Layouts, pages and components carry who wrote them; templates and forms do not.
508
+ const tracked = _extends({}, stamps, contentEditStamp(input.actor, input.now));
500
509
  const marker = input.aiJobId ? {
501
510
  aiJobId: input.aiJobId
502
511
  } : {};
@@ -509,13 +518,13 @@ function recordOf(id, draft, host) {
509
518
  versionId
510
519
  }), artifactCreateListKeys('layouts', {
511
520
  displayName: name
512
- }), stamps, marker));
521
+ }), tracked, marker));
513
522
  tx.create(draftRef.collection('versions').doc(versionId), _extends({
514
523
  layoutId: input.id,
515
524
  hostId: input.hostId,
516
525
  displayName: AI_DRAFT_VERSION_NAME,
517
526
  nodes
518
- }, stamps, marker));
527
+ }, tracked, marker));
519
528
  } else if (input.kind === 'screen') {
520
529
  versionId = createResourceUid();
521
530
  tx.create(draftRef, _extends({}, allowListed('screen', {
@@ -526,7 +535,7 @@ function recordOf(id, draft, host) {
526
535
  displayName: name
527
536
  }), input.visibility === HostScreenVisibility.UNLISTED ? {
528
537
  visibility: HostScreenVisibility.UNLISTED
529
- } : {}, stamps, marker));
538
+ } : {}, tracked, marker));
530
539
  tx.create(draftRef.collection('versions').doc(versionId), _extends({
531
540
  screenId: input.id,
532
541
  hostId: input.hostId,
@@ -534,7 +543,7 @@ function recordOf(id, draft, host) {
534
543
  nodes
535
544
  }, input.layoutId ? {
536
545
  layoutId: input.layoutId
537
- } : {}, stamps, marker));
546
+ } : {}, tracked, marker));
538
547
  } else if (input.kind === 'template') {
539
548
  tx.create(draftRef, _extends({}, allowListed('template', {
540
549
  kind: 'page',
@@ -563,7 +572,7 @@ function recordOf(id, draft, host) {
563
572
  ] : undefined
564
573
  }), artifactCreateListKeys('components', {
565
574
  displayName: name
566
- }), stamps));
575
+ }), tracked));
567
576
  } else {
568
577
  var _encodeStoredNodes, _form_routing;
569
578
  const form = input.form;
@@ -627,10 +636,9 @@ function recordOf(id, draft, host) {
627
636
  };
628
637
  const packed = encodeStoredNodes(next);
629
638
  if (!packed) throw new Error('an AI draft needs a node map');
630
- tx.update(versionRef, {
631
- nodes: Buffer.from(packed),
632
- updatedAt: input.now
633
- });
639
+ tx.update(versionRef, _extends({
640
+ nodes: Buffer.from(packed)
641
+ }, contentEditStamp(input.actor, input.now)));
634
642
  return {
635
643
  ok: true,
636
644
  changed: true
@@ -654,9 +662,7 @@ function recordOf(id, draft, host) {
654
662
  const value = String((_input_seo_key = input.seo[key]) != null ? _input_seo_key : '').trim();
655
663
  if (value && !String((_screen_get = screen.get(`seo.${key}`)) != null ? _screen_get : '').trim()) patch[`seo.${key}`] = value;
656
664
  }
657
- if (Object.keys(patch).length) tx.update(ref, _extends({}, patch, {
658
- updatedAt: input.now
659
- }));
665
+ if (Object.keys(patch).length) tx.update(ref, _extends({}, patch, contentEditStamp(input.actor, input.now)));
660
666
  });
661
667
  }
662
668
  /** The site's subdomain, which a console link names the site by. */ export async function aiSiteSubdomain(firestore, hostId) {