@aglyn/plugins-ai 1.31.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 (104) hide show
  1. package/README.md +2 -1
  2. package/package.json +17 -17
  3. package/src/lib/components/site-chat-api.d.ts +38 -0
  4. package/src/lib/components/site-chat-api.js +65 -0
  5. package/src/lib/components/site-chat-api.js.map +1 -0
  6. package/src/lib/components/site-chat-card.component.d.ts +31 -0
  7. package/src/lib/components/site-chat-card.component.js +474 -0
  8. package/src/lib/components/site-chat-card.component.js.map +1 -0
  9. package/src/lib/components/site-chat-panel.d.ts +38 -0
  10. package/src/lib/components/site-chat-panel.js +749 -0
  11. package/src/lib/components/site-chat-panel.js.map +1 -0
  12. package/src/lib/components/site-chat-runtime.d.ts +29 -0
  13. package/src/lib/components/site-chat-runtime.js +166 -0
  14. package/src/lib/components/site-chat-runtime.js.map +1 -0
  15. package/src/lib/declarations.js +5 -0
  16. package/src/lib/declarations.js.map +1 -1
  17. package/src/lib/jobs/ai-job-campaign-step.js +1 -0
  18. package/src/lib/jobs/ai-job-campaign-step.js.map +1 -1
  19. package/src/lib/jobs/ai-job-component-step.js +2 -1
  20. package/src/lib/jobs/ai-job-component-step.js.map +1 -1
  21. package/src/lib/jobs/ai-job-drafts.d.ts +8 -0
  22. package/src/lib/jobs/ai-job-drafts.js +18 -12
  23. package/src/lib/jobs/ai-job-drafts.js.map +1 -1
  24. package/src/lib/jobs/ai-job-edit-step.d.ts +5 -0
  25. package/src/lib/jobs/ai-job-edit-step.js +16 -9
  26. package/src/lib/jobs/ai-job-edit-step.js.map +1 -1
  27. package/src/lib/jobs/ai-job-email-step.js +1 -0
  28. package/src/lib/jobs/ai-job-email-step.js.map +1 -1
  29. package/src/lib/jobs/ai-job-form-step.js +2 -1
  30. package/src/lib/jobs/ai-job-form-step.js.map +1 -1
  31. package/src/lib/jobs/ai-job-layout-step.js +4 -1
  32. package/src/lib/jobs/ai-job-layout-step.js.map +1 -1
  33. package/src/lib/jobs/ai-job-navigation-step.js +7 -3
  34. package/src/lib/jobs/ai-job-navigation-step.js.map +1 -1
  35. package/src/lib/jobs/ai-job-page-step.js +7 -1
  36. package/src/lib/jobs/ai-job-page-step.js.map +1 -1
  37. package/src/lib/jobs/ai-job-privacy-step.d.ts +2 -0
  38. package/src/lib/jobs/ai-job-privacy-step.js +7 -4
  39. package/src/lib/jobs/ai-job-privacy-step.js.map +1 -1
  40. package/src/lib/jobs/ai-job-site-store-pages.js +3 -1
  41. package/src/lib/jobs/ai-job-site-store-pages.js.map +1 -1
  42. package/src/lib/jobs/ai-job-store-links-layout.js +8 -4
  43. package/src/lib/jobs/ai-job-store-links-layout.js.map +1 -1
  44. package/src/lib/jobs/ai-job-template-step.js +2 -1
  45. package/src/lib/jobs/ai-job-template-step.js.map +1 -1
  46. package/src/lib/jobs/ai-site-import-forms.js +2 -1
  47. package/src/lib/jobs/ai-site-import-forms.js.map +1 -1
  48. package/src/lib/jobs/ai-site-import-publish.d.ts +1 -1
  49. package/src/lib/jobs/ai-site-import-publish.js.map +1 -1
  50. package/src/lib/jobs/ai-site-late-photos.js +2 -1
  51. package/src/lib/jobs/ai-site-late-photos.js.map +1 -1
  52. package/src/lib/jobs/ai-site-publish.d.ts +2 -2
  53. package/src/lib/jobs/ai-site-publish.js +23 -15
  54. package/src/lib/jobs/ai-site-publish.js.map +1 -1
  55. package/src/lib/layout-language/ai-layout-frame-source.js +1 -0
  56. package/src/lib/layout-language/ai-layout-frame-source.js.map +1 -1
  57. package/src/lib/model/site-chat.d.ts +219 -0
  58. package/src/lib/model/site-chat.js +200 -0
  59. package/src/lib/model/site-chat.js.map +1 -0
  60. package/src/lib/plugin.js +10 -0
  61. package/src/lib/plugin.js.map +1 -1
  62. package/src/lib/runtime/ai-palette.generated.js +131 -0
  63. package/src/lib/runtime/ai-palette.generated.js.map +1 -1
  64. package/src/lib/server/ai-experiment-versions.js +6 -3
  65. package/src/lib/server/ai-experiment-versions.js.map +1 -1
  66. package/src/lib/server/ai-page-content.js +2 -1
  67. package/src/lib/server/ai-page-content.js.map +1 -1
  68. package/src/lib/server/ai-seo-apply.js +6 -3
  69. package/src/lib/server/ai-seo-apply.js.map +1 -1
  70. package/src/lib/server/site-chat-enricher.d.ts +29 -0
  71. package/src/lib/server/site-chat-enricher.js +41 -0
  72. package/src/lib/server/site-chat-enricher.js.map +1 -0
  73. package/src/lib/server/site-chat-owner-routes.d.ts +56 -0
  74. package/src/lib/server/site-chat-owner-routes.js +209 -0
  75. package/src/lib/server/site-chat-owner-routes.js.map +1 -0
  76. package/src/lib/server/site-chat-page-reads.d.ts +23 -0
  77. package/src/lib/server/site-chat-page-reads.js +32 -0
  78. package/src/lib/server/site-chat-page-reads.js.map +1 -0
  79. package/src/lib/server/site-chat-platform.d.ts +25 -0
  80. package/src/lib/server/site-chat-platform.js +405 -0
  81. package/src/lib/server/site-chat-platform.js.map +1 -0
  82. package/src/lib/server/site-chat-prompt.d.ts +83 -0
  83. package/src/lib/server/site-chat-prompt.js +166 -0
  84. package/src/lib/server/site-chat-prompt.js.map +1 -0
  85. package/src/lib/server/site-chat-session.d.ts +33 -0
  86. package/src/lib/server/site-chat-session.js +105 -0
  87. package/src/lib/server/site-chat-session.js.map +1 -0
  88. package/src/lib/server/site-chat-visitor-routes.d.ts +46 -0
  89. package/src/lib/server/site-chat-visitor-routes.js +105 -0
  90. package/src/lib/server/site-chat-visitor-routes.js.map +1 -0
  91. package/src/lib/server/site-chat.d.ts +119 -0
  92. package/src/lib/server/site-chat.js +500 -0
  93. package/src/lib/server/site-chat.js.map +1 -0
  94. package/src/lib/server.js +4 -0
  95. package/src/lib/server.js.map +1 -1
  96. package/src/lib/site-server.d.ts +23 -0
  97. package/src/lib/site-server.js +41 -0
  98. package/src/lib/site-server.js.map +1 -0
  99. package/src/lib/site.d.ts +23 -0
  100. package/src/lib/site.js +33 -0
  101. package/src/lib/site.js.map +1 -0
  102. package/src/lib/usage/site-chat-meter.d.ts +68 -0
  103. package/src/lib/usage/site-chat-meter.js +125 -0
  104. package/src/lib/usage/site-chat-meter.js.map +1 -0
