@aglyn/plugins-ai 1.0.0-beta.296 → 1.0.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.
- package/package.json +17 -17
- package/src/lib/components/ai-job-links.d.ts +2 -1
- package/src/lib/components/ai-job-links.js +8 -2
- package/src/lib/components/ai-job-links.js.map +1 -1
- package/src/lib/components/assist-edit-canvas.d.ts +12 -6
- package/src/lib/components/assist-edit-canvas.js +86 -36
- package/src/lib/components/assist-edit-canvas.js.map +1 -1
- package/src/lib/components/assist-edit-card.component.js +9 -8
- package/src/lib/components/assist-edit-card.component.js.map +1 -1
- package/src/lib/components/assist-page-change-card.component.d.ts +1 -1
- package/src/lib/components/assist-page-change-card.component.js +2 -2
- package/src/lib/components/assist-page-change-card.component.js.map +1 -1
- package/src/lib/components/assist-panel.component.js +19 -8
- package/src/lib/components/assist-panel.component.js.map +1 -1
- package/src/lib/jobs/ai-job-edit-step.d.ts +20 -0
- package/src/lib/jobs/ai-job-edit-step.js +39 -3
- package/src/lib/jobs/ai-job-edit-step.js.map +1 -1
- package/src/lib/model/ai-edit-job.js +1 -1
- package/src/lib/model/ai-edit-job.js.map +1 -1
- package/src/lib/model/ai-job-notice.js +3 -1
- package/src/lib/model/ai-job-notice.js.map +1 -1
- package/src/lib/model/assist-edit.d.ts +8 -7
- package/src/lib/model/assist-edit.js +4 -4
- package/src/lib/model/assist-edit.js.map +1 -1
- package/src/lib/model/assist-page-change.d.ts +14 -0
- package/src/lib/model/assist-page-change.js +21 -0
- package/src/lib/model/assist-page-change.js.map +1 -1
- package/src/lib/server/assist-chat.js +5 -1
- package/src/lib/server/assist-chat.js.map +1 -1
- package/src/lib/server/assist-edit.d.ts +12 -7
- package/src/lib/server/assist-edit.js +43 -22
- package/src/lib/server/assist-edit.js.map +1 -1
- package/src/lib/server/assist-page-change.js +1 -1
- package/src/lib/server/assist-page-change.js.map +1 -1
|
@@ -19,9 +19,10 @@ import { SCREEN_KIND_TEMPLATE } from "@aglyn/aglyn/app-utils/screen-route";
|
|
|
19
19
|
import { screenSeoStageKey, SCREEN_SEO_TEXT_FIELDS } from "@aglyn/aglyn/app-utils/screen-seo-fields";
|
|
20
20
|
import { hasConcurrentWrite, versionStamp } from "@aglyn/aglyn/app-utils/guarded-version-save";
|
|
21
21
|
import { decodeStoredNodes, encodeStoredNodes } from "@aglyn/aglyn/app-utils/stored-nodes";
|
|
22
|
-
import { VERSION_DRAFT_COLLECTION, VERSION_DRAFT_DOC_ID } from "@aglyn/aglyn/app-utils/version-draft";
|
|
22
|
+
import { coeditMirrorRoomPath, VERSION_DRAFT_COLLECTION, VERSION_DRAFT_DOC_ID } from "@aglyn/aglyn/app-utils/version-draft";
|
|
23
23
|
import { CanvasManager } from "@aglyn/aglyn/canvas-manager/canvas-manager";
|
|
24
24
|
import { FEATURE_FLAG } from "@aglyn/aglyn/foundation/constants/shared";
|
|
25
|
+
import { firebaseAdmin } from "@aglyn/tenant-data-admin/server/firebase-admin";
|
|
25
26
|
import { resolveOrgIdForHost } from "@aglyn/tenant-data-admin/server/organizations";
|
|
26
27
|
import { applyAssistEdit } from "../components/assist-edit-canvas.js";
|
|
27
28
|
import { 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_VERSION_GONE_COPY, aiEditJobOutline, aiEditOutputNote, aiEditVersionName, parseAiEditJobInputs } from "../model/ai-edit-job.js";
|
|
@@ -123,7 +124,9 @@ export function aiJobEditModel() {
|
|
|
123
124
|
var _input_datasets;
|
|
124
125
|
const datasets = editDatasetsBlock((_input_datasets = input.datasets) != null ? _input_datasets : []);
|
|
125
126
|
return [
|
|
126
|
-
editSelectionBlock(input.context
|
|
127
|
+
editSelectionBlock(input.context, {
|
|
128
|
+
job: true
|
|
129
|
+
}),
|
|
127
130
|
...datasets ? [
|
|
128
131
|
'',
|
|
129
132
|
datasets
|
|
@@ -529,6 +532,26 @@ function pendingScheduleVersion(doc) {
|
|
|
529
532
|
};
|
|
530
533
|
});
|
|
531
534
|
}
|
|
535
|
+
/**
|
|
536
|
+
* Clears the co-edit mirror of the version whose draft a job just wrote
|
|
537
|
+
* (AGL-4116), as the Besigner's own Save draft does.
|
|
538
|
+
*
|
|
539
|
+
* The mirror holds unsaved canvas work and replays everything newer than the
|
|
540
|
+
* version's last save to whoever opens it. A draft write does not move the
|
|
541
|
+
* version's save, so without this the canvas of someone who had opened the
|
|
542
|
+
* older draft replays over the change the job just saved, and a room with
|
|
543
|
+
* replayed work offers no draft at all: the newer draft can only be reached by
|
|
544
|
+
* a Discard that deletes it. Best effort: a mirror that cannot be cleared
|
|
545
|
+
* leaves the draft saved, and the job reports what it wrote.
|
|
546
|
+
*/ export async function clearAiEditMirror(input) {
|
|
547
|
+
await firebaseAdmin.database().ref(coeditMirrorRoomPath({
|
|
548
|
+
orgId: input.orgId,
|
|
549
|
+
hostId: input.hostId,
|
|
550
|
+
docType: input.kind,
|
|
551
|
+
docId: input.id,
|
|
552
|
+
versionId: input.versionId
|
|
553
|
+
})).remove();
|
|
554
|
+
}
|
|
532
555
|
/** What an edit wrote, as the job's output: a link into the Besigner on the version written. */ export function aiEditOutput(read, hostId, written, leftOut, options = {}) {
|
|
533
556
|
return _extends({
|
|
534
557
|
resource: read.kind,
|
|
@@ -571,10 +594,11 @@ function pendingScheduleVersion(doc) {
|
|
|
571
594
|
};
|
|
572
595
|
}
|
|
573
596
|
export function createAiJobEditStep(deps = {}) {
|
|
574
|
-
var _deps_readTarget, _deps_writeEdit, _deps_readDatasets;
|
|
597
|
+
var _deps_readTarget, _deps_writeEdit, _deps_readDatasets, _deps_clearMirror;
|
|
575
598
|
const readTarget = (_deps_readTarget = deps.readTarget) != null ? _deps_readTarget : readAiEditTarget;
|
|
576
599
|
const writeEdit = (_deps_writeEdit = deps.writeEdit) != null ? _deps_writeEdit : writeAiEdit;
|
|
577
600
|
const readDatasets = (_deps_readDatasets = deps.readDatasets) != null ? _deps_readDatasets : readAiSiteDatasets;
|
|
601
|
+
const clearMirror = (_deps_clearMirror = deps.clearMirror) != null ? _deps_clearMirror : clearAiEditMirror;
|
|
578
602
|
return async ({ job, now, signal, firestore, org, modelFor })=>{
|
|
579
603
|
var _ref, _data;
|
|
580
604
|
const model = (_ref = modelFor == null ? void 0 : modelFor('job.edit')) != null ? _ref : aiJobEditModel();
|
|
@@ -686,6 +710,18 @@ export function createAiJobEditStep(deps = {}) {
|
|
|
686
710
|
if (write.ok === false) return _extends({}, spent, {
|
|
687
711
|
failure: write.error
|
|
688
712
|
});
|
|
713
|
+
if (write.placement === 'draft') {
|
|
714
|
+
await clearMirror({
|
|
715
|
+
orgId: job.orgId,
|
|
716
|
+
hostId,
|
|
717
|
+
kind: read.kind,
|
|
718
|
+
id: read.id,
|
|
719
|
+
versionId: write.versionId
|
|
720
|
+
}).catch((error)=>console.warn('[ai edit] the co-edit mirror could not be cleared', {
|
|
721
|
+
jobId: job.$id,
|
|
722
|
+
error
|
|
723
|
+
}));
|
|
724
|
+
}
|
|
689
725
|
const versionsUnavailable = inputs.newVersion && !versioning;
|
|
690
726
|
return _extends({}, spent, {
|
|
691
727
|
outputs: [
|
|
@@ -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 { decodeStoredNodes, encodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { 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 { resolveOrgIdForHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport { applyAssistEdit } 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_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),\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 } | { 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 }\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/** A version's working draft document: the Besigner's, at the core's one address. */\nfunction 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 const nodes = decodeStoredNodes<NodesMap>(source.get('nodes'))\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\nexport interface AiEditWriteInput {\n hostId: string\n kind: AiEditTargetKind\n id: string\n sourceVersionId: string\n /** The new version's id, which is the job's; also the stamp a draft it writes carries. */\n jobVersionId: string\n versioning: boolean\n /** The request asked for a new version (see {@link aiEditJobPlacement}). */\n newVersion: boolean\n proposal: AssistEditProposal\n /** Whether the page's search fields may be written: a page no visitor reaches. */\n writeSeo: boolean\n versionName: string\n uid: string\n /** The job the member started, stamped as `aiJobId` on a new version. */\n aiJobId: string\n now: Date\n}\n\nexport type AiEditWrite =\n | { ok: true; versionId: string; placement: AiEditPlacement; seoWritten: boolean }\n | { ok: false; error: string }\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(firestore: Firestore, input: AiEditWriteInput): Promise<AiEditWrite> {\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> => {\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 draft = placement === 'draft' ? usableDraft(draftDoc, source) : null\n if (draft?.aiEditJobId === input.jobVersionId) {\n return { ok: true, versionId: input.sourceVersionId, placement, seoWritten: false }\n }\n const nodes = draft?.nodes ?? decodeStoredNodes<NodesMap>(source.get('nodes'))\n if (!nodes) return { ok: false, error: AI_EDIT_NO_NODES_COPY }\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 ...input.proposal,\n ops: writeSeo ? input.proposal.ops : input.proposal.ops.filter((op) => op.op !== 'setSeo'),\n target: { ...input.proposal.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 const packed = encodeStoredNodes(applied.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 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 { ok: true, versionId, placement, seoWritten: Object.keys(seo).length > 0 }\n })\n}\n\n// ── The runner ────────────────────────────────────────────────────────────\n\nexport interface AiJobEditStepDeps {\n readTarget?: typeof readAiEditTarget\n writeEdit?: typeof writeAiEdit\n readDatasets?: typeof readAiSiteDatasets\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 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 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","decodeStoredNodes","encodeStoredNodes","VERSION_DRAFT_COLLECTION","VERSION_DRAFT_DOC_ID","CanvasManager","FEATURE_FLAG","resolveOrgIdForHost","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_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","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","field","value","session","documentKind","documentId","versionId","isLiveVersion","applied","ok","reason","toJSON","COLLECTIONS","screen","layout","screenServed","host","get","routing","pendingScheduleVersion","doc","schedule","usableDraft","draft","version","exists","Object","keys","length","baseStamp","aiEditJobId","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","writeSeo","ops","filter","op","packed","stored","Buffer","from","docPatch","set","updatedByUid","uid","updatedByEmail","updatedAt","now","copy","data","create","versionName","createdAt","createdBy","aiJobId","entries","update","aiEditOutput","leftOut","options","resource","label","inDraft","note","versionsUnavailable","aiEditVersionId","job","$id","aiEditJobOps","kept","Set","add","push","createAiJobEditStep","deps","readTarget","writeEdit","readDatasets","org","modelFor","unspent","failure","outputs","orgData","outline","whole","generation","spent","refused","salvaged","dropped","write","summary","runAiJobEditStep","createAiEditJobAdmission","ownerOf","owner","aiEditJobAdmission","registerAiEditJob"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,2CAA0C;AAC3E,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SAASC,iBAAiB,EAAEC,sBAAsB,QAAQ,2CAA0C;AACpG,SAASC,kBAAkB,EAAEC,YAAY,QAAQ,8CAA6C;AAC9F,SAASC,iBAAiB,EAAEC,iBAAiB,QAAQ,sCAAqC;AAC1F,SAASC,wBAAwB,EAAEC,oBAAoB,QAAQ,uCAAsC;AACrG,SAASC,aAAa,QAAQ,6CAA4C;AAC1E,SAASC,YAA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QAAK;QACrH,2EAA2E;QAC3E,OAAO,WAAW9F,OAAOA,OAAO;IAClC;AACF;AAEA,OAAO,MAAM2L,qBAAqBH,2BAA0B;AAE5D,8FAA8F,GAC9F,OAAO,SAASI;IACdnN,kBAAkB,QAAQ8M,kBAAkB;QAAEtM,WAAWD;IAA4B;IACrFb,uBAAuB,QAAQwN;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 { 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 { 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 { applyAssistEdit } 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_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 } | { 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 }\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/** A version's working draft document: the Besigner's, at the core's one address. */\nfunction 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 const nodes = decodeStoredNodes<NodesMap>(source.get('nodes'))\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\nexport interface AiEditWriteInput {\n hostId: string\n kind: AiEditTargetKind\n id: string\n sourceVersionId: string\n /** The new version's id, which is the job's; also the stamp a draft it writes carries. */\n jobVersionId: string\n versioning: boolean\n /** The request asked for a new version (see {@link aiEditJobPlacement}). */\n newVersion: boolean\n proposal: AssistEditProposal\n /** Whether the page's search fields may be written: a page no visitor reaches. */\n writeSeo: boolean\n versionName: string\n uid: string\n /** The job the member started, stamped as `aiJobId` on a new version. */\n aiJobId: string\n now: Date\n}\n\nexport type AiEditWrite =\n | { ok: true; versionId: string; placement: AiEditPlacement; seoWritten: boolean }\n | { ok: false; error: string }\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(firestore: Firestore, input: AiEditWriteInput): Promise<AiEditWrite> {\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> => {\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 draft = placement === 'draft' ? usableDraft(draftDoc, source) : null\n if (draft?.aiEditJobId === input.jobVersionId) {\n return { ok: true, versionId: input.sourceVersionId, placement, seoWritten: false }\n }\n const nodes = draft?.nodes ?? decodeStoredNodes<NodesMap>(source.get('nodes'))\n if (!nodes) return { ok: false, error: AI_EDIT_NO_NODES_COPY }\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 ...input.proposal,\n ops: writeSeo ? input.proposal.ops : input.proposal.ops.filter((op) => op.op !== 'setSeo'),\n target: { ...input.proposal.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 const packed = encodeStoredNodes(applied.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 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 { ok: true, versionId, placement, seoWritten: Object.keys(seo).length > 0 }\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","decodeStoredNodes","encodeStoredNodes","coeditMirrorRoomPath","VERSION_DRAFT_COLLECTION","VERSION_DRAFT_DOC_ID","CanvasManager","FEATURE_FLAG","firebaseAdmin","resolveOrgIdForHost","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_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","field","value","session","documentKind","documentId","versionId","isLiveVersion","applied","ok","reason","toJSON","COLLECTIONS","screen","layout","screenServed","host","get","routing","pendingScheduleVersion","doc","schedule","usableDraft","draft","version","exists","Object","keys","length","baseStamp","aiEditJobId","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","writeSeo","ops","filter","op","packed","stored","Buffer","from","docPatch","set","updatedByUid","uid","updatedByEmail","updatedAt","now","copy","data","create","versionName","createdAt","createdBy","aiJobId","entries","update","clearAiEditMirror","database","ref","docType","docId","remove","aiEditOutput","leftOut","options","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","refused","salvaged","dropped","write","summary","catch","console","warn","runAiJobEditStep","createAiEditJobAdmission","ownerOf","owner","aiEditJobAdmission","registerAiEditJob"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,2CAA0C;AAC3E,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SAASC,iBAAiB,EAAEC,sBAAsB,QAAQ,2CAA0C;AACpG,SAASC,kBAAkB,EAAEC,YAAY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VERSIONS_DRAFT_COPY = 'A new version needs version history, which requires a Pro plan, so the change went into the draft instead.';
|
|
96
96
|
/** The output's note: where the change is, that nothing visitors see moved, and what was left out. */ export function aiEditOutputNote(input) {
|
|
97
97
|
const noun = NOUNS[input.kind];
|
|
98
|
-
const where = input.placement === 'draft' ? `Saved as this ${noun}’s draft. Nothing visitors see has changed: open
|
|
98
|
+
const where = input.placement === 'draft' ? `Saved as this ${noun}’s draft. Nothing visitors see has changed: open it in the Besigner to review it, then publish it when it is ready.` : input.placement === 'new-current' ? `Saved as a new version, now this ${noun}’s current one. The ${noun} is not published, so no visitor sees it until you publish it.` : input.placement === 'new-beside' ? `Saved as a new version beside the one it started from. Nothing visitors see has changed: open it to review it, and publish it when it is ready.` : `Saved on the version it started from, which no visitor sees: open it to review it.`;
|
|
99
99
|
const versions = input.versionsUnavailable ? ` ${AI_EDIT_NO_VERSIONS_DRAFT_COPY}` : '';
|
|
100
100
|
const leftOut = input.leftOut.length ? ` Left out: ${input.leftOut.join('; ')}.` : '';
|
|
101
101
|
return `${where}${versions}${leftOut}`.slice(0, 1000);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-edit-job.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 { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport { ASSIST_EDIT_WHOLE_MAX_NODES } from './assist-edit'\n\n/**\n * An `edit` job (AGL-3616): a change to a page or a layout the site already\n * has, asked for in words, made without the Besigner open.\n *\n * It speaks the Assist edit rung's own protocol — the same tool, the same\n * closed world of element ids, the same validators, the same canvas mutators\n * — against the stored document instead of an open canvas, and the change is\n * saved where no visitor sees it:\n *\n * - by default, on every plan, into the WORKING DRAFT of the version it\n * started from (AGL-4116) — the draft the Besigner saves to as an author\n * works and offers with Open draft, so the author reviews the change and\n * publishes it there exactly as they would their own. A draft the author\n * already has is built on, never replaced;\n * - when the request asks for a new version and the plan keeps version\n * history, as a NEW version beside the one it started from, which becomes\n * the page's current version only when the page is not published; a\n * published page's and a layout's current version never move. Asked for\n * on a plan without version history, the change goes into the draft and\n * the output says why.\n *\n * Pure: the inputs, the sentences a person reads, and the outline the model\n * is shown. The runner is `jobs/ai-job-edit-step.ts`.\n */\n\n/** The documents an edit job changes: those that keep versions and render on a site. */\nexport const AI_EDIT_TARGET_KINDS = ['screen', 'layout'] as const\nexport type AiEditTargetKind = (typeof AI_EDIT_TARGET_KINDS)[number]\n\nexport interface AiEditJobInputs {\n /** The page's or layout's document id, on the job's site. */\n target: string\n /** Which collection the id is in; both are looked in, a page's first, when absent. */\n targetKind: AiEditTargetKind | null\n /** The version to start from; the document's current version when absent. */\n versionId: string | null\n /** The request asked for a new version; otherwise the change goes into the draft. */\n newVersion: boolean\n}\n\nconst DOCUMENT_ID = /^[A-Za-z0-9_-]{1,64}$/\n\nexport const AI_EDIT_TARGET_REQUIRED_COPY = 'Name the page or layout to change.'\nexport const AI_EDIT_TARGET_KIND_COPY = 'inputs.targetKind must be screen or layout'\nexport const AI_EDIT_VERSION_ID_COPY = 'inputs.versionId must name a version of the page or layout'\n\n/** A job's inputs read, or the sentence that says what is wrong with them. */\nexport function parseAiEditJobInputs(\n inputs: Readonly<Record<string, unknown>> | null | undefined,\n): AiEditJobInputs | string {\n const target = inputs?.['target']\n if (typeof target !== 'string' || !DOCUMENT_ID.test(target)) return AI_EDIT_TARGET_REQUIRED_COPY\n const kind = inputs?.['targetKind']\n if (kind != null && kind !== '' && !(AI_EDIT_TARGET_KINDS as readonly unknown[]).includes(kind)) {\n return AI_EDIT_TARGET_KIND_COPY\n }\n const versionId = inputs?.['versionId']\n if (versionId != null && versionId !== '' && (typeof versionId !== 'string' || !DOCUMENT_ID.test(versionId))) {\n return AI_EDIT_VERSION_ID_COPY\n }\n return {\n target,\n targetKind: kind ? (kind as AiEditTargetKind) : null,\n versionId: typeof versionId === 'string' && versionId ? versionId : null,\n newVersion: inputs?.['newVersion'] === true,\n }\n}\n\n// ── What a person reads ───────────────────────────────────────────────────\n\nexport const AI_EDIT_NO_SITE_COPY = 'Open the site the change is for before starting the job'\nexport const AI_EDIT_GONE_COPY = 'The page or layout to change is not on the site.'\nexport const AI_EDIT_VERSION_GONE_COPY = 'The version to start from is no longer on the page or layout.'\nexport const AI_EDIT_EMAIL_COPY = 'That is an email design, not a page — change it from Emails → Templates.'\nexport const AI_EDIT_NO_NODES_COPY = 'That version has nothing on it to change.'\n\n/**\n * A change that would land on a version visitors see, on a plan without\n * version history: the versions route's own sentence, after what it means\n * here.\n */\nexport const AI_EDIT_NEEDS_VERSIONING_COPY =\n 'Visitors see that version, so the change has to go into a new version beside it. Version history requires a Pro plan — see Billing to upgrade.'\n\n/** The model answered and no change survived its checks, even after its re-ask. */\nexport const AI_EDIT_NOTHING_COPY =\n 'No change could be made from that request. Say which part of the page to change, the way it reads on the page, and ask again.'\n\n/** The stored document moved under the change between the read and the write. */\nexport const AI_EDIT_STALE_COPY =\n 'The page changed while this edit was being written, so nothing was saved. Ask again.'\n\n/** The canvas's own guards refused part of the change. */\nexport const AI_EDIT_REFUSED_COPY = 'The editor refused part of this change, so none of it was saved.'\n\n/** What a version an edit job makes is called, from the change's one-line summary. */\nexport const AI_EDIT_VERSION_PREFIX = 'AI edit'\n\n/** The longest label a version takes, as the versions route cuts one. */\nexport const AI_EDIT_VERSION_NAME_MAX_CHARS = 200\n\nexport function aiEditVersionName(summary: string): string {\n const said = String(summary ?? '').replace(/\\s+/g, ' ').trim()\n return (said ? `${AI_EDIT_VERSION_PREFIX}: ${said}` : AI_EDIT_VERSION_PREFIX).slice(0, AI_EDIT_VERSION_NAME_MAX_CHARS)\n}\n\n/** Where the change landed, which decides what the output's note says. */\nexport type AiEditPlacement =\n /** A new version, now the unpublished page's current one. */\n | 'new-current'\n /** A new version beside the one it started from, which is unchanged. */\n | 'new-beside'\n /** The version it started from, changed in place: one no visitor reaches. Written before AGL-4116. */\n | 'in-place'\n /** The working draft of the version it started from, which the Besigner offers with Open draft. */\n | 'draft'\n\nconst NOUNS: Readonly<Record<AiEditTargetKind, string>> = { screen: 'page', layout: 'layout' }\n\n/**\n * Why a change asked for as a new version went into the draft: the plan\n * keeps no version history. The versions route's own words for the plan.\n */\nexport const AI_EDIT_NO_VERSIONS_DRAFT_COPY =\n 'A new version needs version history, which requires a Pro plan, so the change went into the draft instead.'\n\n/** The output's note: where the change is, that nothing visitors see moved, and what was left out. */\nexport function aiEditOutputNote(input: {\n kind: AiEditTargetKind\n placement: AiEditPlacement\n leftOut: readonly string[]\n /** A new version was asked for on a plan without version history. */\n versionsUnavailable?: boolean\n}): string {\n const noun = NOUNS[input.kind]\n const where =\n input.placement === 'draft'\n ? `Saved as this ${noun}’s draft. Nothing visitors see has changed: open the ${noun} in the Besigner and choose Open draft to review it, then publish it when it is ready.`\n : input.placement === 'new-current'\n ? `Saved as a new version, now this ${noun}’s current one. The ${noun} is not published, so no visitor sees it until you publish it.`\n : input.placement === 'new-beside'\n ? `Saved as a new version beside the one it started from. Nothing visitors see has changed: open it to review it, and publish it when it is ready.`\n : `Saved on the version it started from, which no visitor sees: open it to review it.`\n const versions = input.versionsUnavailable ? ` ${AI_EDIT_NO_VERSIONS_DRAFT_COPY}` : ''\n const leftOut = input.leftOut.length ? ` Left out: ${input.leftOut.join('; ')}.` : ''\n return `${where}${versions}${leftOut}`.slice(0, 1_000)\n}\n\n/** What the output says of search fields a published page keeps on the page itself. */\nexport const AI_EDIT_SEO_LEFT_OUT =\n 'the search title and description, which a published page uses as soon as they are saved — change them in Page properties'\n\n/** What the output says of a part a job cannot save on its own. */\nexport const AI_EDIT_COMPONENT_LEFT_OUT = 'saving part of the page as a reusable component, which is done in the editor'\n\n// ── The outline the model is shown ────────────────────────────────────────\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * The stored document as the outline the edit rung's protocol reads\n * (`parseAssistEditContext` with `whole` holds it to its limits): the\n * document root, then every element in the order it reads on the page — each\n * after its parent, so every ancestor chain the check walks is whole — with\n * its settings and its styles, up to the whole-document cap.\n *\n * In the editor, an outline is the neighborhood of what the author selected.\n * A job has no selection and nobody to ask, so it is the WHOLE document: a\n * request about a picture five levels down is about an element the model can\n * see, and a restyle starts from the styles the element has. Each element\n * keeps its real child count and the document its real size, so the prompt\n * can say what a document past the cap leaves out. `null` without a root.\n */\nexport function aiEditJobOutline(nodes: Readonly<Record<string, unknown>>): {\n selectedId: null\n total: number\n nodes: Array<Record<string, unknown>>\n} | null {\n const root = nodes[CANVAS_ROOT_ELEMENT_ID]\n if (!isRecord(root)) return null\n const childrenOf = (node: Record<string, unknown>): string[] =>\n Array.isArray(node['nodes']) ? node['nodes'].filter((id): id is string => typeof id === 'string' && isRecord(nodes[id])) : []\n const order: Array<{ id: string; parentId: string | null; index: number }> = []\n const seen = new Set<string>([CANVAS_ROOT_ELEMENT_ID])\n // Depth first, children in their stored order: the page as it reads.\n const stack: Array<{ id: string; parentId: string | null; index: number }> = [\n { id: CANVAS_ROOT_ELEMENT_ID, parentId: null, index: 0 },\n ]\n while (stack.length) {\n const at = stack.pop() as (typeof stack)[number]\n order.push(at)\n const children = childrenOf(nodes[at.id] as Record<string, unknown>)\n for (let index = children.length - 1; index >= 0; index -= 1) {\n const child = children[index]\n if (seen.has(child)) continue\n seen.add(child)\n stack.push({ id: child, parentId: at.id, index })\n }\n }\n return {\n selectedId: null,\n total: order.length,\n nodes: order.slice(0, ASSIST_EDIT_WHOLE_MAX_NODES).map(({ id, parentId, index }) => {\n const node = nodes[id] as Record<string, unknown>\n return {\n id,\n componentId: node['componentId'],\n parentId,\n index,\n childCount: childrenOf(node).length,\n ...(typeof node['name'] === 'string' && node['name'] ? { name: node['name'] } : {}),\n ...(isRecord(node['props']) ? { props: node['props'] } : {}),\n ...(isRecord(node['sx']) ? { sx: node['sx'] } : {}),\n }\n }),\n }\n}\n"],"names":["CANVAS_ROOT_ELEMENT_ID","ASSIST_EDIT_WHOLE_MAX_NODES","AI_EDIT_TARGET_KINDS","DOCUMENT_ID","AI_EDIT_TARGET_REQUIRED_COPY","AI_EDIT_TARGET_KIND_COPY","AI_EDIT_VERSION_ID_COPY","parseAiEditJobInputs","inputs","target","test","kind","includes","versionId","targetKind","newVersion","AI_EDIT_NO_SITE_COPY","AI_EDIT_GONE_COPY","AI_EDIT_VERSION_GONE_COPY","AI_EDIT_EMAIL_COPY","AI_EDIT_NO_NODES_COPY","AI_EDIT_NEEDS_VERSIONING_COPY","AI_EDIT_NOTHING_COPY","AI_EDIT_STALE_COPY","AI_EDIT_REFUSED_COPY","AI_EDIT_VERSION_PREFIX","AI_EDIT_VERSION_NAME_MAX_CHARS","aiEditVersionName","summary","said","String","replace","trim","slice","NOUNS","screen","layout","AI_EDIT_NO_VERSIONS_DRAFT_COPY","aiEditOutputNote","input","noun","where","placement","versions","versionsUnavailable","leftOut","length","join","AI_EDIT_SEO_LEFT_OUT","AI_EDIT_COMPONENT_LEFT_OUT","isRecord","value","Array","isArray","aiEditJobOutline","nodes","root","childrenOf","node","filter","id","order","seen","Set","stack","parentId","index","at","pop","push","children","child","has","add","selectedId","total","map","componentId","childCount","name","props","sx"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,2CAA0C;AACjF,SAASC,2BAA2B,QAAQ,mBAAe;AAE3D;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GAED,sFAAsF,GACtF,OAAO,MAAMC,uBAAuB;IAAC;IAAU;CAA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BAChCO;gBACAC;gBACAY,YAAYrB,WAAWC,MAAMZ,MAAM;eAC/B,OAAOY,IAAI,CAAC,OAAO,KAAK,YAAYA,IAAI,CAAC,OAAO,GAAG;gBAAEqB,MAAMrB,IAAI,CAAC,OAAO;YAAC,IAAI,CAAC,GAC7ER,SAASQ,IAAI,CAAC,QAAQ,IAAI;gBAAEsB,OAAOtB,IAAI,CAAC,QAAQ;YAAC,IAAI,CAAC,GACtDR,SAASQ,IAAI,CAAC,KAAK,IAAI;gBAAEuB,IAAIvB,IAAI,CAAC,KAAK;YAAC,IAAI,CAAC;QAErD;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-edit-job.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 { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport { ASSIST_EDIT_WHOLE_MAX_NODES } from './assist-edit'\n\n/**\n * An `edit` job (AGL-3616): a change to a page or a layout the site already\n * has, asked for in words, made without the Besigner open.\n *\n * It speaks the Assist edit rung's own protocol — the same tool, the same\n * closed world of element ids, the same validators, the same canvas mutators\n * — against the stored document instead of an open canvas, and the change is\n * saved where no visitor sees it:\n *\n * - by default, on every plan, into the WORKING DRAFT of the version it\n * started from (AGL-4116) — the draft the Besigner saves to as an author\n * works and offers with Open draft, so the author reviews the change and\n * publishes it there exactly as they would their own. A draft the author\n * already has is built on, never replaced;\n * - when the request asks for a new version and the plan keeps version\n * history, as a NEW version beside the one it started from, which becomes\n * the page's current version only when the page is not published; a\n * published page's and a layout's current version never move. Asked for\n * on a plan without version history, the change goes into the draft and\n * the output says why.\n *\n * Pure: the inputs, the sentences a person reads, and the outline the model\n * is shown. The runner is `jobs/ai-job-edit-step.ts`.\n */\n\n/** The documents an edit job changes: those that keep versions and render on a site. */\nexport const AI_EDIT_TARGET_KINDS = ['screen', 'layout'] as const\nexport type AiEditTargetKind = (typeof AI_EDIT_TARGET_KINDS)[number]\n\nexport interface AiEditJobInputs {\n /** The page's or layout's document id, on the job's site. */\n target: string\n /** Which collection the id is in; both are looked in, a page's first, when absent. */\n targetKind: AiEditTargetKind | null\n /** The version to start from; the document's current version when absent. */\n versionId: string | null\n /** The request asked for a new version; otherwise the change goes into the draft. */\n newVersion: boolean\n}\n\nconst DOCUMENT_ID = /^[A-Za-z0-9_-]{1,64}$/\n\nexport const AI_EDIT_TARGET_REQUIRED_COPY = 'Name the page or layout to change.'\nexport const AI_EDIT_TARGET_KIND_COPY = 'inputs.targetKind must be screen or layout'\nexport const AI_EDIT_VERSION_ID_COPY = 'inputs.versionId must name a version of the page or layout'\n\n/** A job's inputs read, or the sentence that says what is wrong with them. */\nexport function parseAiEditJobInputs(\n inputs: Readonly<Record<string, unknown>> | null | undefined,\n): AiEditJobInputs | string {\n const target = inputs?.['target']\n if (typeof target !== 'string' || !DOCUMENT_ID.test(target)) return AI_EDIT_TARGET_REQUIRED_COPY\n const kind = inputs?.['targetKind']\n if (kind != null && kind !== '' && !(AI_EDIT_TARGET_KINDS as readonly unknown[]).includes(kind)) {\n return AI_EDIT_TARGET_KIND_COPY\n }\n const versionId = inputs?.['versionId']\n if (versionId != null && versionId !== '' && (typeof versionId !== 'string' || !DOCUMENT_ID.test(versionId))) {\n return AI_EDIT_VERSION_ID_COPY\n }\n return {\n target,\n targetKind: kind ? (kind as AiEditTargetKind) : null,\n versionId: typeof versionId === 'string' && versionId ? versionId : null,\n newVersion: inputs?.['newVersion'] === true,\n }\n}\n\n// ── What a person reads ───────────────────────────────────────────────────\n\nexport const AI_EDIT_NO_SITE_COPY = 'Open the site the change is for before starting the job'\nexport const AI_EDIT_GONE_COPY = 'The page or layout to change is not on the site.'\nexport const AI_EDIT_VERSION_GONE_COPY = 'The version to start from is no longer on the page or layout.'\nexport const AI_EDIT_EMAIL_COPY = 'That is an email design, not a page — change it from Emails → Templates.'\nexport const AI_EDIT_NO_NODES_COPY = 'That version has nothing on it to change.'\n\n/**\n * A change that would land on a version visitors see, on a plan without\n * version history: the versions route's own sentence, after what it means\n * here.\n */\nexport const AI_EDIT_NEEDS_VERSIONING_COPY =\n 'Visitors see that version, so the change has to go into a new version beside it. Version history requires a Pro plan — see Billing to upgrade.'\n\n/** The model answered and no change survived its checks, even after its re-ask. */\nexport const AI_EDIT_NOTHING_COPY =\n 'No change could be made from that request. Say which part of the page to change, the way it reads on the page, and ask again.'\n\n/** The stored document moved under the change between the read and the write. */\nexport const AI_EDIT_STALE_COPY =\n 'The page changed while this edit was being written, so nothing was saved. Ask again.'\n\n/** The canvas's own guards refused part of the change. */\nexport const AI_EDIT_REFUSED_COPY = 'The editor refused part of this change, so none of it was saved.'\n\n/** What a version an edit job makes is called, from the change's one-line summary. */\nexport const AI_EDIT_VERSION_PREFIX = 'AI edit'\n\n/** The longest label a version takes, as the versions route cuts one. */\nexport const AI_EDIT_VERSION_NAME_MAX_CHARS = 200\n\nexport function aiEditVersionName(summary: string): string {\n const said = String(summary ?? '').replace(/\\s+/g, ' ').trim()\n return (said ? `${AI_EDIT_VERSION_PREFIX}: ${said}` : AI_EDIT_VERSION_PREFIX).slice(0, AI_EDIT_VERSION_NAME_MAX_CHARS)\n}\n\n/** Where the change landed, which decides what the output's note says. */\nexport type AiEditPlacement =\n /** A new version, now the unpublished page's current one. */\n | 'new-current'\n /** A new version beside the one it started from, which is unchanged. */\n | 'new-beside'\n /** The version it started from, changed in place: one no visitor reaches. Written before AGL-4116. */\n | 'in-place'\n /** The working draft of the version it started from, which the Besigner offers with Open draft. */\n | 'draft'\n\nconst NOUNS: Readonly<Record<AiEditTargetKind, string>> = { screen: 'page', layout: 'layout' }\n\n/**\n * Why a change asked for as a new version went into the draft: the plan\n * keeps no version history. The versions route's own words for the plan.\n */\nexport const AI_EDIT_NO_VERSIONS_DRAFT_COPY =\n 'A new version needs version history, which requires a Pro plan, so the change went into the draft instead.'\n\n/** The output's note: where the change is, that nothing visitors see moved, and what was left out. */\nexport function aiEditOutputNote(input: {\n kind: AiEditTargetKind\n placement: AiEditPlacement\n leftOut: readonly string[]\n /** A new version was asked for on a plan without version history. */\n versionsUnavailable?: boolean\n}): string {\n const noun = NOUNS[input.kind]\n const where =\n input.placement === 'draft'\n ? `Saved as this ${noun}’s draft. Nothing visitors see has changed: open it in the Besigner to review it, then publish it when it is ready.`\n : input.placement === 'new-current'\n ? `Saved as a new version, now this ${noun}’s current one. The ${noun} is not published, so no visitor sees it until you publish it.`\n : input.placement === 'new-beside'\n ? `Saved as a new version beside the one it started from. Nothing visitors see has changed: open it to review it, and publish it when it is ready.`\n : `Saved on the version it started from, which no visitor sees: open it to review it.`\n const versions = input.versionsUnavailable ? ` ${AI_EDIT_NO_VERSIONS_DRAFT_COPY}` : ''\n const leftOut = input.leftOut.length ? ` Left out: ${input.leftOut.join('; ')}.` : ''\n return `${where}${versions}${leftOut}`.slice(0, 1_000)\n}\n\n/** What the output says of search fields a published page keeps on the page itself. */\nexport const AI_EDIT_SEO_LEFT_OUT =\n 'the search title and description, which a published page uses as soon as they are saved — change them in Page properties'\n\n/** What the output says of a part a job cannot save on its own. */\nexport const AI_EDIT_COMPONENT_LEFT_OUT = 'saving part of the page as a reusable component, which is done in the editor'\n\n// ── The outline the model is shown ────────────────────────────────────────\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/**\n * The stored document as the outline the edit rung's protocol reads\n * (`parseAssistEditContext` with `whole` holds it to its limits): the\n * document root, then every element in the order it reads on the page — each\n * after its parent, so every ancestor chain the check walks is whole — with\n * its settings and its styles, up to the whole-document cap.\n *\n * In the editor, an outline is the neighborhood of what the author selected.\n * A job has no selection and nobody to ask, so it is the WHOLE document: a\n * request about a picture five levels down is about an element the model can\n * see, and a restyle starts from the styles the element has. Each element\n * keeps its real child count and the document its real size, so the prompt\n * can say what a document past the cap leaves out. `null` without a root.\n */\nexport function aiEditJobOutline(nodes: Readonly<Record<string, unknown>>): {\n selectedId: null\n total: number\n nodes: Array<Record<string, unknown>>\n} | null {\n const root = nodes[CANVAS_ROOT_ELEMENT_ID]\n if (!isRecord(root)) return null\n const childrenOf = (node: Record<string, unknown>): string[] =>\n Array.isArray(node['nodes']) ? node['nodes'].filter((id): id is string => typeof id === 'string' && isRecord(nodes[id])) : []\n const order: Array<{ id: string; parentId: string | null; index: number }> = []\n const seen = new Set<string>([CANVAS_ROOT_ELEMENT_ID])\n // Depth first, children in their stored order: the page as it reads.\n const stack: Array<{ id: string; parentId: string | null; index: number }> = [\n { id: CANVAS_ROOT_ELEMENT_ID, parentId: null, index: 0 },\n ]\n while (stack.length) {\n const at = stack.pop() as (typeof stack)[number]\n order.push(at)\n const children = childrenOf(nodes[at.id] as Record<string, unknown>)\n for (let index = children.length - 1; index >= 0; index -= 1) {\n const child = children[index]\n if (seen.has(child)) continue\n seen.add(child)\n stack.push({ id: child, parentId: at.id, index })\n }\n }\n return {\n selectedId: null,\n total: order.length,\n nodes: order.slice(0, ASSIST_EDIT_WHOLE_MAX_NODES).map(({ id, parentId, index }) => {\n const node = nodes[id] as Record<string, unknown>\n return {\n id,\n componentId: node['componentId'],\n parentId,\n index,\n childCount: childrenOf(node).length,\n ...(typeof node['name'] === 'string' && node['name'] ? { name: node['name'] } : {}),\n ...(isRecord(node['props']) ? { props: node['props'] } : {}),\n ...(isRecord(node['sx']) ? { sx: node['sx'] } : {}),\n }\n }),\n }\n}\n"],"names":["CANVAS_ROOT_ELEMENT_ID","ASSIST_EDIT_WHOLE_MAX_NODES","AI_EDIT_TARGET_KINDS","DOCUMENT_ID","AI_EDIT_TARGET_REQUIRED_COPY","AI_EDIT_TARGET_KIND_COPY","AI_EDIT_VERSION_ID_COPY","parseAiEditJobInputs","inputs","target","test","kind","includes","versionId","targetKind","newVersion","AI_EDIT_NO_SITE_COPY","AI_EDIT_GONE_COPY","AI_EDIT_VERSION_GONE_COPY","AI_EDIT_EMAIL_COPY","AI_EDIT_NO_NODES_COPY","AI_EDIT_NEEDS_VERSIONING_COPY","AI_EDIT_NOTHING_COPY","AI_EDIT_STALE_COPY","AI_EDIT_REFUSED_COPY","AI_EDIT_VERSION_PREFIX","AI_EDIT_VERSION_NAME_MAX_CHARS","aiEditVersionName","summary","said","String","replace","trim","slice","NOUNS","screen","layout","AI_EDIT_NO_VERSIONS_DRAFT_COPY","aiEditOutputNote","input","noun","where","placement","versions","versionsUnavailable","leftOut","length","join","AI_EDIT_SEO_LEFT_OUT","AI_EDIT_COMPONENT_LEFT_OUT","isRecord","value","Array","isArray","aiEditJobOutline","nodes","root","childrenOf","node","filter","id","order","seen","Set","stack","parentId","index","at","pop","push","children","child","has","add","selectedId","total","map","componentId","childCount","name","props","sx"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,2CAA0C;AACjF,SAASC,2BAA2B,QAAQ,mBAAe;AAE3D;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GAED,sFAAsF,GACtF,OAAO,MAAMC,uBAAuB;IAAC;IAAU;CAAS,CAAS;AAcjE,MAAMC,cAAc;AAEpB,OAAO,MAAMC,+BAA+B,qCAAoC;AAChF,OAAO,MAAMC,2BAA2B,6CAA4C;AACpF,OAAO,MAAMC,0BAA0B,6DAA4D;AAEnG,4EAA4E,GAC5E,OAAO,SAASC,qBACdC,MAA4D;IAE5D,MAAMC,SAASD,0BAAAA,MAAQ,CAAC,SAAS;IACjC,IAAI,OAAOC,WAAW,YAAY,CAACN,YAAYO,IAAI,CAACD,SAAS,OAAOL;IACpE,MAAMO,OAAOH,0BAAAA,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AI,CAAC;QAErD;IACF;AACF"}
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
17
|
+
import { besignerOpenDraftHref } from "@aglyn/aglyn/app-utils/version-draft";
|
|
17
18
|
import { aiBuildOutcomeLine, aiSitePartialCopy } from "./ai-build-progress.js";
|
|
18
19
|
import { aiJobKindNoun } from "./ai-job-activity.js";
|
|
19
20
|
import { aiCustomerSafeCopy, aiJobRefundCopy } from "./ai-job-failure-copy.js";
|
|
@@ -74,7 +75,8 @@ import { aiCustomerSafeCopy, aiJobRefundCopy } from "./ai-job-failure-copy.js";
|
|
|
74
75
|
const versioned = own.find((output)=>AI_JOB_BESIGNER_SEGMENT[output.resource] && output.versionId);
|
|
75
76
|
if (own.length === 1 && versioned) {
|
|
76
77
|
const segment = AI_JOB_BESIGNER_SEGMENT[versioned.resource];
|
|
77
|
-
|
|
78
|
+
const besigner = `${base}/${segment}/${versioned.id}/versions/${versioned.versionId}/besigner`;
|
|
79
|
+
return versioned.inDraft ? besignerOpenDraftHref(besigner) : besigner;
|
|
78
80
|
}
|
|
79
81
|
}
|
|
80
82
|
return `${base}?${AI_JOB_LINK_PARAM}=${encodeURIComponent(job.$id)}`;
|