@@ -279,6 +279,11 @@ export interface AiEditWriteInput<R = never> {
279
279
  * writes none.
280
280
  */
281
281
  updatedByLabel?: string;
282
+ /**
283
+ * How the write arrived, stamped as `updatedVia` (see `content-write-stamp`):
284
+ * an API key or connected app names itself; absent, the AI job does.
285
+ */
286
+ updatedVia?: string | null;
282
287
  /**
283
288
  * Refuse a tree larger than this many bytes, measured as the save measures
284
289
  * it (`measureNodeMap`), and write nothing. Absent: not measured.
@@ -14,7 +14,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { checkEntitlement } from "@aglyn/aglyn/app-utils/plan-entitlements";
17
+ */ import { contentEditStamp, parentPublishStamp, versionPublishStamp, withoutVersionPublishStamp } from "@aglyn/aglyn/app-utils/content-write-stamp";
18
+ import { checkEntitlement } from "@aglyn/aglyn/app-utils/plan-entitlements";
18
19
  import { SCREEN_KIND_TEMPLATE } from "@aglyn/aglyn/app-utils/screen-route";
19
20
  import { screenSeoStageKey, SCREEN_SEO_TEXT_FIELDS } from "@aglyn/aglyn/app-utils/screen-seo-fields";
20
21
  import { hasConcurrentWrite, versionStamp } from "@aglyn/aglyn/app-utils/guarded-version-save";
@@ -463,6 +464,7 @@ function pendingScheduleVersion(doc) {
463
464
  const newRef = versions.doc(input.jobVersionId);
464
465
  const sourceDraftRef = draftRef(versions, input.sourceVersionId);
465
466
  return firestore.runTransaction(async (tx)=>{
467
+ var _input_updatedVia;
466
468
  const [host, doc, source, already, draftDoc] = await Promise.all([
467
469
  tx.get(hostRef),
468
470
  tx.get(docRef),
@@ -555,6 +557,11 @@ function pendingScheduleVersion(doc) {
555
557
  };
556
558
  const stored = Buffer.from(packed);
557
559
  const docPatch = {};
560
+ const writer = {
561
+ uid: input.uid,
562
+ via: (_input_updatedVia = input.updatedVia) != null ? _input_updatedVia : `ai-job:${input.aiJobId}`
563
+ };
564
+ const stamp = contentEditStamp(writer, input.now);
558
565
  if (placement === 'draft') {
559
566
  // The whole working tree, as the Besigner writes a draft, taken against
560
567
  // the version as stored so the Besigner offers it with Open draft.
@@ -565,32 +572,32 @@ function pendingScheduleVersion(doc) {
565
572
  updatedByEmail: null
566
573
  }, input.updatedByLabel ? {
567
574
  updatedByLabel: input.updatedByLabel
568
- } : {}, {
569
- updatedAt: input.now,
575
+ } : {}, stamp, {
570
576
  aiEditJobId: input.jobVersionId
571
577
  }));
572
578
  } else {
573
579
  // A copy of the version it started from — its layout binding, its
574
580
  // declared properties, everything the editor stored — with the changed
575
581
  // tree, as the versions route copies one.
576
- const copy = _extends({}, source.data());
582
+ const copy = withoutVersionPublishStamp(_extends({}, source.data()));
577
583
  delete copy['aiEditJobId'];
584
+ // Moving a served page's pointer is a publish, and is stamped as one.
585
+ const live = placement === 'new-current' && served;
578
586
  tx.create(newRef, _extends({}, copy, {
579
587
  nodes: stored,
580
588
  displayName: input.versionName,
581
589
  createdAt: input.now,
582
- updatedAt: input.now,
583
- createdBy: input.uid,
590
+ createdBy: input.uid
591
+ }, stamp, live ? versionPublishStamp(writer, input.now) : {}, {
584
592
  aiJobId: input.aiJobId
585
593
  }));
586
594
  if (placement === 'new-current') docPatch['versionId'] = input.jobVersionId;
595
+ if (live) Object.assign(docPatch, parentPublishStamp(writer, input.now));
587
596
  }
588
597
  for (const [field, value] of Object.entries(seo)){
589
598
  if (value) docPatch[`seo.${field}`] = value;
590
599
  }
591
- if (Object.keys(docPatch).length) tx.update(docRef, _extends({}, docPatch, {
592
- updatedAt: input.now
593
- }));
600
+ if (Object.keys(docPatch).length) tx.update(docRef, _extends({}, docPatch, stamp));
594
601
  return {
595
602
  ok: true,
596
603
  versionId,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-edit-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 { checkEntitlement } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { SCREEN_KIND_TEMPLATE } from '@aglyn/aglyn/app-utils/screen-route'\nimport { screenSeoStageKey, SCREEN_SEO_TEXT_FIELDS } from '@aglyn/aglyn/app-utils/screen-seo-fields'\nimport { hasConcurrentWrite, versionStamp } from '@aglyn/aglyn/app-utils/guarded-version-save'\nimport { extractLayoutStyleOverrides, injectLayoutStyleOverrides } from '@aglyn/aglyn/app-utils/layout-style-overrides'\nimport { decodeStoredNodes, encodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { coeditMirrorRoomPath, VERSION_DRAFT_COLLECTION, VERSION_DRAFT_DOC_ID } from '@aglyn/aglyn/app-utils/version-draft'\nimport { CanvasManager } from '@aglyn/aglyn/canvas-manager/canvas-manager'\nimport { FEATURE_FLAG } from '@aglyn/aglyn/foundation/constants/shared'\nimport type { EditorSession } from '@aglyn/aglyn/plugin-manager/editor-sessions'\nimport type { NodesMap } from '@aglyn/aglyn/types/nodes'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { resolveOrgIdForHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { measureNodeMap } from '@aglyn/aglyn/app-utils/measure-node-map'\nimport { applyAssistEdit, type AssistEditInserted } from '../components/assist-edit-canvas'\nimport {\n AI_EDIT_COMPONENT_LEFT_OUT,\n AI_EDIT_EMAIL_COPY,\n AI_EDIT_GONE_COPY,\n AI_EDIT_NO_NODES_COPY,\n AI_EDIT_NO_SITE_COPY,\n AI_EDIT_NOTHING_COPY,\n AI_EDIT_REFUSED_COPY,\n AI_EDIT_SEO_LEFT_OUT,\n AI_EDIT_STALE_COPY,\n AI_EDIT_TOO_LARGE_COPY,\n AI_EDIT_VERSION_GONE_COPY,\n aiEditJobOutline,\n aiEditOutputNote,\n aiEditVersionName,\n parseAiEditJobInputs,\n type AiEditJobInputs,\n type AiEditPlacement,\n type AiEditTargetKind,\n} from '../model/ai-edit-job'\nimport type { AiJob, AiJobOutput } from '../model/ai-jobs.types'\nimport {\n ASSIST_EDIT_TOOL_NAME,\n type AssistEditCanvasContext,\n type AssistEditOp,\n type AssistEditProposal,\n type AssistEditTarget,\n} from '../model/assist-edit'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport {\n runValidatedGeneration,\n validateStreamedGeneration,\n type AiCustomGenerationInput,\n} from '../runtime/ai-doctrine'\nimport { AI_PALETTE } from '../runtime/ai-palette.generated'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { readAiSiteDatasets } from '../runtime/site-inventory'\nimport {\n assistEditTool,\n checkAssistEditAnswer,\n editCanvasBlock,\n editDatasetsBlock,\n editSelectionBlock,\n parseAssistEditContext,\n type AssistEditDataset,\n type AssistEditDatasetScope,\n} from '../server/assist-edit'\nimport { registerAiJobAdmission, type AiJobAdmission, type AiJobAdmissionRefusal } from './ai-job-admission'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiOriginJobId } from './ai-job-draft-ids'\nimport { aiGenerationSpent, aiUnspentOutcome } from './ai-job-generation'\nimport { AI_JOB_BRIEF_MAX_CHARS, type AiJobStepOutcome, type AiJobStepRunner } from './ai-job-text-step'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The `edit` step (AGL-3616): a change to a page or a layout the site already\n * has, from a description, made on the server with no editor open.\n *\n * It is the Assist edit rung, run as a job. The model is shown the stored\n * document as the rung's outline and proposes through the rung's own tool;\n * its answer is held to the rung's closed world and palette validators\n * (`checkAssistEditAnswer`) and re-asked once, naming what was left out; and\n * what survives lands through the canvas's own guarded mutators\n * (`applyAssistEdit`), on a `CanvasManager` built headless from the stored\n * nodes, inside the transaction that writes it.\n *\n * ── Where the change lands, decided before anything is spent ────────────\n *\n * Never on a version a visitor sees. By default, on every plan, in the\n * WORKING DRAFT of the version it started from (AGL-4116): the one document\n * the Besigner saves to as an author works and offers with Open draft, which\n * publishing moves into the version. The change is built on the draft the\n * author already has, when the Besigner would still offer it, so their work\n * in progress is never thrown away; otherwise on the version's own tree.\n *\n * Only when the request asks for a new version, and the plan keeps version\n * history, a NEW version beside the one it started from — a copy of that\n * version's stored fields with the changed nodes — which becomes the page's\n * current version only when the page is not published; a published page's\n * current version, and a layout's, never move. Asked for without version\n * history, the change goes into the draft and the output says why.\n *\n * ── What a job cannot do that the editor can ────────────────────────────\n *\n * The rung's chat door never offers saving part of a page as a reusable\n * component, and neither does this. A page's search title and description\n * live on the page itself, not on a version, so they are written only for a\n * page that is not published; on a published page they are left out, and the\n * output's note says so, as it says every change it left out.\n *\n * ── One version per job ──────────────────────────────────────────────────\n *\n * The new version is named by the job's id — a build's unit is named by its\n * plan item's id — so a run asked again finds what it wrote and spends\n * nothing. A draft the job writes is stamped with the job's id for the same\n * reason.\n */\n\n/** The longest the step may take reading the page and writing it. */\nexport const AI_EDIT_READS_MS = 2_000\n\n/** The step's time: its answer and its re-ask at the `job.edit` ceiling, with its own reads. */\nexport const AI_JOB_EDIT_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.edit'],\n maxTokens: AI_ROUTING_TABLE['job.edit'].maxTokens,\n lookups: 0,\n ownReadsMs: AI_EDIT_READS_MS,\n})\n\nexport const AI_JOB_EDIT_STEP_MINIMUM_MS = AI_JOB_EDIT_STEP_BUDGET.minimumMs\n\nexport function aiJobEditModel(): string {\n return aiModelForStep('job.edit')\n}\n\n/**\n * The job's own rules, byte-identical on every request, ahead of the rung's\n * protocol and catalog for the document's kind, which carries the breakpoint:\n * both are the same for every site, so a kind's whole prefix caches once.\n */\nexport const AI_JOB_EDIT_RULES: AiSystemBlock = {\n text: [\n 'You change a page or a layout the person already has, as a job that runs on its own. No editor is open, nothing is selected, and nobody can answer a question before you finish.',\n `- Make exactly the change the request asks for, and keep everything else as it is: other elements, their text, their styles and their order. Never rewrite, restyle, move or remove what the request does not ask about, beyond what making that change needs.`,\n '- Find the elements the request means in the outline of the whole document the request carries, by what they say, what they are and where they sit on the page. Name only ids that outline lists.',\n `- If the outline does not show an element the request is about, change nothing for that part: never guess at an element.`,\n `- Call ${ASSIST_EDIT_TOOL_NAME} exactly once, with every operation. Its summary is one short line saying what changed, in the language of the request; it names the version the change is saved in.`,\n \"- Fill in a page's search title or description only when the request asks for it.\",\n '- What you change is saved where no visitor sees it until the person publishes it, so never say the site or the page has changed.',\n '- The protocol below was written for Assist’s chat. In this job there is no user to ask or to press Apply, and no selection: what it says about those does not apply. Everything else in it — the operations, their fields, the elements and the style tokens — does.',\n ].join('\\n'),\n}\n\n/** The system blocks for one kind of document. */\nexport function aiJobEditInstructions(kind: AiEditTargetKind): AiSystemBlock[] {\n return [AI_JOB_EDIT_RULES, { text: editCanvasBlock(kind), cacheBreakpoint: true }]\n}\n\n/**\n * What the change is asked from: the document's outline, the site's datasets\n * an element may show the records of (AGL-3616), then the request.\n */\nexport function aiJobEditPrompt(input: {\n brief: string\n context: AssistEditCanvasContext\n datasets?: readonly AssistEditDataset[]\n}): string {\n const datasets = editDatasetsBlock(input.datasets ?? [])\n return [\n editSelectionBlock(input.context, { job: true }),\n ...(datasets ? ['', datasets] : []),\n '',\n `Request: ${input.brief.slice(0, AI_JOB_BRIEF_MAX_CHARS)}`,\n ].join('\\n')\n}\n\n/**\n * The datasets an edit to this document knows (AGL-3616): every one the site\n * holds, and the one whose record page the document is, if it is one.\n */\nexport function aiEditDatasetScope(\n datasets: ReadonlyArray<AssistEditDataset & { recordScreenId?: string }>,\n read: Pick<AiEditTargetRead, 'kind' | 'id'>,\n): Required<AssistEditDatasetScope> {\n const record = read.kind === 'screen' ? datasets.find((dataset) => dataset.recordScreenId === read.id) : undefined\n return {\n datasets: datasets.map(({ id, name, fields, fieldIds, imageField }) => ({\n id,\n name,\n fields,\n ...(fieldIds ? { fieldIds } : {}),\n ...(imageField ? { imageField } : {}),\n })),\n recordDatasetId: record?.id ?? null,\n }\n}\n\n/** The edit as the doctrine's loop runs it: the rung's tool, held to the rung's check. */\nexport function aiJobEditGeneration(request: {\n brief: string\n context: AssistEditCanvasContext\n target: AssistEditTarget\n model: string\n signal?: AbortSignal\n} & AssistEditDatasetScope): AiCustomGenerationInput<AssistEditProposal> {\n const row = AI_ROUTING_TABLE['job.edit']\n const kind = request.target.kind as AiEditTargetKind\n return {\n step: 'job.edit',\n model: request.model,\n instructions: aiJobEditInstructions(kind),\n messages: [{ role: 'user', content: aiJobEditPrompt(request) }],\n tool: assistEditTool(kind),\n maxTokens: AI_JOB_EDIT_STEP_BUDGET.maxTokens(request.model),\n ...(row.thinking ? { thinking: row.thinking } : {}),\n ...(row.effort ? { effort: row.effort } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n check: (answer) =>\n checkAssistEditAnswer(answer, {\n context: request.context,\n target: request.target,\n ...(request.datasets ? { datasets: request.datasets } : {}),\n ...(request.recordDatasetId ? { recordDatasetId: request.recordDatasetId } : {}),\n }),\n }\n}\n\n// ── The document, headless ────────────────────────────────────────────────\n\n/**\n * The slice of the platform a headless canvas asks: whether an element takes\n * children, answered from the AI palette the edit validator reads, so the\n * canvas refuses exactly what the validator refuses.\n */\nconst AI_EDIT_CANVAS_PLATFORM = {\n components: {\n getSchema: (componentId: string) => {\n const entry = AI_PALETTE[componentId]\n if (!entry) return undefined\n return entry.acceptsChildren ? {} : { flags: { dropping: FEATURE_FLAG.DISABLED } }\n },\n getLabel: (componentId: string) => AI_PALETTE[componentId]?.displayName ?? componentId,\n },\n}\n\n/** A canvas over a stored node map, with the editor's own guarded mutators and no editor. */\nexport function aiEditCanvas(nodes: NodesMap): CanvasManager {\n const canvas = new CanvasManager(AI_EDIT_CANVAS_PLATFORM as never)\n canvas.setNodes(nodes)\n return canvas\n}\n\n/**\n * Lands a proposal on a stored node map, as the editor lands one on its open\n * canvas: checked whole first, then one batch, all or nothing. The session is\n * the version being written, which is never one a visitor sees; a page's\n * search fields are captured into `seo` only where `seo` is given.\n */\nexport function aiApplyEditToNodes(\n nodes: NodesMap,\n proposal: AssistEditProposal,\n seo?: Partial<Record<(typeof SCREEN_SEO_TEXT_FIELDS)[number], string>>,\n): { ok: true; nodes: NodesMap; inserted: AssistEditInserted[] } | { ok: false; reason: string } {\n const canvas = aiEditCanvas(nodes)\n const fields: Record<string, (value: string) => void> = {}\n if (seo) {\n for (const field of SCREEN_SEO_TEXT_FIELDS) fields[screenSeoStageKey(field)] = (value) => (seo[field] = value)\n }\n const session: EditorSession = {\n documentKind: proposal.target.kind,\n documentId: proposal.target.documentId,\n versionId: proposal.target.versionId,\n isLiveVersion: () => false,\n ...(seo ? { fields } : {}),\n }\n const applied = applyAssistEdit(canvas, proposal, session)\n if (applied.ok === false) return { ok: false, reason: applied.reason }\n return { ok: true, nodes: canvas.toJSON().nodes as NodesMap, inserted: applied.inserted ?? [] }\n}\n\n// ── Reading the document ──────────────────────────────────────────────────\n\ntype Firestore = FirebaseFirestore.Firestore\n\nconst COLLECTIONS: Readonly<Record<AiEditTargetKind, 'screens' | 'layouts'>> = {\n screen: 'screens',\n layout: 'layouts',\n}\n\n/** The page or layout an edit job changes, as it stands before anything is spent. */\nexport interface AiEditTargetRead {\n kind: AiEditTargetKind\n id: string\n name: string\n hostSubdomain: string | null\n /** The document's current version. */\n pointerVersionId: string | null\n /** The version the change starts from. */\n sourceVersionId: string\n /** The version's own tree. */\n nodes: NodesMap\n /**\n * The version's working draft, when it has one the Besigner would still\n * offer: an author's saved work in progress, which a change to the draft\n * is built on. Null when there is none, or the version was saved since.\n */\n draft: { nodes: NodesMap } | null\n /** Whether visitors see the document's current version: a published page, a collection template, any layout. */\n served: boolean\n /** The version a pending publish schedule will make current, if any. */\n scheduledVersionId: string | null\n /** What this job already wrote, when a run of it got that far. */\n written: { versionId: string; placement: AiEditPlacement } | null\n}\n\nexport interface AiEditTargetRefusal {\n status: 400 | 404\n error: string\n}\n\nconst text = (value: unknown): string => (typeof value === 'string' ? value : '')\n\n/** Whether visitors see a page's current version: it is routed, or it renders a collection's entries. */\nfunction screenServed(screen: FirebaseFirestore.DocumentSnapshot, host: FirebaseFirestore.DocumentSnapshot): boolean {\n if (screen.get('kind') === SCREEN_KIND_TEMPLATE) return true\n const routing = host.get('screens') as Record<string, unknown> | null | undefined\n return typeof routing?.[screen.id] === 'string'\n}\n\nfunction pendingScheduleVersion(doc: FirebaseFirestore.DocumentSnapshot): string | null {\n const schedule = doc.get('publishSchedule') as Record<string, unknown> | null | undefined\n if (!schedule || schedule['status'] !== 'pending' || schedule['action'] === 'unpublish') return null\n return text(schedule['versionId']) || null\n}\n\n/**\n * A version's working draft as the Besigner would offer it: a tree, taken\n * against the version as it is stored now. A draft the version has been\n * saved past is not offered there (it would undo that save), so a change is\n * not built on it here either. `aiEditJobId` names the job that wrote it.\n */\nfunction usableDraft(\n draft: FirebaseFirestore.DocumentSnapshot,\n version: FirebaseFirestore.DocumentSnapshot,\n): { nodes: NodesMap; aiEditJobId: string | null } | null {\n if (!draft.exists) return null\n const nodes = decodeStoredNodes<NodesMap>(draft.get('nodes'))\n if (!nodes || !Object.keys(nodes).length) return null\n const baseStamp = typeof draft.get('baseStamp') === 'string' ? (draft.get('baseStamp') as string) : null\n if (hasConcurrentWrite(baseStamp, versionStamp(version.get('updatedAt')))) return null\n return { nodes, aiEditJobId: text(draft.get('aiEditJobId')) || null }\n}\n\n/**\n * A version's own tree as the Besigner opens it (AGL-4235): the stored\n * `nodes` with the version's layout style overrides parked on the root by the\n * editor's own `injectLayoutStyleOverrides`. A draft the editor saves carries\n * them there, so a draft built on this tree does too, and publishing it — from\n * the editor or over the API — keeps them rather than clearing them. Null\n * without a tree.\n */\nexport function aiEditSavedTree(version: FirebaseFirestore.DocumentSnapshot): NodesMap | null {\n const nodes = decodeStoredNodes<NodesMap>(version.get('nodes'))\n return nodes ? (injectLayoutStyleOverrides(nodes, version.get('layoutStyleOverrides')) as NodesMap) : null\n}\n\n/** The tree a change is built on, as it is stored now (AGL-4235). */\nexport interface AiEditBase {\n /**\n * `draft` for the version's working draft, when the Besigner would still\n * offer it; `saved` for the version's own tree otherwise.\n */\n from: 'draft' | 'saved'\n /**\n * The tree, as the Besigner would hold it: a draft's as its author left it,\n * the saved version's with its layout style overrides on the root.\n */\n nodes: NodesMap\n /**\n * The `nodes` field as stored, exactly as read: what a revision of the tree\n * is read off, so parking the overrides on the root never moves it.\n */\n stored: unknown\n /** What stamped the draft, when a write did (`aiEditJobId`); null for a saved tree. */\n stampedBy: string | null\n}\n\n/**\n * The tree a change to a version is built on — the one rule, for the edit job,\n * its write and a reader that shows a page as the next change will find it:\n * the version's working draft when the Besigner would still offer it, so an\n * author's work in progress is never thrown away; otherwise the version's own\n * tree. `useDraft: false` is a change that lands somewhere other than the\n * draft, built on the version alone. Null when neither has a tree.\n */\nexport function aiEditBase(\n draft: FirebaseFirestore.DocumentSnapshot,\n version: FirebaseFirestore.DocumentSnapshot,\n options: { useDraft?: boolean } = {},\n): AiEditBase | null {\n const usable = options.useDraft === false ? null : usableDraft(draft, version)\n if (usable) return { from: 'draft', nodes: usable.nodes, stored: draft.get('nodes'), stampedBy: usable.aiEditJobId }\n // A usable draft's root says what its author meant, overrides or none, so\n // only the saved tree gets them, as the editor gives them when it opens it.\n const nodes = aiEditSavedTree(version)\n return nodes ? { from: 'saved', nodes, stored: version.get('nodes'), stampedBy: null } : null\n}\n\n/** A version's working draft document: the Besigner's, at the core's one address. */\nexport function draftRef(versions: FirebaseFirestore.CollectionReference, versionId: string): FirebaseFirestore.DocumentReference {\n return versions.doc(versionId).collection(VERSION_DRAFT_COLLECTION).doc(VERSION_DRAFT_DOC_ID)\n}\n\n/**\n * The document an edit job changes, on the job's own site: the page or\n * layout named, not deleted, not an email design, and the version it starts\n * from with a document in it. A refusal names what is wrong.\n */\nexport async function readAiEditTarget(\n firestore: Firestore,\n input: {\n orgId: string\n hostId: string\n inputs: AiEditJobInputs\n /** The job's own version id, to find what a run of it wrote; `null` at the door, before there is one. */\n jobId: string | null\n },\n): Promise<AiEditTargetRead | AiEditTargetRefusal> {\n const hostRef = firestore.collection('hosts').doc(input.hostId)\n const host = await hostRef.get()\n if (!host.exists || host.get('orgId') !== input.orgId) return { status: 404, error: AI_EDIT_NO_SITE_COPY }\n const kinds: AiEditTargetKind[] = input.inputs.targetKind ? [input.inputs.targetKind] : ['screen', 'layout']\n for (const kind of kinds) {\n const docRef = hostRef.collection(COLLECTIONS[kind]).doc(input.inputs.target)\n const doc = await docRef.get()\n if (!doc.exists) continue\n if (doc.get('deletedAt') != null) return { status: 404, error: AI_EDIT_GONE_COPY }\n if (kind === 'screen' && doc.get('kind') === 'email') return { status: 400, error: AI_EDIT_EMAIL_COPY }\n const pointerVersionId = text(doc.get('versionId')) || null\n const versions = docRef.collection('versions')\n const hostSubdomain = text(host.get('subdomain')) || null\n const name = text(doc.get('displayName')) || (kind === 'screen' ? 'Page' : 'Layout')\n // A run of this job that got as far as its write.\n const own = input.jobId ? await versions.doc(input.jobId).get() : null\n const sourceVersionId = input.inputs.versionId ?? pointerVersionId\n const base = {\n kind,\n id: doc.id,\n name,\n hostSubdomain,\n pointerVersionId,\n served: kind === 'layout' || screenServed(doc, host),\n scheduledVersionId: pendingScheduleVersion(doc),\n }\n if (own?.exists && input.jobId) {\n const placement: AiEditPlacement = pointerVersionId === input.jobId ? 'new-current' : 'new-beside'\n return { ...base, sourceVersionId: sourceVersionId ?? input.jobId, nodes: {}, draft: null, written: { versionId: input.jobId, placement } }\n }\n if (!sourceVersionId) return { status: 404, error: AI_EDIT_VERSION_GONE_COPY }\n const [source, draftDoc] = await Promise.all([versions.doc(sourceVersionId).get(), draftRef(versions, sourceVersionId).get()])\n if (!source.exists) return { status: 404, error: AI_EDIT_VERSION_GONE_COPY }\n if (input.jobId && source.get('aiEditJobId') === input.jobId) {\n return { ...base, sourceVersionId, nodes: {}, draft: null, written: { versionId: sourceVersionId, placement: 'in-place' } }\n }\n const draft = usableDraft(draftDoc, source)\n if (input.jobId && draft?.aiEditJobId === input.jobId) {\n return { ...base, sourceVersionId, nodes: {}, draft: null, written: { versionId: sourceVersionId, placement: 'draft' } }\n }\n // The saved tree as the Besigner opens it, the page's layout style\n // overrides on its root (see `aiEditSavedTree`).\n const nodes = aiEditSavedTree(source)\n if (!nodes || !Object.keys(nodes).length) return { status: 400, error: AI_EDIT_NO_NODES_COPY }\n return { ...base, sourceVersionId, nodes, draft: draft ? { nodes: draft.nodes } : null, written: null }\n }\n return { status: 404, error: AI_EDIT_GONE_COPY }\n}\n\n/**\n * Where a change may land (see the module head), or `refused` when the only\n * place is a version visitors see and the plan keeps no version history.\n */\nexport function aiEditPlacement(input: {\n versioning: boolean\n served: boolean\n sourceIsPointer: boolean\n sourceScheduled: boolean\n}): AiEditPlacement | 'refused' {\n if (input.versioning) return !input.served && input.sourceIsPointer ? 'new-current' : 'new-beside'\n const seen = input.sourceScheduled || (input.sourceIsPointer && input.served)\n return seen ? 'refused' : 'in-place'\n}\n\n/**\n * Where an edit job's change lands (AGL-4116): the version's working draft,\n * unless the request asked for a new version and the plan keeps version\n * history — then where {@link aiEditPlacement} puts a new one. Never refused:\n * a draft is on every plan, and no visitor sees it.\n */\nexport function aiEditJobPlacement(input: {\n newVersion: boolean\n versioning: boolean\n served: boolean\n sourceIsPointer: boolean\n sourceScheduled: boolean\n}): AiEditPlacement {\n if (!input.newVersion || !input.versioning) return 'draft'\n const placed = aiEditPlacement(input)\n return placed === 'refused' ? 'draft' : placed\n}\n\n// ── Writing it ────────────────────────────────────────────────────────────\n\n/** What a proposal built from the stored tree sees of the document, besides the tree (AGL-4235). */\nexport interface AiEditWriteBase extends AiEditBase {\n /** The document's current version, as the transaction reads it. */\n pointerVersionId: string | null\n}\n\nexport interface AiEditWriteInput<R = never> {\n hostId: string\n kind: AiEditTargetKind\n id: string\n sourceVersionId: string\n /**\n * A fresh id for this write: the new version's id, which is the job's, and\n * the stamp a draft it writes carries, which is how a write asked again\n * finds what it wrote. An API edit hands its own (AGL-4235).\n */\n jobVersionId: string\n versioning: boolean\n /** The request asked for a new version (see {@link aiEditJobPlacement}). */\n newVersion: boolean\n /**\n * The change. A model's proposal is checked before the write against the\n * tree the model was shown, and the canvas's guards refuse it whole if an\n * element changed since. A caller that holds no tree yet (AGL-4235) hands a\n * function instead, given the tree exactly as this transaction reads it,\n * and validates and builds the change on that, so what it checked and what\n * is written are one tree. It refuses with `{ refused }`, and nothing is\n * written.\n */\n proposal: AssistEditProposal | ((base: AiEditWriteBase) => AssistEditProposal | { refused: R })\n /** Whether the page's search fields may be written: a page no visitor reaches. */\n writeSeo: boolean\n versionName: string\n /** Who the write is for: a member's uid, or a stable id for a writer that is no person. */\n uid: string\n /**\n * Who the write is for in words, written on a draft as `updatedByLabel`\n * when given: an API key's or a connected app's name (AGL-4235). The job\n * writes none.\n */\n updatedByLabel?: string\n /**\n * Refuse a tree larger than this many bytes, measured as the save measures\n * it (`measureNodeMap`), and write nothing. Absent: not measured.\n */\n maxNodeBytes?: number\n /** The job the member started, stamped as `aiJobId` on a new version. */\n aiJobId: string\n now: Date\n}\n\nexport type AiEditWrite<R = never> =\n | {\n ok: true\n versionId: string\n placement: AiEditPlacement\n seoWritten: boolean\n /**\n * What this call wrote, when it wrote (not a run asked again): the\n * stored tree's bytes, and the ids the canvas gave each insert's elements.\n */\n written?: { stored: Uint8Array; inserted: AssistEditInserted[] }\n }\n | {\n ok: false\n error: string\n /** The caller's own refusal, from a proposal built on the stored tree. */\n refused?: R\n /** The tree would pass `maxNodeBytes`: its size. */\n tooLarge?: { bytes: number }\n }\n\n/**\n * The change written, in one transaction that reads the document as it is\n * stored NOW — a member may have saved, published or changed plan's history\n * since the read — decides where it lands again on that, and applies the\n * proposal to the stored nodes through the canvas's guards. An element that\n * changed since the model saw it refuses the whole change, as the editor does.\n */\nexport async function writeAiEdit<R = never>(firestore: Firestore, input: AiEditWriteInput<R>): Promise<AiEditWrite<R>> {\n const hostRef = firestore.collection('hosts').doc(input.hostId)\n const docRef = hostRef.collection(COLLECTIONS[input.kind]).doc(input.id)\n const versions = docRef.collection('versions')\n const sourceRef = versions.doc(input.sourceVersionId)\n const newRef = versions.doc(input.jobVersionId)\n const sourceDraftRef = draftRef(versions, input.sourceVersionId)\n return firestore.runTransaction(async (tx): Promise<AiEditWrite<R>> => {\n const [host, doc, source, already, draftDoc] = await Promise.all([\n tx.get(hostRef),\n tx.get(docRef),\n tx.get(sourceRef),\n tx.get(newRef),\n tx.get(sourceDraftRef),\n ])\n const pointer = text(doc.get('versionId')) || null\n if (already.exists) {\n return { ok: true, versionId: input.jobVersionId, placement: pointer === input.jobVersionId ? 'new-current' : 'new-beside', seoWritten: false }\n }\n if (!doc.exists || doc.get('deletedAt') != null) return { ok: false, error: AI_EDIT_GONE_COPY }\n if (!source.exists) return { ok: false, error: AI_EDIT_VERSION_GONE_COPY }\n const served = input.kind === 'layout' || screenServed(doc, host)\n const placement = aiEditJobPlacement({\n newVersion: input.newVersion,\n versioning: input.versioning,\n served,\n sourceIsPointer: pointer === input.sourceVersionId,\n sourceScheduled: pendingScheduleVersion(doc) === input.sourceVersionId,\n })\n // Read again here, as the version is: an author who saved their draft,\n // or published it, since the read is what the change is built on now.\n const base = aiEditBase(draftDoc, source, { useDraft: placement === 'draft' })\n if (base?.from === 'draft' && base.stampedBy === input.jobVersionId) {\n return { ok: true, versionId: input.sourceVersionId, placement, seoWritten: false }\n }\n if (!base) return { ok: false, error: AI_EDIT_NO_NODES_COPY }\n const nodes = base.nodes\n const built = typeof input.proposal === 'function' ? input.proposal({ ...base, pointerVersionId: pointer }) : input.proposal\n if ('refused' in built) return { ok: false, error: AI_EDIT_REFUSED_COPY, refused: built.refused }\n const versionId = placement === 'draft' ? input.sourceVersionId : input.jobVersionId\n const seo: Partial<Record<(typeof SCREEN_SEO_TEXT_FIELDS)[number], string>> = {}\n const writeSeo = input.writeSeo && input.kind === 'screen' && !served\n const proposal: AssistEditProposal = {\n ...built,\n ops: writeSeo ? built.ops : built.ops.filter((op) => op.op !== 'setSeo'),\n target: { ...built.target, versionId },\n }\n const applied = aiApplyEditToNodes(nodes, proposal, writeSeo ? seo : undefined)\n if (applied.ok === false) return { ok: false, error: applied.reason === 'stale' ? AI_EDIT_STALE_COPY : AI_EDIT_REFUSED_COPY }\n if (input.maxNodeBytes !== undefined) {\n const { bytes } = measureNodeMap(applied.nodes)\n if (bytes > input.maxNodeBytes) return { ok: false, error: AI_EDIT_TOO_LARGE_COPY, tooLarge: { bytes } }\n }\n // A draft keeps the overrides on its root, as the editor's own draft\n // does; a version stores them beside its tree, never in it, as the\n // editor's save lifts them out (the copy below keeps the field).\n const packed = encodeStoredNodes(placement === 'draft' ? applied.nodes : extractLayoutStyleOverrides(applied.nodes).nodes)\n if (!packed) return { ok: false, error: AI_EDIT_NO_NODES_COPY }\n const stored = Buffer.from(packed)\n const docPatch: Record<string, unknown> = {}\n if (placement === 'draft') {\n // The whole working tree, as the Besigner writes a draft, taken against\n // the version as stored so the Besigner offers it with Open draft.\n tx.set(sourceDraftRef, {\n nodes: stored,\n baseStamp: versionStamp(source.get('updatedAt')),\n updatedByUid: input.uid,\n updatedByEmail: null,\n ...(input.updatedByLabel ? { updatedByLabel: input.updatedByLabel } : {}),\n updatedAt: input.now,\n aiEditJobId: input.jobVersionId,\n })\n } else {\n // A copy of the version it started from — its layout binding, its\n // declared properties, everything the editor stored — with the changed\n // tree, as the versions route copies one.\n const copy = { ...(source.data() as Record<string, unknown>) }\n delete copy['aiEditJobId']\n tx.create(newRef, {\n ...copy,\n nodes: stored,\n displayName: input.versionName,\n createdAt: input.now,\n updatedAt: input.now,\n createdBy: input.uid,\n aiJobId: input.aiJobId,\n })\n if (placement === 'new-current') docPatch['versionId'] = input.jobVersionId\n }\n for (const [field, value] of Object.entries(seo)) {\n if (value) docPatch[`seo.${field}`] = value\n }\n if (Object.keys(docPatch).length) tx.update(docRef, { ...docPatch, updatedAt: input.now })\n return {\n ok: true,\n versionId,\n placement,\n seoWritten: Object.keys(seo).length > 0,\n written: { stored, inserted: applied.inserted },\n }\n })\n}\n\n// ── The runner ────────────────────────────────────────────────────────────\n\nexport interface AiJobEditStepDeps {\n readTarget?: typeof readAiEditTarget\n writeEdit?: typeof writeAiEdit\n readDatasets?: typeof readAiSiteDatasets\n clearMirror?: typeof clearAiEditMirror\n}\n\n/**\n * Clears the co-edit mirror of the version whose draft a job just wrote\n * (AGL-4116), as the Besigner's own Save draft does.\n *\n * The mirror holds unsaved canvas work and replays everything newer than the\n * version's last save to whoever opens it. A draft write does not move the\n * version's save, so without this the canvas of someone who had opened the\n * older draft replays over the change the job just saved, and a room with\n * replayed work offers no draft at all: the newer draft can only be reached by\n * a Discard that deletes it. Best effort: a mirror that cannot be cleared\n * leaves the draft saved, and the job reports what it wrote.\n */\nexport async function clearAiEditMirror(input: {\n orgId: string\n hostId: string\n kind: AiEditTargetKind\n id: string\n versionId: string\n}): Promise<void> {\n await firebaseAdmin\n .database()\n .ref(coeditMirrorRoomPath({ orgId: input.orgId, hostId: input.hostId, docType: input.kind, docId: input.id, versionId: input.versionId }))\n .remove()\n}\n\n/** What an edit wrote, as the job's output: a link into the Besigner on the version written. */\nexport function aiEditOutput(\n read: Pick<AiEditTargetRead, 'kind' | 'id' | 'name' | 'hostSubdomain'>,\n hostId: string,\n written: { versionId: string; placement: AiEditPlacement },\n leftOut: readonly string[],\n options: { versionsUnavailable?: boolean } = {},\n): AiJobOutput {\n return {\n resource: read.kind,\n id: read.id,\n versionId: written.versionId,\n hostId,\n hostSubdomain: read.hostSubdomain,\n label: read.name,\n ...(written.placement === 'draft' ? { inDraft: true as const } : {}),\n note: aiEditOutputNote({\n kind: read.kind,\n placement: written.placement,\n leftOut,\n ...(options.versionsUnavailable ? { versionsUnavailable: true } : {}),\n }),\n }\n}\n\n/** The new version's id: the job's own, which a build's unit takes from its plan item. */\nexport function aiEditVersionId(job: Pick<AiJob, '$id'>): string {\n return job.$id.slice(0, 64)\n}\n\n/**\n * The ops a job may save, and why it left the rest out: never a component\n * save, and a page's search fields only where no visitor reaches the page.\n */\nexport function aiEditJobOps(\n ops: readonly AssistEditOp[],\n options: { seo: boolean },\n): { ops: AssistEditOp[]; leftOut: string[] } {\n const kept: AssistEditOp[] = []\n const leftOut = new Set<string>()\n for (const op of ops) {\n if (op.op === 'saveAsComponent') leftOut.add(AI_EDIT_COMPONENT_LEFT_OUT)\n else if (op.op === 'setSeo' && !options.seo) leftOut.add(AI_EDIT_SEO_LEFT_OUT)\n else kept.push(op)\n }\n return { ops: kept, leftOut: [...leftOut] }\n}\n\nexport function createAiJobEditStep(deps: AiJobEditStepDeps = {}): AiJobStepRunner {\n const readTarget = deps.readTarget ?? readAiEditTarget\n const writeEdit = deps.writeEdit ?? writeAiEdit\n const readDatasets = deps.readDatasets ?? readAiSiteDatasets\n const clearMirror = deps.clearMirror ?? clearAiEditMirror\n return async ({ job, now, signal, firestore, org, modelFor }): Promise<AiJobStepOutcome> => {\n const model = modelFor?.('job.edit') ?? aiJobEditModel()\n const unspent = (failure: string): AiJobStepOutcome => ({ ...aiUnspentOutcome(model), failure })\n const inputs = parseAiEditJobInputs(job.inputs)\n if (typeof inputs === 'string') return unspent(inputs)\n const hostId = job.hostId\n if (!hostId) return unspent(AI_EDIT_NO_SITE_COPY)\n const read = await readTarget(firestore, { orgId: job.orgId, hostId, inputs, jobId: aiEditVersionId(job) })\n if ('error' in read) return unspent(read.error)\n if (read.written) return aiUnspentOutcome(model, { outputs: [aiEditOutput(read, hostId, read.written, [])] })\n\n const orgData = org ?? ((await firestore.collection('orgs').doc(job.orgId).get()).data() ?? null)\n const versioning = checkEntitlement(orgData as never, 'versioning')\n const placement = aiEditJobPlacement({\n newVersion: inputs.newVersion,\n versioning,\n served: read.served,\n sourceIsPointer: read.sourceVersionId === read.pointerVersionId,\n sourceScheduled: read.scheduledVersionId === read.sourceVersionId,\n })\n // A change to the draft is made on the draft the author already has.\n const outline = aiEditJobOutline(placement === 'draft' && read.draft ? read.draft.nodes : read.nodes)\n const context = outline ? parseAssistEditContext(outline, { whole: true }) : null\n if (!context) return unspent(AI_EDIT_NO_NODES_COPY)\n const target: AssistEditTarget = {\n kind: read.kind,\n documentId: read.id,\n versionId: placement === 'draft' ? read.sourceVersionId : aiEditVersionId(job),\n hostId,\n }\n\n // The site's datasets, so a request to show records binds a repeat to a\n // real one instead of writing tokens nothing fills (AGL-3616).\n const datasets = aiEditDatasetScope(await readDatasets(job.orgId, hostId), read)\n\n const generation = await runValidatedGeneration(\n 'edit',\n aiJobEditGeneration({ brief: job.brief, context, target, model, ...datasets, ...(signal ? { signal } : {}) }),\n )\n const spent = { ...aiGenerationSpent(generation), ...(generation.effort ? { effort: generation.effort } : {}) }\n if (generation.status === 'refused') return { ...spent, refused: true }\n // An answer its re-ask still could not make whole keeps the changes that\n // survived, as the chat door's card does, and says what it left out; one\n // with none, or one that broke a numbered rule, is nothing to save.\n let proposal: AssistEditProposal | null = generation.status === 'ok' ? generation.value : null\n const refused = generation.status === 'needs_input' ? generation.answer : null\n if (!proposal && refused) {\n const salvaged = validateStreamedGeneration('edit', {\n answer: refused,\n check: (answer) => checkAssistEditAnswer(answer, { context, target, ...datasets }),\n })\n proposal = salvaged.status === 'ok' ? salvaged.value : null\n }\n if (!proposal) return { ...spent, failure: AI_EDIT_NOTHING_COPY }\n\n const seo = read.kind === 'screen' && !read.served\n const kept = aiEditJobOps(proposal.ops, { seo })\n const leftOut = [...proposal.dropped, ...kept.leftOut]\n if (!kept.ops.length) {\n return { ...spent, failure: `Nothing was saved. Left out: ${leftOut.join('; ') || 'every change'}.` }\n }\n const write = await writeEdit(firestore, {\n hostId,\n kind: read.kind,\n id: read.id,\n sourceVersionId: read.sourceVersionId,\n jobVersionId: aiEditVersionId(job),\n versioning,\n newVersion: inputs.newVersion,\n proposal: { ...proposal, ops: kept.ops },\n writeSeo: seo,\n versionName: aiEditVersionName(proposal.summary),\n uid: job.createdBy,\n aiJobId: aiOriginJobId(job),\n now,\n })\n if (write.ok === false) return { ...spent, failure: write.error }\n if (write.placement === 'draft') {\n await clearMirror({ orgId: job.orgId, hostId, kind: read.kind, id: read.id, versionId: write.versionId }).catch((error: unknown) =>\n console.warn('[ai edit] the co-edit mirror could not be cleared', { jobId: job.$id, error }),\n )\n }\n const versionsUnavailable = inputs.newVersion && !versioning\n return { ...spent, outputs: [aiEditOutput(read, hostId, write, leftOut, { versionsUnavailable })] }\n }\n}\n\nexport const runAiJobEditStep = createAiJobEditStep()\n\n// ── Admission ─────────────────────────────────────────────────────────────\n\nexport interface AiEditJobAdmissionDeps {\n readTarget?: typeof readAiEditTarget\n ownerOf?: typeof resolveOrgIdForHost\n}\n\n/**\n * An edit job is admitted for a page or layout of a site of its own org that\n * has a version to start from. Every plan has somewhere to put the change\n * that no visitor sees — the version's draft — so no plan is refused.\n */\nexport function createAiEditJobAdmission(deps: AiEditJobAdmissionDeps = {}): AiJobAdmission {\n const readTarget = deps.readTarget ?? readAiEditTarget\n const ownerOf = deps.ownerOf ?? resolveOrgIdForHost\n return async (context): Promise<AiJobAdmissionRefusal | null> => {\n const inputs = parseAiEditJobInputs(context.inputs)\n if (typeof inputs === 'string') return { status: 400, error: inputs }\n if (!context.hostId) return { status: 400, error: AI_EDIT_NO_SITE_COPY }\n const owner = await ownerOf(context.hostId)\n if (!owner || owner !== context.orgId) return { status: 404, error: 'Unknown site' }\n // A job asked about at its door has no run to find yet.\n const read = await readTarget(context.firestore, { orgId: context.orgId, hostId: context.hostId, inputs, jobId: null })\n // Every plan has somewhere to put the change: the page's draft (AGL-4116).\n return 'error' in read ? read : null\n }\n}\n\nexport const aiEditJobAdmission = createAiEditJobAdmission()\n\n/** Registers the edit step and the check an edit job passes before it is created or resumed. */\nexport function registerAiEditJob(): void {\n registerAiJobStep('edit', runAiJobEditStep, { minimumMs: AI_JOB_EDIT_STEP_MINIMUM_MS })\n registerAiJobAdmission('edit', aiEditJobAdmission)\n}\n"],"names":["checkEntitlement","SCREEN_KIND_TEMPLATE","screenSeoStageKey","SCREEN_SEO_TEXT_FIELDS","hasConcurrentWrite","versionStamp","extractLayoutStyleOverrides","injectLayoutStyleOverrides","decodeStoredNodes","encodeStoredNodes","coeditMirrorRoomPath","VERSION_DRAFT_COLLECTION","VERSION_DRAFT_DOC_ID","CanvasManager","FEATURE_FLAG","firebaseAdmin","resolveOrgIdForHost","measureNodeMap","applyAssistEdit","AI_EDIT_COMPONENT_LEFT_OUT","AI_EDIT_EMAIL_COPY","AI_EDIT_GONE_COPY","AI_EDIT_NO_NODES_COPY","AI_EDIT_NO_SITE_COPY","AI_EDIT_NOTHING_COPY","AI_EDIT_REFUSED_COPY","AI_EDIT_SEO_LEFT_OUT","AI_EDIT_STALE_COPY","AI_EDIT_TOO_LARGE_COPY","AI_EDIT_VERSION_GONE_COPY","aiEditJobOutline","aiEditOutputNote","aiEditVersionName","parseAiEditJobInputs","ASSIST_EDIT_TOOL_NAME","AI_STEP_TIERS","AI_ROUTING_TABLE","aiModelForStep","runValidatedGeneration","validateStreamedGeneration","AI_PALETTE","readAiSiteDatasets","assistEditTool","checkAssistEditAnswer","editCanvasBlock","editDatasetsBlock","editSelectionBlock","parseAssistEditContext","registerAiJobAdmission","aiJobStepBudget","aiOriginJobId","aiGenerationSpent","aiUnspentOutcome","AI_JOB_BRIEF_MAX_CHARS","registerAiJobStep","AI_EDIT_READS_MS","AI_JOB_EDIT_STEP_BUDGET","tier","maxTokens","lookups","ownReadsMs","AI_JOB_EDIT_STEP_MINIMUM_MS","minimumMs","aiJobEditModel","AI_JOB_EDIT_RULES","text","join","aiJobEditInstructions","kind","cacheBreakpoint","aiJobEditPrompt","input","datasets","context","job","brief","slice","aiEditDatasetScope","read","record","find","dataset","recordScreenId","id","undefined","map","name","fields","fieldIds","imageField","recordDatasetId","aiJobEditGeneration","request","row","target","step","model","instructions","messages","role","content","tool","thinking","effort","signal","check","answer","AI_EDIT_CANVAS_PLATFORM","components","getSchema","componentId","entry","acceptsChildren","flags","dropping","DISABLED","getLabel","displayName","aiEditCanvas","nodes","canvas","setNodes","aiApplyEditToNodes","proposal","seo","applied","field","value","session","documentKind","documentId","versionId","isLiveVersion","ok","reason","toJSON","inserted","COLLECTIONS","screen","layout","screenServed","host","get","routing","pendingScheduleVersion","doc","schedule","usableDraft","draft","version","exists","Object","keys","length","baseStamp","aiEditJobId","aiEditSavedTree","aiEditBase","options","usable","useDraft","from","stored","stampedBy","draftRef","versions","collection","readAiEditTarget","firestore","hostRef","hostId","orgId","status","error","kinds","inputs","targetKind","docRef","pointerVersionId","hostSubdomain","own","jobId","sourceVersionId","base","served","scheduledVersionId","placement","written","source","draftDoc","Promise","all","aiEditPlacement","versioning","sourceIsPointer","seen","sourceScheduled","aiEditJobPlacement","newVersion","placed","writeAiEdit","sourceRef","newRef","jobVersionId","sourceDraftRef","runTransaction","tx","already","pointer","seoWritten","built","refused","writeSeo","ops","filter","op","maxNodeBytes","bytes","tooLarge","packed","Buffer","docPatch","set","updatedByUid","uid","updatedByEmail","updatedByLabel","updatedAt","now","copy","data","create","versionName","createdAt","createdBy","aiJobId","entries","update","clearAiEditMirror","database","ref","docType","docId","remove","aiEditOutput","leftOut","resource","label","inDraft","note","versionsUnavailable","aiEditVersionId","$id","aiEditJobOps","kept","Set","add","push","createAiJobEditStep","deps","readTarget","writeEdit","readDatasets","clearMirror","org","modelFor","unspent","failure","outputs","orgData","outline","whole","generation","spent","salvaged","dropped","write","summary","catch","console","warn","runAiJobEditStep","createAiEditJobAdmission","ownerOf","owner","aiEditJobAdmission","registerAiEditJob"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA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QAAe;QACnF,wDAAwD;QACxD,MAAM/F,OAAO,MAAMsL,WAAW3L,QAAQ+F,SAAS,EAAE;YAAEG,OAAOlG,QAAQkG,KAAK;YAAED,QAAQjG,QAAQiG,MAAM;YAAEK;YAAQM,OAAO;QAAK;QACrH,2EAA2E;QAC3E,OAAO,WAAWvG,OAAOA,OAAO;IAClC;AACF;AAEA,OAAO,MAAM+M,qBAAqBH,2BAA0B;AAE5D,8FAA8F,GAC9F,OAAO,SAASI;IACdxO,kBAAkB,QAAQmO,kBAAkB;QAAE3N,WAAWD;IAA4B;IACrFb,uBAAuB,QAAQ6O;AACjC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-job-edit-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 {\n contentEditStamp,\n parentPublishStamp,\n versionPublishStamp,\n withoutVersionPublishStamp,\n type ContentWriteActor,\n} from '@aglyn/aglyn/app-utils/content-write-stamp'\nimport { checkEntitlement } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { SCREEN_KIND_TEMPLATE } from '@aglyn/aglyn/app-utils/screen-route'\nimport { screenSeoStageKey, SCREEN_SEO_TEXT_FIELDS } from '@aglyn/aglyn/app-utils/screen-seo-fields'\nimport { hasConcurrentWrite, versionStamp } from '@aglyn/aglyn/app-utils/guarded-version-save'\nimport { extractLayoutStyleOverrides, injectLayoutStyleOverrides } from '@aglyn/aglyn/app-utils/layout-style-overrides'\nimport { decodeStoredNodes, encodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { coeditMirrorRoomPath, VERSION_DRAFT_COLLECTION, VERSION_DRAFT_DOC_ID } from '@aglyn/aglyn/app-utils/version-draft'\nimport { CanvasManager } from '@aglyn/aglyn/canvas-manager/canvas-manager'\nimport { FEATURE_FLAG } from '@aglyn/aglyn/foundation/constants/shared'\nimport type { EditorSession } from '@aglyn/aglyn/plugin-manager/editor-sessions'\nimport type { NodesMap } from '@aglyn/aglyn/types/nodes'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { resolveOrgIdForHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { measureNodeMap } from '@aglyn/aglyn/app-utils/measure-node-map'\nimport { applyAssistEdit, type AssistEditInserted } from '../components/assist-edit-canvas'\nimport {\n AI_EDIT_COMPONENT_LEFT_OUT,\n AI_EDIT_EMAIL_COPY,\n AI_EDIT_GONE_COPY,\n AI_EDIT_NO_NODES_COPY,\n AI_EDIT_NO_SITE_COPY,\n AI_EDIT_NOTHING_COPY,\n AI_EDIT_REFUSED_COPY,\n AI_EDIT_SEO_LEFT_OUT,\n AI_EDIT_STALE_COPY,\n AI_EDIT_TOO_LARGE_COPY,\n AI_EDIT_VERSION_GONE_COPY,\n aiEditJobOutline,\n aiEditOutputNote,\n aiEditVersionName,\n parseAiEditJobInputs,\n type AiEditJobInputs,\n type AiEditPlacement,\n type AiEditTargetKind,\n} from '../model/ai-edit-job'\nimport type { AiJob, AiJobOutput } from '../model/ai-jobs.types'\nimport {\n ASSIST_EDIT_TOOL_NAME,\n type AssistEditCanvasContext,\n type AssistEditOp,\n type AssistEditProposal,\n type AssistEditTarget,\n} from '../model/assist-edit'\nimport { AI_STEP_TIERS } from '../providers/catalog'\nimport { AI_ROUTING_TABLE, aiModelForStep } from '../providers/routing'\nimport {\n runValidatedGeneration,\n validateStreamedGeneration,\n type AiCustomGenerationInput,\n} from '../runtime/ai-doctrine'\nimport { AI_PALETTE } from '../runtime/ai-palette.generated'\nimport type { AiSystemBlock } from '../runtime/ai-runtime'\nimport { readAiSiteDatasets } from '../runtime/site-inventory'\nimport {\n assistEditTool,\n checkAssistEditAnswer,\n editCanvasBlock,\n editDatasetsBlock,\n editSelectionBlock,\n parseAssistEditContext,\n type AssistEditDataset,\n type AssistEditDatasetScope,\n} from '../server/assist-edit'\nimport { registerAiJobAdmission, type AiJobAdmission, type AiJobAdmissionRefusal } from './ai-job-admission'\nimport { aiJobStepBudget } from './ai-job-budget'\nimport { aiOriginJobId } from './ai-job-draft-ids'\nimport { aiGenerationSpent, aiUnspentOutcome } from './ai-job-generation'\nimport { AI_JOB_BRIEF_MAX_CHARS, type AiJobStepOutcome, type AiJobStepRunner } from './ai-job-text-step'\nimport { registerAiJobStep } from './ai-jobs'\n\n/**\n * The `edit` step (AGL-3616): a change to a page or a layout the site already\n * has, from a description, made on the server with no editor open.\n *\n * It is the Assist edit rung, run as a job. The model is shown the stored\n * document as the rung's outline and proposes through the rung's own tool;\n * its answer is held to the rung's closed world and palette validators\n * (`checkAssistEditAnswer`) and re-asked once, naming what was left out; and\n * what survives lands through the canvas's own guarded mutators\n * (`applyAssistEdit`), on a `CanvasManager` built headless from the stored\n * nodes, inside the transaction that writes it.\n *\n * ── Where the change lands, decided before anything is spent ────────────\n *\n * Never on a version a visitor sees. By default, on every plan, in the\n * WORKING DRAFT of the version it started from (AGL-4116): the one document\n * the Besigner saves to as an author works and offers with Open draft, which\n * publishing moves into the version. The change is built on the draft the\n * author already has, when the Besigner would still offer it, so their work\n * in progress is never thrown away; otherwise on the version's own tree.\n *\n * Only when the request asks for a new version, and the plan keeps version\n * history, a NEW version beside the one it started from — a copy of that\n * version's stored fields with the changed nodes — which becomes the page's\n * current version only when the page is not published; a published page's\n * current version, and a layout's, never move. Asked for without version\n * history, the change goes into the draft and the output says why.\n *\n * ── What a job cannot do that the editor can ────────────────────────────\n *\n * The rung's chat door never offers saving part of a page as a reusable\n * component, and neither does this. A page's search title and description\n * live on the page itself, not on a version, so they are written only for a\n * page that is not published; on a published page they are left out, and the\n * output's note says so, as it says every change it left out.\n *\n * ── One version per job ──────────────────────────────────────────────────\n *\n * The new version is named by the job's id — a build's unit is named by its\n * plan item's id — so a run asked again finds what it wrote and spends\n * nothing. A draft the job writes is stamped with the job's id for the same\n * reason.\n */\n\n/** The longest the step may take reading the page and writing it. */\nexport const AI_EDIT_READS_MS = 2_000\n\n/** The step's time: its answer and its re-ask at the `job.edit` ceiling, with its own reads. */\nexport const AI_JOB_EDIT_STEP_BUDGET = aiJobStepBudget({\n tier: AI_STEP_TIERS['job.edit'],\n maxTokens: AI_ROUTING_TABLE['job.edit'].maxTokens,\n lookups: 0,\n ownReadsMs: AI_EDIT_READS_MS,\n})\n\nexport const AI_JOB_EDIT_STEP_MINIMUM_MS = AI_JOB_EDIT_STEP_BUDGET.minimumMs\n\nexport function aiJobEditModel(): string {\n return aiModelForStep('job.edit')\n}\n\n/**\n * The job's own rules, byte-identical on every request, ahead of the rung's\n * protocol and catalog for the document's kind, which carries the breakpoint:\n * both are the same for every site, so a kind's whole prefix caches once.\n */\nexport const AI_JOB_EDIT_RULES: AiSystemBlock = {\n text: [\n 'You change a page or a layout the person already has, as a job that runs on its own. No editor is open, nothing is selected, and nobody can answer a question before you finish.',\n `- Make exactly the change the request asks for, and keep everything else as it is: other elements, their text, their styles and their order. Never rewrite, restyle, move or remove what the request does not ask about, beyond what making that change needs.`,\n '- Find the elements the request means in the outline of the whole document the request carries, by what they say, what they are and where they sit on the page. Name only ids that outline lists.',\n `- If the outline does not show an element the request is about, change nothing for that part: never guess at an element.`,\n `- Call ${ASSIST_EDIT_TOOL_NAME} exactly once, with every operation. Its summary is one short line saying what changed, in the language of the request; it names the version the change is saved in.`,\n \"- Fill in a page's search title or description only when the request asks for it.\",\n '- What you change is saved where no visitor sees it until the person publishes it, so never say the site or the page has changed.',\n '- The protocol below was written for Assist’s chat. In this job there is no user to ask or to press Apply, and no selection: what it says about those does not apply. Everything else in it — the operations, their fields, the elements and the style tokens — does.',\n ].join('\\n'),\n}\n\n/** The system blocks for one kind of document. */\nexport function aiJobEditInstructions(kind: AiEditTargetKind): AiSystemBlock[] {\n return [AI_JOB_EDIT_RULES, { text: editCanvasBlock(kind), cacheBreakpoint: true }]\n}\n\n/**\n * What the change is asked from: the document's outline, the site's datasets\n * an element may show the records of (AGL-3616), then the request.\n */\nexport function aiJobEditPrompt(input: {\n brief: string\n context: AssistEditCanvasContext\n datasets?: readonly AssistEditDataset[]\n}): string {\n const datasets = editDatasetsBlock(input.datasets ?? [])\n return [\n editSelectionBlock(input.context, { job: true }),\n ...(datasets ? ['', datasets] : []),\n '',\n `Request: ${input.brief.slice(0, AI_JOB_BRIEF_MAX_CHARS)}`,\n ].join('\\n')\n}\n\n/**\n * The datasets an edit to this document knows (AGL-3616): every one the site\n * holds, and the one whose record page the document is, if it is one.\n */\nexport function aiEditDatasetScope(\n datasets: ReadonlyArray<AssistEditDataset & { recordScreenId?: string }>,\n read: Pick<AiEditTargetRead, 'kind' | 'id'>,\n): Required<AssistEditDatasetScope> {\n const record = read.kind === 'screen' ? datasets.find((dataset) => dataset.recordScreenId === read.id) : undefined\n return {\n datasets: datasets.map(({ id, name, fields, fieldIds, imageField }) => ({\n id,\n name,\n fields,\n ...(fieldIds ? { fieldIds } : {}),\n ...(imageField ? { imageField } : {}),\n })),\n recordDatasetId: record?.id ?? null,\n }\n}\n\n/** The edit as the doctrine's loop runs it: the rung's tool, held to the rung's check. */\nexport function aiJobEditGeneration(request: {\n brief: string\n context: AssistEditCanvasContext\n target: AssistEditTarget\n model: string\n signal?: AbortSignal\n} & AssistEditDatasetScope): AiCustomGenerationInput<AssistEditProposal> {\n const row = AI_ROUTING_TABLE['job.edit']\n const kind = request.target.kind as AiEditTargetKind\n return {\n step: 'job.edit',\n model: request.model,\n instructions: aiJobEditInstructions(kind),\n messages: [{ role: 'user', content: aiJobEditPrompt(request) }],\n tool: assistEditTool(kind),\n maxTokens: AI_JOB_EDIT_STEP_BUDGET.maxTokens(request.model),\n ...(row.thinking ? { thinking: row.thinking } : {}),\n ...(row.effort ? { effort: row.effort } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n check: (answer) =>\n checkAssistEditAnswer(answer, {\n context: request.context,\n target: request.target,\n ...(request.datasets ? { datasets: request.datasets } : {}),\n ...(request.recordDatasetId ? { recordDatasetId: request.recordDatasetId } : {}),\n }),\n }\n}\n\n// ── The document, headless ────────────────────────────────────────────────\n\n/**\n * The slice of the platform a headless canvas asks: whether an element takes\n * children, answered from the AI palette the edit validator reads, so the\n * canvas refuses exactly what the validator refuses.\n */\nconst AI_EDIT_CANVAS_PLATFORM = {\n components: {\n getSchema: (componentId: string) => {\n const entry = AI_PALETTE[componentId]\n if (!entry) return undefined\n return entry.acceptsChildren ? {} : { flags: { dropping: FEATURE_FLAG.DISABLED } }\n },\n getLabel: (componentId: string) => AI_PALETTE[componentId]?.displayName ?? componentId,\n },\n}\n\n/** A canvas over a stored node map, with the editor's own guarded mutators and no editor. */\nexport function aiEditCanvas(nodes: NodesMap): CanvasManager {\n const canvas = new CanvasManager(AI_EDIT_CANVAS_PLATFORM as never)\n canvas.setNodes(nodes)\n return canvas\n}\n\n/**\n * Lands a proposal on a stored node map, as the editor lands one on its open\n * canvas: checked whole first, then one batch, all or nothing. The session is\n * the version being written, which is never one a visitor sees; a page's\n * search fields are captured into `seo` only where `seo` is given.\n */\nexport function aiApplyEditToNodes(\n nodes: NodesMap,\n proposal: AssistEditProposal,\n seo?: Partial<Record<(typeof SCREEN_SEO_TEXT_FIELDS)[number], string>>,\n): { ok: true; nodes: NodesMap; inserted: AssistEditInserted[] } | { ok: false; reason: string } {\n const canvas = aiEditCanvas(nodes)\n const fields: Record<string, (value: string) => void> = {}\n if (seo) {\n for (const field of SCREEN_SEO_TEXT_FIELDS) fields[screenSeoStageKey(field)] = (value) => (seo[field] = value)\n }\n const session: EditorSession = {\n documentKind: proposal.target.kind,\n documentId: proposal.target.documentId,\n versionId: proposal.target.versionId,\n isLiveVersion: () => false,\n ...(seo ? { fields } : {}),\n }\n const applied = applyAssistEdit(canvas, proposal, session)\n if (applied.ok === false) return { ok: false, reason: applied.reason }\n return { ok: true, nodes: canvas.toJSON().nodes as NodesMap, inserted: applied.inserted ?? [] }\n}\n\n// ── Reading the document ──────────────────────────────────────────────────\n\ntype Firestore = FirebaseFirestore.Firestore\n\nconst COLLECTIONS: Readonly<Record<AiEditTargetKind, 'screens' | 'layouts'>> = {\n screen: 'screens',\n layout: 'layouts',\n}\n\n/** The page or layout an edit job changes, as it stands before anything is spent. */\nexport interface AiEditTargetRead {\n kind: AiEditTargetKind\n id: string\n name: string\n hostSubdomain: string | null\n /** The document's current version. */\n pointerVersionId: string | null\n /** The version the change starts from. */\n sourceVersionId: string\n /** The version's own tree. */\n nodes: NodesMap\n /**\n * The version's working draft, when it has one the Besigner would still\n * offer: an author's saved work in progress, which a change to the draft\n * is built on. Null when there is none, or the version was saved since.\n */\n draft: { nodes: NodesMap } | null\n /** Whether visitors see the document's current version: a published page, a collection template, any layout. */\n served: boolean\n /** The version a pending publish schedule will make current, if any. */\n scheduledVersionId: string | null\n /** What this job already wrote, when a run of it got that far. */\n written: { versionId: string; placement: AiEditPlacement } | null\n}\n\nexport interface AiEditTargetRefusal {\n status: 400 | 404\n error: string\n}\n\nconst text = (value: unknown): string => (typeof value === 'string' ? value : '')\n\n/** Whether visitors see a page's current version: it is routed, or it renders a collection's entries. */\nfunction screenServed(screen: FirebaseFirestore.DocumentSnapshot, host: FirebaseFirestore.DocumentSnapshot): boolean {\n if (screen.get('kind') === SCREEN_KIND_TEMPLATE) return true\n const routing = host.get('screens') as Record<string, unknown> | null | undefined\n return typeof routing?.[screen.id] === 'string'\n}\n\nfunction pendingScheduleVersion(doc: FirebaseFirestore.DocumentSnapshot): string | null {\n const schedule = doc.get('publishSchedule') as Record<string, unknown> | null | undefined\n if (!schedule || schedule['status'] !== 'pending' || schedule['action'] === 'unpublish') return null\n return text(schedule['versionId']) || null\n}\n\n/**\n * A version's working draft as the Besigner would offer it: a tree, taken\n * against the version as it is stored now. A draft the version has been\n * saved past is not offered there (it would undo that save), so a change is\n * not built on it here either. `aiEditJobId` names the job that wrote it.\n */\nfunction usableDraft(\n draft: FirebaseFirestore.DocumentSnapshot,\n version: FirebaseFirestore.DocumentSnapshot,\n): { nodes: NodesMap; aiEditJobId: string | null } | null {\n if (!draft.exists) return null\n const nodes = decodeStoredNodes<NodesMap>(draft.get('nodes'))\n if (!nodes || !Object.keys(nodes).length) return null\n const baseStamp = typeof draft.get('baseStamp') === 'string' ? (draft.get('baseStamp') as string) : null\n if (hasConcurrentWrite(baseStamp, versionStamp(version.get('updatedAt')))) return null\n return { nodes, aiEditJobId: text(draft.get('aiEditJobId')) || null }\n}\n\n/**\n * A version's own tree as the Besigner opens it (AGL-4235): the stored\n * `nodes` with the version's layout style overrides parked on the root by the\n * editor's own `injectLayoutStyleOverrides`. A draft the editor saves carries\n * them there, so a draft built on this tree does too, and publishing it — from\n * the editor or over the API — keeps them rather than clearing them. Null\n * without a tree.\n */\nexport function aiEditSavedTree(version: FirebaseFirestore.DocumentSnapshot): NodesMap | null {\n const nodes = decodeStoredNodes<NodesMap>(version.get('nodes'))\n return nodes ? (injectLayoutStyleOverrides(nodes, version.get('layoutStyleOverrides')) as NodesMap) : null\n}\n\n/** The tree a change is built on, as it is stored now (AGL-4235). */\nexport interface AiEditBase {\n /**\n * `draft` for the version's working draft, when the Besigner would still\n * offer it; `saved` for the version's own tree otherwise.\n */\n from: 'draft' | 'saved'\n /**\n * The tree, as the Besigner would hold it: a draft's as its author left it,\n * the saved version's with its layout style overrides on the root.\n */\n nodes: NodesMap\n /**\n * The `nodes` field as stored, exactly as read: what a revision of the tree\n * is read off, so parking the overrides on the root never moves it.\n */\n stored: unknown\n /** What stamped the draft, when a write did (`aiEditJobId`); null for a saved tree. */\n stampedBy: string | null\n}\n\n/**\n * The tree a change to a version is built on — the one rule, for the edit job,\n * its write and a reader that shows a page as the next change will find it:\n * the version's working draft when the Besigner would still offer it, so an\n * author's work in progress is never thrown away; otherwise the version's own\n * tree. `useDraft: false` is a change that lands somewhere other than the\n * draft, built on the version alone. Null when neither has a tree.\n */\nexport function aiEditBase(\n draft: FirebaseFirestore.DocumentSnapshot,\n version: FirebaseFirestore.DocumentSnapshot,\n options: { useDraft?: boolean } = {},\n): AiEditBase | null {\n const usable = options.useDraft === false ? null : usableDraft(draft, version)\n if (usable) return { from: 'draft', nodes: usable.nodes, stored: draft.get('nodes'), stampedBy: usable.aiEditJobId }\n // A usable draft's root says what its author meant, overrides or none, so\n // only the saved tree gets them, as the editor gives them when it opens it.\n const nodes = aiEditSavedTree(version)\n return nodes ? { from: 'saved', nodes, stored: version.get('nodes'), stampedBy: null } : null\n}\n\n/** A version's working draft document: the Besigner's, at the core's one address. */\nexport function draftRef(versions: FirebaseFirestore.CollectionReference, versionId: string): FirebaseFirestore.DocumentReference {\n return versions.doc(versionId).collection(VERSION_DRAFT_COLLECTION).doc(VERSION_DRAFT_DOC_ID)\n}\n\n/**\n * The document an edit job changes, on the job's own site: the page or\n * layout named, not deleted, not an email design, and the version it starts\n * from with a document in it. A refusal names what is wrong.\n */\nexport async function readAiEditTarget(\n firestore: Firestore,\n input: {\n orgId: string\n hostId: string\n inputs: AiEditJobInputs\n /** The job's own version id, to find what a run of it wrote; `null` at the door, before there is one. */\n jobId: string | null\n },\n): Promise<AiEditTargetRead | AiEditTargetRefusal> {\n const hostRef = firestore.collection('hosts').doc(input.hostId)\n const host = await hostRef.get()\n if (!host.exists || host.get('orgId') !== input.orgId) return { status: 404, error: AI_EDIT_NO_SITE_COPY }\n const kinds: AiEditTargetKind[] = input.inputs.targetKind ? [input.inputs.targetKind] : ['screen', 'layout']\n for (const kind of kinds) {\n const docRef = hostRef.collection(COLLECTIONS[kind]).doc(input.inputs.target)\n const doc = await docRef.get()\n if (!doc.exists) continue\n if (doc.get('deletedAt') != null) return { status: 404, error: AI_EDIT_GONE_COPY }\n if (kind === 'screen' && doc.get('kind') === 'email') return { status: 400, error: AI_EDIT_EMAIL_COPY }\n const pointerVersionId = text(doc.get('versionId')) || null\n const versions = docRef.collection('versions')\n const hostSubdomain = text(host.get('subdomain')) || null\n const name = text(doc.get('displayName')) || (kind === 'screen' ? 'Page' : 'Layout')\n // A run of this job that got as far as its write.\n const own = input.jobId ? await versions.doc(input.jobId).get() : null\n const sourceVersionId = input.inputs.versionId ?? pointerVersionId\n const base = {\n kind,\n id: doc.id,\n name,\n hostSubdomain,\n pointerVersionId,\n served: kind === 'layout' || screenServed(doc, host),\n scheduledVersionId: pendingScheduleVersion(doc),\n }\n if (own?.exists && input.jobId) {\n const placement: AiEditPlacement = pointerVersionId === input.jobId ? 'new-current' : 'new-beside'\n return { ...base, sourceVersionId: sourceVersionId ?? input.jobId, nodes: {}, draft: null, written: { versionId: input.jobId, placement } }\n }\n if (!sourceVersionId) return { status: 404, error: AI_EDIT_VERSION_GONE_COPY }\n const [source, draftDoc] = await Promise.all([versions.doc(sourceVersionId).get(), draftRef(versions, sourceVersionId).get()])\n if (!source.exists) return { status: 404, error: AI_EDIT_VERSION_GONE_COPY }\n if (input.jobId && source.get('aiEditJobId') === input.jobId) {\n return { ...base, sourceVersionId, nodes: {}, draft: null, written: { versionId: sourceVersionId, placement: 'in-place' } }\n }\n const draft = usableDraft(draftDoc, source)\n if (input.jobId && draft?.aiEditJobId === input.jobId) {\n return { ...base, sourceVersionId, nodes: {}, draft: null, written: { versionId: sourceVersionId, placement: 'draft' } }\n }\n // The saved tree as the Besigner opens it, the page's layout style\n // overrides on its root (see `aiEditSavedTree`).\n const nodes = aiEditSavedTree(source)\n if (!nodes || !Object.keys(nodes).length) return { status: 400, error: AI_EDIT_NO_NODES_COPY }\n return { ...base, sourceVersionId, nodes, draft: draft ? { nodes: draft.nodes } : null, written: null }\n }\n return { status: 404, error: AI_EDIT_GONE_COPY }\n}\n\n/**\n * Where a change may land (see the module head), or `refused` when the only\n * place is a version visitors see and the plan keeps no version history.\n */\nexport function aiEditPlacement(input: {\n versioning: boolean\n served: boolean\n sourceIsPointer: boolean\n sourceScheduled: boolean\n}): AiEditPlacement | 'refused' {\n if (input.versioning) return !input.served && input.sourceIsPointer ? 'new-current' : 'new-beside'\n const seen = input.sourceScheduled || (input.sourceIsPointer && input.served)\n return seen ? 'refused' : 'in-place'\n}\n\n/**\n * Where an edit job's change lands (AGL-4116): the version's working draft,\n * unless the request asked for a new version and the plan keeps version\n * history — then where {@link aiEditPlacement} puts a new one. Never refused:\n * a draft is on every plan, and no visitor sees it.\n */\nexport function aiEditJobPlacement(input: {\n newVersion: boolean\n versioning: boolean\n served: boolean\n sourceIsPointer: boolean\n sourceScheduled: boolean\n}): AiEditPlacement {\n if (!input.newVersion || !input.versioning) return 'draft'\n const placed = aiEditPlacement(input)\n return placed === 'refused' ? 'draft' : placed\n}\n\n// ── Writing it ────────────────────────────────────────────────────────────\n\n/** What a proposal built from the stored tree sees of the document, besides the tree (AGL-4235). */\nexport interface AiEditWriteBase extends AiEditBase {\n /** The document's current version, as the transaction reads it. */\n pointerVersionId: string | null\n}\n\nexport interface AiEditWriteInput<R = never> {\n hostId: string\n kind: AiEditTargetKind\n id: string\n sourceVersionId: string\n /**\n * A fresh id for this write: the new version's id, which is the job's, and\n * the stamp a draft it writes carries, which is how a write asked again\n * finds what it wrote. An API edit hands its own (AGL-4235).\n */\n jobVersionId: string\n versioning: boolean\n /** The request asked for a new version (see {@link aiEditJobPlacement}). */\n newVersion: boolean\n /**\n * The change. A model's proposal is checked before the write against the\n * tree the model was shown, and the canvas's guards refuse it whole if an\n * element changed since. A caller that holds no tree yet (AGL-4235) hands a\n * function instead, given the tree exactly as this transaction reads it,\n * and validates and builds the change on that, so what it checked and what\n * is written are one tree. It refuses with `{ refused }`, and nothing is\n * written.\n */\n proposal: AssistEditProposal | ((base: AiEditWriteBase) => AssistEditProposal | { refused: R })\n /** Whether the page's search fields may be written: a page no visitor reaches. */\n writeSeo: boolean\n versionName: string\n /** Who the write is for: a member's uid, or a stable id for a writer that is no person. */\n uid: string\n /**\n * Who the write is for in words, written on a draft as `updatedByLabel`\n * when given: an API key's or a connected app's name (AGL-4235). The job\n * writes none.\n */\n updatedByLabel?: string\n /**\n * How the write arrived, stamped as `updatedVia` (see `content-write-stamp`):\n * an API key or connected app names itself; absent, the AI job does.\n */\n updatedVia?: string | null\n /**\n * Refuse a tree larger than this many bytes, measured as the save measures\n * it (`measureNodeMap`), and write nothing. Absent: not measured.\n */\n maxNodeBytes?: number\n /** The job the member started, stamped as `aiJobId` on a new version. */\n aiJobId: string\n now: Date\n}\n\nexport type AiEditWrite<R = never> =\n | {\n ok: true\n versionId: string\n placement: AiEditPlacement\n seoWritten: boolean\n /**\n * What this call wrote, when it wrote (not a run asked again): the\n * stored tree's bytes, and the ids the canvas gave each insert's elements.\n */\n written?: { stored: Uint8Array; inserted: AssistEditInserted[] }\n }\n | {\n ok: false\n error: string\n /** The caller's own refusal, from a proposal built on the stored tree. */\n refused?: R\n /** The tree would pass `maxNodeBytes`: its size. */\n tooLarge?: { bytes: number }\n }\n\n/**\n * The change written, in one transaction that reads the document as it is\n * stored NOW — a member may have saved, published or changed plan's history\n * since the read — decides where it lands again on that, and applies the\n * proposal to the stored nodes through the canvas's guards. An element that\n * changed since the model saw it refuses the whole change, as the editor does.\n */\nexport async function writeAiEdit<R = never>(firestore: Firestore, input: AiEditWriteInput<R>): Promise<AiEditWrite<R>> {\n const hostRef = firestore.collection('hosts').doc(input.hostId)\n const docRef = hostRef.collection(COLLECTIONS[input.kind]).doc(input.id)\n const versions = docRef.collection('versions')\n const sourceRef = versions.doc(input.sourceVersionId)\n const newRef = versions.doc(input.jobVersionId)\n const sourceDraftRef = draftRef(versions, input.sourceVersionId)\n return firestore.runTransaction(async (tx): Promise<AiEditWrite<R>> => {\n const [host, doc, source, already, draftDoc] = await Promise.all([\n tx.get(hostRef),\n tx.get(docRef),\n tx.get(sourceRef),\n tx.get(newRef),\n tx.get(sourceDraftRef),\n ])\n const pointer = text(doc.get('versionId')) || null\n if (already.exists) {\n return { ok: true, versionId: input.jobVersionId, placement: pointer === input.jobVersionId ? 'new-current' : 'new-beside', seoWritten: false }\n }\n if (!doc.exists || doc.get('deletedAt') != null) return { ok: false, error: AI_EDIT_GONE_COPY }\n if (!source.exists) return { ok: false, error: AI_EDIT_VERSION_GONE_COPY }\n const served = input.kind === 'layout' || screenServed(doc, host)\n const placement = aiEditJobPlacement({\n newVersion: input.newVersion,\n versioning: input.versioning,\n served,\n sourceIsPointer: pointer === input.sourceVersionId,\n sourceScheduled: pendingScheduleVersion(doc) === input.sourceVersionId,\n })\n // Read again here, as the version is: an author who saved their draft,\n // or published it, since the read is what the change is built on now.\n const base = aiEditBase(draftDoc, source, { useDraft: placement === 'draft' })\n if (base?.from === 'draft' && base.stampedBy === input.jobVersionId) {\n return { ok: true, versionId: input.sourceVersionId, placement, seoWritten: false }\n }\n if (!base) return { ok: false, error: AI_EDIT_NO_NODES_COPY }\n const nodes = base.nodes\n const built = typeof input.proposal === 'function' ? input.proposal({ ...base, pointerVersionId: pointer }) : input.proposal\n if ('refused' in built) return { ok: false, error: AI_EDIT_REFUSED_COPY, refused: built.refused }\n const versionId = placement === 'draft' ? input.sourceVersionId : input.jobVersionId\n const seo: Partial<Record<(typeof SCREEN_SEO_TEXT_FIELDS)[number], string>> = {}\n const writeSeo = input.writeSeo && input.kind === 'screen' && !served\n const proposal: AssistEditProposal = {\n ...built,\n ops: writeSeo ? built.ops : built.ops.filter((op) => op.op !== 'setSeo'),\n target: { ...built.target, versionId },\n }\n const applied = aiApplyEditToNodes(nodes, proposal, writeSeo ? seo : undefined)\n if (applied.ok === false) return { ok: false, error: applied.reason === 'stale' ? AI_EDIT_STALE_COPY : AI_EDIT_REFUSED_COPY }\n if (input.maxNodeBytes !== undefined) {\n const { bytes } = measureNodeMap(applied.nodes)\n if (bytes > input.maxNodeBytes) return { ok: false, error: AI_EDIT_TOO_LARGE_COPY, tooLarge: { bytes } }\n }\n // A draft keeps the overrides on its root, as the editor's own draft\n // does; a version stores them beside its tree, never in it, as the\n // editor's save lifts them out (the copy below keeps the field).\n const packed = encodeStoredNodes(placement === 'draft' ? applied.nodes : extractLayoutStyleOverrides(applied.nodes).nodes)\n if (!packed) return { ok: false, error: AI_EDIT_NO_NODES_COPY }\n const stored = Buffer.from(packed)\n const docPatch: Record<string, unknown> = {}\n const writer: ContentWriteActor = { uid: input.uid, via: input.updatedVia ?? `ai-job:${input.aiJobId}` }\n const stamp = contentEditStamp(writer, input.now)\n if (placement === 'draft') {\n // The whole working tree, as the Besigner writes a draft, taken against\n // the version as stored so the Besigner offers it with Open draft.\n tx.set(sourceDraftRef, {\n nodes: stored,\n baseStamp: versionStamp(source.get('updatedAt')),\n updatedByUid: input.uid,\n updatedByEmail: null,\n ...(input.updatedByLabel ? { updatedByLabel: input.updatedByLabel } : {}),\n ...stamp,\n aiEditJobId: input.jobVersionId,\n })\n } else {\n // A copy of the version it started from — its layout binding, its\n // declared properties, everything the editor stored — with the changed\n // tree, as the versions route copies one.\n const copy = withoutVersionPublishStamp({ ...(source.data() as Record<string, unknown>) })\n delete copy['aiEditJobId']\n // Moving a served page's pointer is a publish, and is stamped as one.\n const live = placement === 'new-current' && served\n tx.create(newRef, {\n ...copy,\n nodes: stored,\n displayName: input.versionName,\n createdAt: input.now,\n createdBy: input.uid,\n ...stamp,\n ...(live ? versionPublishStamp(writer, input.now) : {}),\n aiJobId: input.aiJobId,\n })\n if (placement === 'new-current') docPatch['versionId'] = input.jobVersionId\n if (live) Object.assign(docPatch, parentPublishStamp(writer, input.now))\n }\n for (const [field, value] of Object.entries(seo)) {\n if (value) docPatch[`seo.${field}`] = value\n }\n if (Object.keys(docPatch).length) tx.update(docRef, { ...docPatch, ...stamp })\n return {\n ok: true,\n versionId,\n placement,\n seoWritten: Object.keys(seo).length > 0,\n written: { stored, inserted: applied.inserted },\n }\n })\n}\n\n// ── The runner ────────────────────────────────────────────────────────────\n\nexport interface AiJobEditStepDeps {\n readTarget?: typeof readAiEditTarget\n writeEdit?: typeof writeAiEdit\n readDatasets?: typeof readAiSiteDatasets\n clearMirror?: typeof clearAiEditMirror\n}\n\n/**\n * Clears the co-edit mirror of the version whose draft a job just wrote\n * (AGL-4116), as the Besigner's own Save draft does.\n *\n * The mirror holds unsaved canvas work and replays everything newer than the\n * version's last save to whoever opens it. A draft write does not move the\n * version's save, so without this the canvas of someone who had opened the\n * older draft replays over the change the job just saved, and a room with\n * replayed work offers no draft at all: the newer draft can only be reached by\n * a Discard that deletes it. Best effort: a mirror that cannot be cleared\n * leaves the draft saved, and the job reports what it wrote.\n */\nexport async function clearAiEditMirror(input: {\n orgId: string\n hostId: string\n kind: AiEditTargetKind\n id: string\n versionId: string\n}): Promise<void> {\n await firebaseAdmin\n .database()\n .ref(coeditMirrorRoomPath({ orgId: input.orgId, hostId: input.hostId, docType: input.kind, docId: input.id, versionId: input.versionId }))\n .remove()\n}\n\n/** What an edit wrote, as the job's output: a link into the Besigner on the version written. */\nexport function aiEditOutput(\n read: Pick<AiEditTargetRead, 'kind' | 'id' | 'name' | 'hostSubdomain'>,\n hostId: string,\n written: { versionId: string; placement: AiEditPlacement },\n leftOut: readonly string[],\n options: { versionsUnavailable?: boolean } = {},\n): AiJobOutput {\n return {\n resource: read.kind,\n id: read.id,\n versionId: written.versionId,\n hostId,\n hostSubdomain: read.hostSubdomain,\n label: read.name,\n ...(written.placement === 'draft' ? { inDraft: true as const } : {}),\n note: aiEditOutputNote({\n kind: read.kind,\n placement: written.placement,\n leftOut,\n ...(options.versionsUnavailable ? { versionsUnavailable: true } : {}),\n }),\n }\n}\n\n/** The new version's id: the job's own, which a build's unit takes from its plan item. */\nexport function aiEditVersionId(job: Pick<AiJob, '$id'>): string {\n return job.$id.slice(0, 64)\n}\n\n/**\n * The ops a job may save, and why it left the rest out: never a component\n * save, and a page's search fields only where no visitor reaches the page.\n */\nexport function aiEditJobOps(\n ops: readonly AssistEditOp[],\n options: { seo: boolean },\n): { ops: AssistEditOp[]; leftOut: string[] } {\n const kept: AssistEditOp[] = []\n const leftOut = new Set<string>()\n for (const op of ops) {\n if (op.op === 'saveAsComponent') leftOut.add(AI_EDIT_COMPONENT_LEFT_OUT)\n else if (op.op === 'setSeo' && !options.seo) leftOut.add(AI_EDIT_SEO_LEFT_OUT)\n else kept.push(op)\n }\n return { ops: kept, leftOut: [...leftOut] }\n}\n\nexport function createAiJobEditStep(deps: AiJobEditStepDeps = {}): AiJobStepRunner {\n const readTarget = deps.readTarget ?? readAiEditTarget\n const writeEdit = deps.writeEdit ?? writeAiEdit\n const readDatasets = deps.readDatasets ?? readAiSiteDatasets\n const clearMirror = deps.clearMirror ?? clearAiEditMirror\n return async ({ job, now, signal, firestore, org, modelFor }): Promise<AiJobStepOutcome> => {\n const model = modelFor?.('job.edit') ?? aiJobEditModel()\n const unspent = (failure: string): AiJobStepOutcome => ({ ...aiUnspentOutcome(model), failure })\n const inputs = parseAiEditJobInputs(job.inputs)\n if (typeof inputs === 'string') return unspent(inputs)\n const hostId = job.hostId\n if (!hostId) return unspent(AI_EDIT_NO_SITE_COPY)\n const read = await readTarget(firestore, { orgId: job.orgId, hostId, inputs, jobId: aiEditVersionId(job) })\n if ('error' in read) return unspent(read.error)\n if (read.written) return aiUnspentOutcome(model, { outputs: [aiEditOutput(read, hostId, read.written, [])] })\n\n const orgData = org ?? ((await firestore.collection('orgs').doc(job.orgId).get()).data() ?? null)\n const versioning = checkEntitlement(orgData as never, 'versioning')\n const placement = aiEditJobPlacement({\n newVersion: inputs.newVersion,\n versioning,\n served: read.served,\n sourceIsPointer: read.sourceVersionId === read.pointerVersionId,\n sourceScheduled: read.scheduledVersionId === read.sourceVersionId,\n })\n // A change to the draft is made on the draft the author already has.\n const outline = aiEditJobOutline(placement === 'draft' && read.draft ? read.draft.nodes : read.nodes)\n const context = outline ? parseAssistEditContext(outline, { whole: true }) : null\n if (!context) return unspent(AI_EDIT_NO_NODES_COPY)\n const target: AssistEditTarget = {\n kind: read.kind,\n documentId: read.id,\n versionId: placement === 'draft' ? read.sourceVersionId : aiEditVersionId(job),\n hostId,\n }\n\n // The site's datasets, so a request to show records binds a repeat to a\n // real one instead of writing tokens nothing fills (AGL-3616).\n const datasets = aiEditDatasetScope(await readDatasets(job.orgId, hostId), read)\n\n const generation = await runValidatedGeneration(\n 'edit',\n aiJobEditGeneration({ brief: job.brief, context, target, model, ...datasets, ...(signal ? { signal } : {}) }),\n )\n const spent = { ...aiGenerationSpent(generation), ...(generation.effort ? { effort: generation.effort } : {}) }\n if (generation.status === 'refused') return { ...spent, refused: true }\n // An answer its re-ask still could not make whole keeps the changes that\n // survived, as the chat door's card does, and says what it left out; one\n // with none, or one that broke a numbered rule, is nothing to save.\n let proposal: AssistEditProposal | null = generation.status === 'ok' ? generation.value : null\n const refused = generation.status === 'needs_input' ? generation.answer : null\n if (!proposal && refused) {\n const salvaged = validateStreamedGeneration('edit', {\n answer: refused,\n check: (answer) => checkAssistEditAnswer(answer, { context, target, ...datasets }),\n })\n proposal = salvaged.status === 'ok' ? salvaged.value : null\n }\n if (!proposal) return { ...spent, failure: AI_EDIT_NOTHING_COPY }\n\n const seo = read.kind === 'screen' && !read.served\n const kept = aiEditJobOps(proposal.ops, { seo })\n const leftOut = [...proposal.dropped, ...kept.leftOut]\n if (!kept.ops.length) {\n return { ...spent, failure: `Nothing was saved. Left out: ${leftOut.join('; ') || 'every change'}.` }\n }\n const write = await writeEdit(firestore, {\n hostId,\n kind: read.kind,\n id: read.id,\n sourceVersionId: read.sourceVersionId,\n jobVersionId: aiEditVersionId(job),\n versioning,\n newVersion: inputs.newVersion,\n proposal: { ...proposal, ops: kept.ops },\n writeSeo: seo,\n versionName: aiEditVersionName(proposal.summary),\n uid: job.createdBy,\n aiJobId: aiOriginJobId(job),\n now,\n })\n if (write.ok === false) return { ...spent, failure: write.error }\n if (write.placement === 'draft') {\n await clearMirror({ orgId: job.orgId, hostId, kind: read.kind, id: read.id, versionId: write.versionId }).catch((error: unknown) =>\n console.warn('[ai edit] the co-edit mirror could not be cleared', { jobId: job.$id, error }),\n )\n }\n const versionsUnavailable = inputs.newVersion && !versioning\n return { ...spent, outputs: [aiEditOutput(read, hostId, write, leftOut, { versionsUnavailable })] }\n }\n}\n\nexport const runAiJobEditStep = createAiJobEditStep()\n\n// ── Admission ─────────────────────────────────────────────────────────────\n\nexport interface AiEditJobAdmissionDeps {\n readTarget?: typeof readAiEditTarget\n ownerOf?: typeof resolveOrgIdForHost\n}\n\n/**\n * An edit job is admitted for a page or layout of a site of its own org that\n * has a version to start from. Every plan has somewhere to put the change\n * that no visitor sees — the version's draft — so no plan is refused.\n */\nexport function createAiEditJobAdmission(deps: AiEditJobAdmissionDeps = {}): AiJobAdmission {\n const readTarget = deps.readTarget ?? readAiEditTarget\n const ownerOf = deps.ownerOf ?? resolveOrgIdForHost\n return async (context): Promise<AiJobAdmissionRefusal | null> => {\n const inputs = parseAiEditJobInputs(context.inputs)\n if (typeof inputs === 'string') return { status: 400, error: inputs }\n if (!context.hostId) return { status: 400, error: AI_EDIT_NO_SITE_COPY }\n const owner = await ownerOf(context.hostId)\n if (!owner || owner !== context.orgId) return { status: 404, error: 'Unknown site' }\n // A job asked about at its door has no run to find yet.\n const read = await readTarget(context.firestore, { orgId: context.orgId, hostId: context.hostId, inputs, jobId: null })\n // Every plan has somewhere to put the change: the page's draft (AGL-4116).\n return 'error' in read ? read : null\n }\n}\n\nexport const aiEditJobAdmission = createAiEditJobAdmission()\n\n/** Registers the edit step and the check an edit job passes before it is created or resumed. */\nexport function registerAiEditJob(): void {\n registerAiJobStep('edit', runAiJobEditStep, { minimumMs: AI_JOB_EDIT_STEP_MINIMUM_MS })\n registerAiJobAdmission('edit', aiEditJobAdmission)\n}\n"],"names":["contentEditStamp","parentPublishStamp","versionPublishStamp","withoutVersionPublishStamp","checkEntitlement","SCREEN_KIND_TEMPLATE","screenSeoStageKey","SCREEN_SEO_TEXT_FIELDS","hasConcurrentWrite","versionStamp","extractLayoutStyleOverrides","injectLayoutStyleOverrides","decodeStoredNodes","encodeStoredNodes","coeditMirrorRoomPath","VERSION_DRAFT_COLLECTION","VERSION_DRAFT_DOC_ID","CanvasManager","FEATURE_FLAG","firebaseAdmin","resolveOrgIdForHost","measureNodeMap","applyAssistEdit","AI_EDIT_COMPONENT_LEFT_OUT","AI_EDIT_EMAIL_COPY","AI_EDIT_GONE_COPY","AI_EDIT_NO_NODES_COPY","AI_EDIT_NO_SITE_COPY","AI_EDIT_NOTHING_COPY","AI_EDIT_REFUSED_COPY","AI_EDIT_SEO_LEFT_OUT","AI_EDIT_STALE_COPY","AI_EDIT_TOO_LARGE_COPY","AI_EDIT_VERSION_GONE_COPY","aiEditJobOutline","aiEditOutputNote","aiEditVersionName","parseAiEditJobInputs","ASSIST_EDIT_TOOL_NAME","AI_STEP_TIERS","AI_ROUTING_TABLE","aiModelForStep","runValidatedGeneration","validateStreamedGeneration","AI_PALETTE","readAiSiteDatasets","assistEditTool","checkAssistEditAnswer","editCanvasBlock","editDatasetsBlock","editSelectionBlock","parseAssistEditContext","registerAiJobAdmission","aiJobStepBudget","aiOriginJobId","aiGenerationSpent","aiUnspentOutcome","AI_JOB_BRIEF_MAX_CHARS","registerAiJobStep","AI_EDIT_READS_MS","AI_JOB_EDIT_STEP_BUDGET","tier","maxTokens","lookups","ownReadsMs","AI_JOB_EDIT_STEP_MINIMUM_MS","minimumMs","aiJobEditModel","AI_JOB_EDIT_RULES","text","join","aiJobEditInstructions","kind","cacheBreakpoint","aiJobEditPrompt","input","datasets","context","job","brief","slice","aiEditDatasetScope","read","record","find","dataset","recordScreenId","id","undefined","map","name","fields","fieldIds","imageField","recordDatasetId","aiJobEditGeneration","request","row","target","step","model","instructions","messages","role","content","tool","thinking","effort","signal","check","answer","AI_EDIT_CANVAS_PLATFORM","components","getSchema","componentId","entry","acceptsChildren","flags","dropping","DISABLED","getLabel","displayName","aiEditCanvas","nodes","canvas","setNodes","aiApplyEditToNodes","proposal","seo","applied","field","value","session","documentKind","documentId","versionId","isLiveVersion","ok","reason","toJSON","inserted","COLLECTIONS","screen","layout","screenServed","host","get","routing","pendingScheduleVersion","doc","schedule","usableDraft","draft","version","exists","Object","keys","length","baseStamp","aiEditJobId","aiEditSavedTree","aiEditBase","options","usable","useDraft","from","stored","stampedBy","draftRef","versions","collection","readAiEditTarget","firestore","hostRef","hostId","orgId","status","error","kinds","inputs","targetKind","docRef","pointerVersionId","hostSubdomain","own","jobId","sourceVersionId","base","served","scheduledVersionId","placement","written","source","draftDoc","Promise","all","aiEditPlacement","versioning","sourceIsPointer","seen","sourceScheduled","aiEditJobPlacement","newVersion","placed","writeAiEdit","sourceRef","newRef","jobVersionId","sourceDraftRef","runTransaction","tx","already","pointer","seoWritten","built","refused","writeSeo","ops","filter","op","maxNodeBytes","bytes","tooLarge","packed","Buffer","docPatch","writer","uid","via","updatedVia","aiJobId","stamp","now","set","updatedByUid","updatedByEmail","updatedByLabel","copy","data","live","create","versionName","createdAt","createdBy","assign","entries","update","clearAiEditMirror","database","ref","docType","docId","remove","aiEditOutput","leftOut","resource","label","inDraft","note","versionsUnavailable","aiEditVersionId","$id","aiEditJobOps","kept","Set","add","push","createAiJobEditStep","deps","readTarget","writeEdit","readDatasets","clearMirror","org","modelFor","unspent","failure","outputs","orgData","outline","whole","generation","spent","salvaged","dropped","write","summary","catch","console","warn","runAiJobEditStep","createAiEditJobAdmission","ownerOf","owner","aiEditJobAdmission","registerAiEditJob"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,kBAAkB,EAClBC,mBAAmB,EACnBC,0BAA0B,QAErB,6CAA4C;AACnD,SAASC,gBAAgB,QAAQ,2CAA0C;AAC3E,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SAASC,iBAAiB,EAAEC,sBAAsB,QAAQ,2CAA0C;AACpG,SAASC,kBAAkB,EAAEC,YAAY,QAAQ,8CAA6C;AAC9F,SAASC,2BAA2B,EAAEC,0BAA0B,QAAQ,gDAA+C;AACvH,SAASC,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MAAM0Q,QAAQ,MAAMD,QAAQvN,QAAQiG,MAAM;QAC1C,IAAI,CAACuH,SAASA,UAAUxN,QAAQkG,KAAK,EAAE,OAAO;YAAEC,QAAQ;YAAKC,OAAO;QAAe;QACnF,wDAAwD;QACxD,MAAM/F,OAAO,MAAM2L,WAAWhM,QAAQ+F,SAAS,EAAE;YAAEG,OAAOlG,QAAQkG,KAAK;YAAED,QAAQjG,QAAQiG,MAAM;YAAEK;YAAQM,OAAO;QAAK;QACrH,2EAA2E;QAC3E,OAAO,WAAWvG,OAAOA,OAAO;IAClC;AACF;AAEA,OAAO,MAAMoN,qBAAqBH,2BAA0B;AAE5D,8FAA8F,GAC9F,OAAO,SAASI;IACd7O,kBAAkB,QAAQwO,kBAAkB;QAAEhO,WAAWD;IAA4B;IACrFb,uBAAuB,QAAQkP;AACjC"}
@@ -595,6 +595,7 @@ export function createAiJobEmailStep(deps = {}) {
595
595
  orgId: job.orgId,
596
596
  hostId,
597
597
  uid: job.createdBy,
598
+ via: `ai-job:${job.$id}`,
598
599
  org,
599
600
  now
600
601
  };