@aglyn/plugins-ai 1.27.0 → 1.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/package.json +17 -17
  2. package/src/lib/components/ai-credits-prompt.component.js +4 -1
  3. package/src/lib/components/ai-credits-prompt.component.js.map +1 -1
  4. package/src/lib/components/ai-site-import-job.component.js +5 -2
  5. package/src/lib/components/ai-site-import-job.component.js.map +1 -1
  6. package/src/lib/components/ai-site-start-card.component.js +6 -3
  7. package/src/lib/components/ai-site-start-card.component.js.map +1 -1
  8. package/src/lib/components/assist-build-card.component.js +4 -1
  9. package/src/lib/components/assist-build-card.component.js.map +1 -1
  10. package/src/lib/components/assist-edit-canvas.d.ts +12 -0
  11. package/src/lib/components/assist-edit-canvas.js +38 -7
  12. package/src/lib/components/assist-edit-canvas.js.map +1 -1
  13. package/src/lib/components/assist-jobs-drawer.component.js +4 -1
  14. package/src/lib/components/assist-jobs-drawer.component.js.map +1 -1
  15. package/src/lib/components/assist-panel.component.js +5 -2
  16. package/src/lib/components/assist-panel.component.js.map +1 -1
  17. package/src/lib/declarations.server.js +17 -0
  18. package/src/lib/declarations.server.js.map +1 -1
  19. package/src/lib/jobs/ai-job-drafts.d.ts +5 -11
  20. package/src/lib/jobs/ai-job-drafts.js +8 -25
  21. package/src/lib/jobs/ai-job-drafts.js.map +1 -1
  22. package/src/lib/jobs/ai-job-edit-step.d.ts +95 -5
  23. package/src/lib/jobs/ai-job-edit-step.js +88 -17
  24. package/src/lib/jobs/ai-job-edit-step.js.map +1 -1
  25. package/src/lib/model/ai-edit-job.d.ts +27 -0
  26. package/src/lib/model/ai-edit-job.js +45 -23
  27. package/src/lib/model/ai-edit-job.js.map +1 -1
  28. package/src/lib/model/assist-edit.d.ts +2 -0
  29. package/src/lib/model/assist-edit.js.map +1 -1
  30. package/src/lib/runtime/ai-node-tree.d.ts +25 -1
  31. package/src/lib/runtime/ai-node-tree.js +39 -14
  32. package/src/lib/runtime/ai-node-tree.js.map +1 -1
  33. package/src/lib/server/ai-page-content.d.ts +83 -0
  34. package/src/lib/server/ai-page-content.js +765 -0
  35. package/src/lib/server/ai-page-content.js.map +1 -0
  36. package/src/lib/server/ai-usage.js +7 -1
  37. package/src/lib/server/ai-usage.js.map +1 -1
  38. package/src/lib/server/assist-edit.d.ts +136 -1
  39. package/src/lib/server/assist-edit.js +124 -47
  40. package/src/lib/server/assist-edit.js.map +1 -1
  41. package/src/lib/usage/ai-usage-wire.d.ts +15 -0
  42. package/src/lib/usage/ai-usage-wire.js +21 -0
  43. package/src/lib/usage/ai-usage-wire.js.map +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-page-content.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 { createHash } from 'node:crypto'\nimport { NODE_MAP_MAX_BYTES } from '@aglyn/aglyn/app-utils/measure-node-map'\nimport { screenClaimsToBeAPage } from '@aglyn/aglyn/app-utils/screen-route'\nimport { CANVAS_ROOT_ELEMENT_ID } from '@aglyn/aglyn/foundation/constants/canvas'\nimport type {\n PageContentEdit,\n PageContentEditInput,\n PageContentEditResult,\n PageContentElement,\n PageContentKind,\n PageContentKindProp,\n PageContentNewElement,\n PageContentRead,\n PageContentReadInput,\n PageContentRefusal,\n PageContentService,\n} from '@aglyn/aglyn/plugin-manager/plugin-page-content'\nimport {\n aiEditBase,\n aiEditDatasetScope,\n clearAiEditMirror,\n draftRef,\n writeAiEdit,\n type AiEditWriteBase,\n} from '../jobs/ai-job-edit-step'\nimport {\n AI_EDIT_GONE_COPY,\n AI_EDIT_NO_NODES_COPY,\n AI_EDIT_STALE_COPY,\n AI_EDIT_TOO_LARGE_COPY,\n AI_EDIT_VERSION_GONE_COPY,\n aiDocumentElements,\n type AiDocumentElement,\n} from '../model/ai-edit-job'\nimport {\n ASSIST_EDIT_ACTION_ID,\n summarizeAssistEditOps,\n type AssistEditCanvasContext,\n type AssistEditCanvasNode,\n type AssistEditProposal,\n} from '../model/assist-edit'\nimport {\n AI_REPEAT_DATASET_PROP,\n AI_SX_ALLOWED_KEYS,\n aiPaletteEntryWithCapabilities,\n aiPropIsIconPick,\n} from '../runtime/ai-node-tree'\nimport { AI_PALETTE } from '../runtime/ai-palette.generated'\nimport { readAiSiteDatasets } from '../runtime/site-inventory'\nimport {\n ASSIST_EDIT_MAX_INSERT_NODES,\n ASSIST_EDIT_MAX_OPS,\n ASSIST_EDIT_MOTION_SETTINGS,\n assistEditClosedWorld,\n assistEditLayerNameRefusal,\n validatePendingEdit,\n type AssistEditClosedWorldRefusal,\n type AssistEditViolation,\n type PendingEditOp,\n} from './assist-edit'\n\n/**\n * The platform's `core.page-content` contract, answered by the one server\n * page editor there is (AGL-4235): the Assist edit rung the AI edit job runs.\n *\n * A read shows a page as the next edit will find it — the waiting draft when\n * the Besigner would still offer it, otherwise the version the page points at\n * — with every element, complete. An edit is held to the editor's own closed\n * world and validators, as STRICTLY as a caller that is not a model needs:\n * where the rung repairs a model's answer (a setting dropped, text cut, a\n * value coerced), this refuses and names the problem. It lands through the\n * job's own write, always in the page's DRAFT: the live version, the version\n * document and the page document are never touched, and nothing a visitor\n * sees changes until the page is published.\n *\n * ## What `revision` is\n *\n * A digest of the base tree exactly as stored — the `nodes` field's bytes —\n * with which tree it is (the draft or the saved version) and the version's\n * id. It changes whenever that tree changes, and only then: a save that\n * stores the same tree leaves it, and a draft that stops being offered moves\n * the base to the saved version and so moves it too. Read off the content\n * rather than `updatedAt`, which a version written before stamps existed does\n * not carry, so the check an edit makes with `ifRevision` cannot pass on a\n * tree it has not seen.\n *\n * ## What is not editable here, shown as such\n *\n * Each element's `props` and `style` carry only what an edit can set: the\n * settings its kind declares in the palette (with the ones every element\n * takes — repeating, motion), and the style keys the validator admits.\n * Everything else the element stores — rich text (`html`), a class name, an\n * icon the owner picks, references only the editor writes, styles past the\n * key set, interactions, overrides — is under `readOnly`, so a caller can\n * read it and is not invited to send it back.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The id a write made with no person behind it is attributed to, beside its label. */\nexport const AI_PAGE_CONTENT_API_ACTOR = 'api'\n\n/** What a write's summary says, in the draft's history. */\nconst API_EDIT_SUMMARY = 'Edited through the API'\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst refusal = (\n status: PageContentRefusal['status'],\n code: string,\n message: string,\n fields?: Record<string, string>,\n): PageContentRefusal => ({ ok: false, status, code, message, ...(fields && Object.keys(fields).length ? { fields } : {}) })\n\n// ── The revision ──────────────────────────────────────────────────────────\n\n/** A stored value as text that does not depend on key order. */\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`\n if (isRecord(value)) {\n return `{${Object.keys(value)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`)\n .join(',')}}`\n }\n return JSON.stringify(value ?? null)\n}\n\n/**\n * The base tree's revision (see the module head): which tree, of which\n * version, and a digest of its `nodes` field as stored — the bytes a\n * current document stores, or a legacy map in a key-order-free form.\n */\nexport function aiPageContentRevision(from: 'draft' | 'saved', versionId: string, stored: unknown): string {\n const hash = createHash('sha256').update(`${from}:${versionId}:`)\n if (stored instanceof Uint8Array) hash.update(stored)\n else hash.update(canonicalJson(stored))\n return `${from === 'draft' ? 'd' : 's'}_${hash.digest('base64url').slice(0, 22)}`\n}\n\n// ── What an element shows ────────────────────────────────────────────────\n\n/** The kind an element is stored as; the document root's wrapper when it names none. */\nconst kindOf = (node: Record<string, unknown>): string =>\n typeof node['componentId'] === 'string' && node['componentId'] ? node['componentId'] : 'div'\n\n/**\n * The settings an edit can set on an element of this kind, by name: the\n * palette's declarations with the ones every element takes, less an icon the\n * site owner picks, then the motion settings and the repeat's dataset. Empty\n * for a kind the palette does not list, whose settings the validator cannot\n * check.\n */\nexport function aiPageContentKindProps(kind: string): Record<string, PageContentKindProp> {\n const entry = aiPaletteEntryWithCapabilities(kind)\n if (!entry) return {}\n const props: Record<string, PageContentKindProp> = {}\n for (const [name, schema] of Object.entries(entry.propsSchema.properties)) {\n if (aiPropIsIconPick(entry, name)) continue\n const role = entry.propRoles[name]\n const maxLength = role === 'text' ? (entry.textLimits[name] ?? schema.maxLength) : schema.maxLength\n props[name] = {\n ...(role ? { role } : {}),\n type: schema.type ?? 'string',\n ...(schema.enum?.length ? { values: [...schema.enum] } : {}),\n ...(maxLength !== undefined ? { maxLength } : {}),\n }\n }\n for (const [name, allowed] of Object.entries(ASSIST_EDIT_MOTION_SETTINGS)) {\n props[name] =\n allowed === 'switch'\n ? { role: 'motion', type: 'boolean' }\n : typeof allowed === 'number'\n ? { role: 'motion', type: 'integer' }\n : { role: 'motion', type: 'string', values: [...allowed] }\n }\n props[AI_REPEAT_DATASET_PROP] = { role: 'dataset', type: 'string' }\n return props\n}\n\n/** What the palette knows of one kind of element. */\nexport function aiPageContentKind(kind: string, options: { root?: boolean } = {}): PageContentKind {\n const entry = AI_PALETTE[kind]\n return {\n label: options.root ? 'Page' : (entry?.displayName ?? kind),\n acceptsChildren: options.root === true || entry?.acceptsChildren === true,\n props: options.root ? {} : aiPageContentKindProps(kind),\n }\n}\n\n/** Node fields an edit here never writes, which an element shows read-only. */\nconst READ_ONLY_NODE_FIELDS = ['className', 'styleOverrides', 'attrOverrides', 'presetRef', 'layoutStyleOverrides'] as const\n\n/** One stored element as a read answers it: what an edit can set, and the rest read-only. */\nfunction elementView(element: AiDocumentElement, settable: ReadonlySet<string>): PageContentElement {\n const { node } = element\n const kind = kindOf(node)\n const props: Record<string, unknown> = {}\n const readOnlyProps: Record<string, unknown> = {}\n for (const [name, value] of Object.entries(isRecord(node['props']) ? node['props'] : {})) {\n if (value === undefined) continue\n if (settable.has(name)) props[name] = value\n else readOnlyProps[name] = value\n }\n const style: Record<string, unknown> = {}\n const readOnlyStyle: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(isRecord(node['sx']) ? node['sx'] : {})) {\n if (AI_SX_ALLOWED_KEYS.has(key)) style[key] = value\n else readOnlyStyle[key] = value\n }\n const readOnly: NonNullable<PageContentElement['readOnly']> = {}\n if (Object.keys(readOnlyProps).length) readOnly.props = readOnlyProps\n if (Object.keys(readOnlyStyle).length) readOnly.style = readOnlyStyle\n if (Array.isArray(node['interactions']) && node['interactions'].length) readOnly.interactions = node['interactions'].length\n const fields = READ_ONLY_NODE_FIELDS.filter((field) => node[field] !== undefined && node[field] !== null)\n if (fields.length) readOnly.fields = fields\n return {\n id: element.id,\n kind,\n ...(typeof node['pluginId'] === 'string' && node['pluginId'] ? { pluginId: node['pluginId'] } : {}),\n ...(typeof node['name'] === 'string' && node['name'] ? { name: node['name'] } : {}),\n parentId: element.parentId,\n children: [...element.children],\n props,\n ...(Object.keys(style).length ? { style } : {}),\n ...(node['hidden'] === true ? { hidden: true } : {}),\n ...(Object.keys(readOnly).length ? { readOnly } : {}),\n }\n}\n\n/**\n * A page's elements as a read answers them, every one, depth first in the\n * order the page reads, with what each kind takes. With `elementId`, that\n * element and everything inside it; null when it is not on the page.\n */\nexport function aiPageContentElements(\n nodes: Readonly<Record<string, unknown>>,\n elementId?: string,\n): { total: number; elements: PageContentElement[]; kinds: Record<string, PageContentKind> } | null {\n const order = aiDocumentElements(nodes)\n if (!order) return null\n let chosen = order\n if (elementId !== undefined) {\n const start = order.findIndex((element) => element.id === elementId)\n if (start < 0) return null\n // Depth first, so a branch is the run of elements from its root until\n // the walk leaves it.\n const inside = new Set([elementId])\n chosen = [order[start]]\n for (const element of order.slice(start + 1)) {\n if (element.parentId === null || !inside.has(element.parentId)) break\n inside.add(element.id)\n chosen.push(element)\n }\n }\n const kinds: Record<string, PageContentKind> = {}\n const settable = new Map<string, ReadonlySet<string>>()\n const elements = chosen.map((element) => {\n const kind = kindOf(element.node)\n const root = element.id === CANVAS_ROOT_ELEMENT_ID\n if (!kinds[kind]) kinds[kind] = aiPageContentKind(kind, { root })\n if (!settable.has(kind)) settable.set(kind, new Set(Object.keys(kinds[kind].props)))\n return elementView(element, settable.get(kind) as ReadonlySet<string>)\n })\n return { total: order.length, elements, kinds }\n}\n\n// ── Reading the page ──────────────────────────────────────────────────────\n\nconst NO_PAGE = (): PageContentRefusal => refusal(404, 'page_not_found', 'No such page')\nconst EMPTY_PAGE = (): PageContentRefusal =>\n refusal(404, 'page_empty', 'That page has no saved content to read or edit yet. Open it in the editor first.')\n\n/** The page a read or an edit names, with the version it points at. */\ninterface PageInHand {\n pageRef: FirebaseFirestore.DocumentReference\n versionId: string\n version: FirebaseFirestore.DocumentSnapshot\n draft: FirebaseFirestore.DocumentSnapshot\n}\n\n/**\n * An ordinary page of the site — not deleted, not an email design, a\n * template, an error page or a folder (`screenClaimsToBeAPage`, the rule\n * every page list holds to), and a layout is not in this collection at all —\n * with its current version and that version's draft.\n */\nasync function readPage(\n firestore: Firestore,\n input: { orgId: string; hostId: string; pageId: string },\n): Promise<PageInHand | PageContentRefusal> {\n const hostRef = firestore.collection('hosts').doc(input.hostId)\n const pageRef = hostRef.collection('screens').doc(input.pageId)\n const [host, page] = await Promise.all([hostRef.get(), pageRef.get()])\n // A site of another workspace holds no page of this one. The door that\n // calls has admitted the site already, so this only guards the pairing.\n if (!host.exists || host.get('orgId') !== input.orgId) return NO_PAGE()\n if (!page.exists || !screenClaimsToBeAPage(page.data() as never)) return NO_PAGE()\n const versionId = typeof page.get('versionId') === 'string' ? (page.get('versionId') as string) : ''\n if (!versionId) return EMPTY_PAGE()\n const versions = pageRef.collection('versions')\n const [version, draft] = await Promise.all([versions.doc(versionId).get(), draftRef(versions, versionId).get()])\n if (!version.exists) return EMPTY_PAGE()\n return { pageRef, versionId, version, draft }\n}\n\nexport async function readAiPageContent(input: PageContentReadInput): Promise<PageContentRead | PageContentRefusal> {\n const firestore = input.firestore as Firestore\n const page = await readPage(firestore, input)\n if ('ok' in page) return page\n const base = aiEditBase(page.draft, page.version)\n if (!base) return EMPTY_PAGE()\n const content = aiPageContentElements(base.nodes, input.elementId)\n if (!content) {\n return input.elementId !== undefined && aiDocumentElements(base.nodes)\n ? refusal(404, 'element_not_found', 'No such element on this page', { elementId: 'is not an element of this page' })\n : EMPTY_PAGE()\n }\n return {\n ok: true,\n pageId: input.pageId,\n versionId: page.versionId,\n base: base.from,\n revision: aiPageContentRevision(base.from, page.versionId, base.stored),\n rootId: CANVAS_ROOT_ELEMENT_ID,\n total: content.total,\n elements: content.elements,\n kinds: content.kinds,\n }\n}\n\n// ── Edits, held to the editor's rules ─────────────────────────────────────\n\n/** Props an edit here never names: markup, styles and handlers, which no field of an element offers. */\nconst UNSETTABLE_PROP = /^(html|sx|style|className|dangerouslySetInnerHTML|on[A-Z].*)$/\n\n/** The words a refused element is named with. */\nconst ELEMENT_REFUSALS: Readonly<Record<AssistEditClosedWorldRefusal, string>> = {\n unknown: 'is not an element of this page',\n root: 'is the page’s root, which cannot be changed, moved or removed',\n removed: 'is inside an element an earlier edit removes',\n}\n\nconst UNSETTABLE_WORDS = 'cannot be set through the API; send text in `children` to replace rich text'\n\n/** The whole page as the editor's closed world: every element, its kind, its place and its settings. */\nfunction wholeContext(order: readonly AiDocumentElement[]): AssistEditCanvasContext {\n const nodes: AssistEditCanvasNode[] = order.map(({ id, parentId, index, childCount, node }) => ({\n id,\n componentId: typeof node['componentId'] === 'string' ? node['componentId'] : '',\n parentId,\n index,\n childCount,\n ...(isRecord(node['props']) ? { props: node['props'] as AssistEditCanvasNode['props'] } : {}),\n }))\n return { selectedId: null, total: nodes.length, nodes, whole: true }\n}\n\n/** Where each element of one insert sits in the request, by the local id it is validated under. */\ntype InsertPaths = Map<string, { path: string; kind: string }>\n\ninterface ParsedApiEdits {\n pending: PendingEditOp[]\n /** The edit each pending op came from. */\n edits: number[]\n /** Each insert's element paths, by the edit's index. */\n inserts: Map<number, InsertPaths>\n fields: Record<string, string>\n}\n\n/** The local id an inserted element is validated under: its path among the request's nested elements. */\nconst localId = (steps: readonly number[]) => ['el', ...steps].join('-')\n\n/**\n * The API's edits as the editor's pending ops, through the one closed world\n * (`assistEditClosedWorld`), with every problem the request itself carries\n * named by edit and member.\n */\nfunction parseApiEdits(edits: readonly PageContentEdit[], context: AssistEditCanvasContext): ParsedApiEdits {\n const world = assistEditClosedWorld(context)\n const parsed: ParsedApiEdits = { pending: [], edits: [], inserts: new Map(), fields: {} }\n const { fields } = parsed\n const element = (at: string, nodeId: unknown): AssistEditCanvasNode | null => {\n const found = world.element(nodeId)\n if (typeof found !== 'string') return found\n fields[at] = ELEMENT_REFUSALS[found]\n return null\n }\n const parent = (at: string, parentId: unknown): AssistEditCanvasNode | null => {\n const found = world.parent(parentId)\n if (!found) fields[at] = typeof parentId === 'string' && world.byId.has(parentId) ? ELEMENT_REFUSALS.removed : ELEMENT_REFUSALS.unknown\n return found\n }\n const unsettable = (at: string, props: Record<string, unknown>): boolean => {\n let found = false\n for (const name of Object.keys(props)) {\n if (!UNSETTABLE_PROP.test(name)) continue\n fields[`${at}.${name}`] = UNSETTABLE_WORDS\n found = true\n }\n return found\n }\n const push = (index: number, op: PendingEditOp) => {\n parsed.pending.push(op)\n parsed.edits.push(index)\n }\n\n edits.forEach((edit, index) => {\n const at = `edits[${index}]`\n switch (edit.op) {\n case 'updateProps': {\n const node = element(`${at}.elementId`, edit.elementId)\n const props = isRecord(edit.props) ? edit.props : {}\n if (!Object.keys(props).length) fields[`${at}.props`] = 'sets no property'\n if (unsettable(`${at}.props`, props) || !node || !Object.keys(props).length) return\n push(index, { op: 'updateProps', nodeId: node.id, componentId: node.componentId, props })\n return\n }\n case 'updateStyle': {\n const node = element(`${at}.elementId`, edit.elementId)\n const style = isRecord(edit.style) ? edit.style : {}\n if (!Object.keys(style).length) fields[`${at}.style`] = 'sets no style'\n if (!node || !Object.keys(style).length) return\n push(index, { op: 'updateSx', nodeId: node.id, componentId: node.componentId, sx: style })\n return\n }\n case 'rename': {\n const node = element(`${at}.elementId`, edit.elementId)\n const named = typeof edit.name === 'string' ? assistEditLayerNameRefusal(edit.name) : 'is not text'\n if (named) fields[`${at}.name`] = named\n if (!node || named) return\n push(index, { op: 'rename', nodeId: node.id, componentId: node.componentId, name: edit.name })\n return\n }\n case 'remove': {\n const node = element(`${at}.elementId`, edit.elementId)\n if (!node) return\n world.remove(node.id)\n push(index, { op: 'remove', nodeId: node.id, componentId: node.componentId })\n return\n }\n case 'move': {\n const node = element(`${at}.elementId`, edit.elementId)\n const into = parent(`${at}.parentId`, edit.parentId)\n if (!node || !into) return\n if (world.movesInsideItself(node.id, into.id)) {\n fields[`${at}.parentId`] = 'is inside the element being moved'\n return\n }\n world.move(node.id, into.id)\n push(index, {\n op: 'move',\n nodeId: node.id,\n componentId: node.componentId,\n parentId: into.id,\n parentComponentId: into.componentId,\n index: edit.index,\n })\n return\n }\n case 'insert': {\n const into = parent(`${at}.parentId`, edit.parentId)\n const paths: InsertPaths = new Map()\n const nodes: Record<string, Record<string, unknown>> = {}\n let refused = false\n const visit = (raw: PageContentNewElement, steps: number[], path: string) => {\n const id = localId(steps)\n paths.set(id, { path, kind: raw.kind })\n const props = isRecord(raw.props) ? raw.props : {}\n if (unsettable(`${path}.props`, props)) refused = true\n if (raw.name !== undefined) {\n const named = assistEditLayerNameRefusal(raw.name)\n if (named) {\n fields[`${path}.name`] = named\n refused = true\n }\n }\n const children = Array.isArray(raw.children) ? raw.children : []\n nodes[id] = {\n $id: id,\n componentId: raw.kind,\n nodes: children.map((_, child) => localId([...steps, child])),\n props,\n ...(raw.style !== undefined ? { sx: raw.style } : {}),\n ...(raw.name !== undefined ? { name: raw.name } : {}),\n }\n children.forEach((child, position) => visit(child, [...steps, position], `${path}.children[${position}]`))\n }\n visit(edit.element, [], `${at}.element`)\n if (paths.size > ASSIST_EDIT_MAX_INSERT_NODES) {\n fields[`${at}.element`] = `adds ${paths.size} elements; one insert adds at most ${ASSIST_EDIT_MAX_INSERT_NODES}`\n return\n }\n if (!into || refused) return\n parsed.inserts.set(index, paths)\n push(index, {\n op: 'insertSubtree',\n parentId: into.id,\n parentComponentId: into.componentId,\n index: typeof edit.index === 'number' ? edit.index : null,\n tree: { rootId: localId([]), nodes },\n })\n return\n }\n default:\n fields[`${at}.op`] = 'is not an edit this API makes: updateProps, updateStyle, rename, insert, move or remove'\n }\n })\n return parsed\n}\n\n/** The validator's line, in the words a field is named with. */\nfunction reasonOf(text: string): string {\n return text\n .replace(/; (dropped|truncated|recomputed)$/, '')\n .replace(/^was over (\\d+) characters$/, 'is longer than $1 characters')\n .replace(/^is not a prop of /, 'is not a property of ')\n .replace(/; normalized to \"([^\"]*)\"$/, '; write \"$1\"')\n .trim()\n}\n\nconst escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\n/**\n * One violation, named by the edit and the member it is in. A repair line\n * names the element the validator was given — the kind, for a patch; the\n * local id, for an inserted element — and the setting, which is read back\n * off it.\n */\nfunction placeViolation(\n violation: AssistEditViolation,\n edit: PageContentEdit,\n at: string,\n paths: InsertPaths | undefined,\n kindOfElement: (elementId: string) => string,\n): [member: string, reason: string] {\n const { message } = violation\n if (edit.op === 'updateProps') {\n const subject = `${escapeRegExp(kindOfElement(edit.elementId))}\\\\.`\n const names = Object.keys(edit.props ?? {}).sort((a, b) => b.length - a.length)\n for (const name of names) {\n const repaired = new RegExp(`^${subject}${escapeRegExp(name)}:? (.*)$`).exec(message)\n if (repaired) return [`${at}.props.${name}`, reasonOf(repaired[1])]\n if (message.startsWith(`${name} `)) return [`${at}.props.${name}`, reasonOf(message.slice(name.length + 1))]\n }\n return [`${at}.props`, reasonOf(message)]\n }\n if (edit.op === 'updateStyle') {\n const repaired = /: sx\\.([A-Za-z]+)((?:\\.[A-Za-z]+)?) (.*)$/.exec(message)\n if (repaired) return [`${at}.style.${repaired[1]}${repaired[2]}`, reasonOf(repaired[3])]\n return [`${at}.style`, reasonOf(message)]\n }\n if (edit.op === 'move') return [`${at}.parentId`, reasonOf(message)]\n if (edit.op === 'insert' && paths) {\n const ids = [...paths.keys()].sort((a, b) => b.length - a.length)\n const named = (text: string) =>\n ids\n .reduce((out, id) => out.replace(new RegExp(`\\\\b${escapeRegExp(id)}\\\\b(?!-)`, 'g'), paths.get(id)?.path ?? id), text)\n .replace(/\\bchain-\\d+\\b/g, 'the element it is added into')\n .replace(new RegExp(escapeRegExp(CANVAS_ROOT_ELEMENT_ID), 'g'), 'the page’s root')\n for (const id of ids) {\n const path = paths.get(id)?.path as string\n const prop = new RegExp(`^${escapeRegExp(id)}\\\\.([A-Za-z_][A-Za-z0-9_]*)(?:\\\\.[A-Za-z0-9_]+)?:? (.*)$`).exec(message)\n if (prop) return [`${path}.${prop[1] === 'hidden' ? 'hidden' : `props.${prop[1]}`}`, reasonOf(named(prop[2]))]\n const style = new RegExp(`^${escapeRegExp(id)}: sx\\\\.([A-Za-z]+)((?:\\\\.[A-Za-z]+)?) (.*)$`).exec(message)\n if (style) return [`${path}.style.${style[1]}${style[2]}`, reasonOf(named(style[3]))]\n if (new RegExp(`\\\\(${escapeRegExp(id)}\\\\)|^${escapeRegExp(id)}\\\\b(?!-)`).test(message)) return [path, reasonOf(named(message))]\n }\n // An element the page's palette does not offer, as the palette or the\n // sanitizer under it words it.\n const component = /^Component \"([^\"]+)\" (?:is not in the palette|cannot be published)/.exec(message)\n if (component) {\n const found = [...paths.values()].find((entry) => entry.kind === component[1])\n if (found) return [`${found.path}.kind`, 'is not a kind of element a page takes']\n }\n return [`${at}.element`, reasonOf(named(message))]\n }\n return [at, reasonOf(message)]\n}\n\n/** What a built change is, or why the edits were refused. */\ntype BuiltEdit = { proposal: AssistEditProposal } | { refused: PageContentRefusal }\n\n/**\n * The edits validated against one tree and built into the editor's proposal,\n * or refused with every problem named. Pure: the write calls it with the tree\n * its transaction read, so what is checked is what is written.\n */\nexport function buildAiPageContentEdit(input: {\n base: Pick<AiEditWriteBase, 'from' | 'nodes' | 'stored'>\n pageId: string\n hostId: string\n versionId: string\n edits: readonly PageContentEdit[]\n ifRevision?: string\n screenIds: Iterable<string>\n mediaScopes: Iterable<string>\n datasets?: ReturnType<typeof aiEditDatasetScope>\n}): BuiltEdit {\n if (input.ifRevision !== undefined) {\n const current = aiPageContentRevision(input.base.from, input.versionId, input.base.stored)\n if (current !== input.ifRevision) {\n return {\n refused: refusal(409, 'stale', 'The page changed since that revision was read, so nothing was saved. Read it again.', {\n ifRevision: `is not the page’s current revision, ${current}`,\n }),\n }\n }\n }\n if (!input.edits.length || input.edits.length > ASSIST_EDIT_MAX_OPS) {\n return {\n refused: refusal(422, 'edit_refused', 'The edits could not be saved, so none were.', {\n edits: `holds ${input.edits.length}; send 1 to ${ASSIST_EDIT_MAX_OPS} edits`,\n }),\n }\n }\n const order = aiDocumentElements(input.base.nodes)\n if (!order) return { refused: EMPTY_PAGE() }\n const context = wholeContext(order)\n // The kind each element was validated as, which a patch's repair lines name.\n const kinds = new Map(context.nodes.map((node) => [node.id, node.componentId]))\n const parsed = parseApiEdits(input.edits, context)\n const validated = validatePendingEdit({\n surface: 'screen',\n context,\n pending: parsed.pending,\n strict: true,\n references: { screenIds: input.screenIds, mediaScopes: input.mediaScopes },\n ...(input.datasets ? { datasets: input.datasets } : {}),\n })\n const fields = { ...parsed.fields }\n for (const violation of validated.violations) {\n const index = parsed.edits[violation.position]\n const [member, reason] = placeViolation(violation, input.edits[index], `edits[${index}]`, parsed.inserts.get(index), (id) =>\n kinds.get(id) ?? '',\n )\n fields[member] = fields[member] ? `${fields[member]}; ${reason}` : reason\n }\n if (Object.keys(fields).length || validated.ops.length !== input.edits.length) {\n return { refused: refusal(422, 'edit_refused', 'The edits could not be saved, so none were. `fields` names each problem.', fields) }\n }\n return {\n proposal: {\n id: ASSIST_EDIT_ACTION_ID,\n summary: API_EDIT_SUMMARY,\n ops: validated.ops,\n diff: summarizeAssistEditOps(validated.ops),\n dropped: [],\n target: { kind: 'screen', documentId: input.pageId, versionId: input.versionId, hostId: input.hostId },\n },\n }\n}\n\n// ── Writing them ──────────────────────────────────────────────────────────\n\nexport interface AiPageContentDeps {\n writeEdit?: typeof writeAiEdit\n readDatasets?: typeof readAiSiteDatasets\n clearMirror?: typeof clearAiEditMirror\n now?: () => Date\n}\n\n/** The site's pages a link may name: every ordinary page, as a page list holds them. */\nasync function sitePageIds(firestore: Firestore, hostId: string): Promise<string[]> {\n const pages = await firestore.collection('hosts').doc(hostId).collection('screens').select('deletedAt', 'kind').get()\n return pages.docs.filter((page) => screenClaimsToBeAPage(page.data() as never)).map((page) => page.id)\n}\n\n/** A write's own failures, as the statuses an API answers. */\nfunction writeRefusal(error: string, tooLarge?: { bytes: number }): PageContentRefusal {\n if (tooLarge) {\n return refusal(413, 'page_too_large', `${AI_EDIT_TOO_LARGE_COPY} It would be ${tooLarge.bytes} bytes; a page holds at most ${NODE_MAP_MAX_BYTES}.`)\n }\n if (error === AI_EDIT_GONE_COPY) return NO_PAGE()\n if (error === AI_EDIT_NO_NODES_COPY) return EMPTY_PAGE()\n if (error === AI_EDIT_STALE_COPY || error === AI_EDIT_VERSION_GONE_COPY) {\n return refusal(409, 'stale', 'The page changed while the edits were being saved, so nothing was saved. Read it again.')\n }\n return refusal(422, 'edit_refused', 'The editor refused part of these edits, so none were saved.')\n}\n\nexport function createAiPageContentEditor(deps: AiPageContentDeps = {}) {\n const writeEdit = deps.writeEdit ?? writeAiEdit\n const readDatasets = deps.readDatasets ?? readAiSiteDatasets\n const clearMirror = deps.clearMirror ?? clearAiEditMirror\n return async function editAiPageContent(input: PageContentEditInput): Promise<PageContentEditResult | PageContentRefusal> {\n const firestore = input.firestore as Firestore\n if (!Array.isArray(input.edits) || !input.edits.length || input.edits.length > ASSIST_EDIT_MAX_OPS) {\n return refusal(422, 'edit_refused', 'The edits could not be saved, so none were.', {\n edits: `send 1 to ${ASSIST_EDIT_MAX_OPS} edits`,\n })\n }\n const page = await readPage(firestore, input)\n if ('ok' in page) return page\n const [screenIds, datasets] = await Promise.all([\n sitePageIds(firestore, input.hostId),\n readDatasets(input.orgId, input.hostId),\n ])\n const scope = aiEditDatasetScope(datasets, { kind: 'screen', id: input.pageId })\n const write = await writeEdit<PageContentRefusal>(firestore, {\n hostId: input.hostId,\n kind: 'screen',\n id: input.pageId,\n sourceVersionId: page.versionId,\n jobVersionId: input.editId,\n // Always the version's draft: never a new version, never the search\n // fields, so nothing a visitor sees and nothing on the page moves.\n versioning: false,\n newVersion: false,\n writeSeo: false,\n versionName: API_EDIT_SUMMARY,\n uid: input.actor.uid ?? AI_PAGE_CONTENT_API_ACTOR,\n updatedByLabel: input.actor.label,\n maxNodeBytes: NODE_MAP_MAX_BYTES,\n aiJobId: input.editId,\n now: (deps.now ?? (() => new Date()))(),\n proposal: (base) => {\n // The version the page points at moved since the read: the draft the\n // edits were asked of is no longer the page's.\n if (base.pointerVersionId !== page.versionId) {\n return { refused: refusal(409, 'stale', 'The page changed since it was read, so nothing was saved. Read it again.') }\n }\n const built = buildAiPageContentEdit({\n base,\n pageId: input.pageId,\n hostId: input.hostId,\n versionId: page.versionId,\n edits: input.edits,\n ...(input.ifRevision !== undefined ? { ifRevision: input.ifRevision } : {}),\n screenIds,\n mediaScopes: input.mediaScopes,\n datasets: scope,\n })\n return 'proposal' in built ? built.proposal : built\n },\n })\n if (write.ok === false) return write.refused ?? writeRefusal(write.error, write.tooLarge)\n if (write.placement === 'draft') {\n await clearMirror({ orgId: input.orgId, hostId: input.hostId, kind: 'screen', id: input.pageId, versionId: write.versionId }).catch(\n (error: unknown) => console.warn('[page content] the co-edit mirror could not be cleared', { pageId: input.pageId, error }),\n )\n }\n // A write asked again finds what it wrote and writes nothing; its\n // revision is the draft's as it stands.\n const revision = write.written\n ? aiPageContentRevision('draft', write.versionId, write.written.stored)\n : await readAiPageContent({ firestore, orgId: input.orgId, hostId: input.hostId, pageId: input.pageId }).then((read) =>\n read.ok ? read.revision : '',\n )\n return {\n ok: true,\n pageId: input.pageId,\n versionId: write.versionId,\n revision,\n applied: input.edits.length,\n created: (write.written?.inserted ?? []).map(({ op, ids }) => ({ index: op, id: ids[0], ids })),\n }\n }\n}\n\n/** The contract's implementation, as the plugin registers it. */\nexport const aiPageContentService: PageContentService = {\n read: readAiPageContent,\n editDraft: createAiPageContentEditor(),\n}\n\n"],"names":["createHash","NODE_MAP_MAX_BYTES","screenClaimsToBeAPage","CANVAS_ROOT_ELEMENT_ID","aiEditBase","aiEditDatasetScope","clearAiEditMirror","draftRef","writeAiEdit","AI_EDIT_GONE_COPY","AI_EDIT_NO_NODES_COPY","AI_EDIT_STALE_COPY","AI_EDIT_TOO_LARGE_COPY","AI_EDIT_VERSION_GONE_COPY","aiDocumentElements","ASSIST_EDIT_ACTION_ID","summarizeAssistEditOps","AI_REPEAT_DATASET_PROP","AI_SX_ALLOWED_KEYS","aiPaletteEntryWithCapabilities","aiPropIsIconPick","AI_PALETTE","readAiSiteDatasets","ASSIST_EDIT_MAX_INSERT_NODES","ASSIST_EDIT_MAX_OPS","ASSIST_EDIT_MOTION_SETTINGS","assistEditClosedWorld","assistEditLayerNameRefusal","validatePendingEdit","AI_PAGE_CONTENT_API_ACTOR","API_EDIT_SUMMARY","isRecord","value","Array","isArray","refusal","status","code","message","fields","ok","Object","keys","length","canonicalJson","map","join","sort","key","JSON","stringify","aiPageContentRevision","from","versionId","stored","hash","update","Uint8Array","digest","slice","kindOf","node","aiPageContentKindProps","kind","entry","props","name","schema","entries","propsSchema","properties","role","propRoles","maxLength","textLimits","type","enum","values","undefined","allowed","aiPageContentKind","options","label","root","displayName","acceptsChildren","READ_ONLY_NODE_FIELDS","elementView","element","settable","readOnlyProps","has","style","readOnlyStyle","readOnly","interactions","filter","field","id","pluginId","parentId","children","hidden","aiPageContentElements","nodes","elementId","order","chosen","start","findIndex","inside","Set","add","push","kinds","Map","elements","set","get","total","NO_PAGE","EMPTY_PAGE","readPage","firestore","input","hostRef","collection","doc","hostId","pageRef","pageId","host","page","Promise","all","exists","orgId","data","versions","version","draft","readAiPageContent","base","content","revision","rootId","UNSETTABLE_PROP","ELEMENT_REFUSALS","unknown","removed","UNSETTABLE_WORDS","wholeContext","index","childCount","componentId","selectedId","whole","localId","steps","parseApiEdits","edits","context","world","parsed","pending","inserts","at","nodeId","found","parent","byId","unsettable","test","op","forEach","edit","sx","named","remove","into","movesInsideItself","move","parentComponentId","paths","refused","visit","raw","path","$id","_","child","position","size","tree","reasonOf","text","replace","trim","escapeRegExp","placeViolation","violation","kindOfElement","subject","names","a","b","repaired","RegExp","exec","startsWith","ids","reduce","out","prop","component","find","buildAiPageContentEdit","ifRevision","current","validated","surface","strict","references","screenIds","mediaScopes","datasets","violations","member","reason","ops","proposal","summary","diff","dropped","target","documentId","sitePageIds","pages","select","docs","writeRefusal","error","tooLarge","bytes","createAiPageContentEditor","deps","writeEdit","readDatasets","clearMirror","editAiPageContent","write","scope","sourceVersionId","jobVersionId","editId","versioning","newVersion","writeSeo","versionName","uid","actor","updatedByLabel","maxNodeBytes","aiJobId","now","Date","pointerVersionId","built","placement","catch","console","warn","written","then","read","applied","created","inserted","aiPageContentService","editDraft"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,cAAa;AACxC,SAASC,kBAAkB,QAAQ,0CAAyC;AAC5E,SAASC,qBAAqB,QAAQ,sCAAqC;AAC3E,SAASC,sBAAsB,QAAQ,2CAA0C;AAcjF,SACEC,UAAU,EACVC,kBAAkB,EAClBC,iBAAiB,EACjBC,QAAQ,EACRC,WAAW,QAEN,8BAA0B;AACjC,SACEC,iBAAiB,EACjBC,qBAAqB,EACrBC,kBAAkB,EAClBC,sBAAsB,EACtBC,yBA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WqM,MAAMrM,SAAS;YAAC,GAAGwN,KAAK,CACjI,CAAC5B,QAAmB6B,QAAQC,IAAI,CAAC,0DAA0D;oBAAE7I,QAAQN,MAAMM,MAAM;oBAAE+G;gBAAM;QAE7H;QACA,kEAAkE;QAClE,wCAAwC;QACxC,MAAMjG,WAAW0G,MAAMsB,OAAO,GAC1B7N,sBAAsB,SAASuM,MAAMrM,SAAS,EAAEqM,MAAMsB,OAAO,CAAC1N,MAAM,IACpE,MAAMuF,kBAAkB;YAAElB;YAAWa,OAAOZ,MAAMY,KAAK;YAAER,QAAQJ,MAAMI,MAAM;YAAEE,QAAQN,MAAMM,MAAM;QAAC,GAAG+I,IAAI,CAAC,CAACC,OAC3GA,KAAK1O,EAAE,GAAG0O,KAAKlI,QAAQ,GAAG;QAEhC,OAAO;YACLxG,IAAI;YACJ0F,QAAQN,MAAMM,MAAM;YACpB7E,WAAWqM,MAAMrM,SAAS;YAC1B2F;YACAmI,SAASvJ,MAAMoC,KAAK,CAACrH,MAAM;YAC3ByO,SAAS,UAAC1B,iBAAAA,MAAMsB,OAAO,qBAAbtB,eAAe2B,QAAQ,mBAAI,EAAE,EAAExO,GAAG,CAAC,CAAC,EAAEgI,EAAE,EAAEqC,GAAG,EAAE,GAAM,CAAA;oBAAE1D,OAAOqB;oBAAI3E,IAAIgH,GAAG,CAAC,EAAE;oBAAEA;gBAAI,CAAA;QAC9F;IACF;AACF;AAEA,+DAA+D,GAC/D,OAAO,MAAMoE,uBAA2C;IACtDJ,MAAMrI;IACN0I,WAAWnC;AACb,EAAC"}
@@ -19,7 +19,7 @@ import { aiUsageMonthKeys, aiUsageMonthWithinRetention, aiUsageShare } from "../
19
19
  import { readOrgAiUsageByUser, readUserAiUsageMonths } from "../usage/ai-usage-by-user.js";
20
20
  import { FieldValue } from "firebase-admin/firestore";
21
21
  import { invalidIdTokenResponse } from "@aglyn/tenant-data-admin/server/id-token-refusal";
22
- import { AI_USAGE_CSV_HEADER, AI_USAGE_EXPORT_ROWS_HEADER, aiUsageCsvLine, toAiUsageWireRow } from "../usage/ai-usage-wire.js";
22
+ import { AI_USAGE_CSV_HEADER, AI_USAGE_EXPORT_ROWS_HEADER, aiUsageCsvLine, aiUsageHostCells, toAiUsageWireRow } from "../usage/ai-usage-wire.js";
23
23
  import { addAdminAudit } from "@aglyn/tenant-data-admin/server/admin-audit-write";
24
24
  // lockdown-423: exempt — a READ-ONLY usage report that writes nothing to the
25
25
  // workspace, the posture of ai/billing/credits beside it: a billing-locked
@@ -147,12 +147,18 @@ async function handler(request) {
147
147
  });
148
148
  }
149
149
  if (format !== 'csv') {
150
+ var _params_view;
150
151
  const table = {
151
152
  month,
152
153
  months,
153
154
  orgCredits: usage.orgCredits,
154
155
  rows
155
156
  };
157
+ // The apps' collaborators column: one cell per asked person.
158
+ if (hostId && String((_params_view = params['view']) != null ? _params_view : '') === 'prepared') {
159
+ var _params_uids;
160
+ table.hostCells = aiUsageHostCells(rows, String((_params_uids = params['uids']) != null ? _params_uids : '').split(','));
161
+ }
156
162
  return json(table, 200);
157
163
  }
158
164
  /*
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-usage.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 { csvCell, pluginRequestFromWeb } from '@aglyn/aglyn/server'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n isImpersonationSession,\n memberHasOrgPermission,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport {\n aiUsageMonthKeys,\n aiUsageMonthWithinRetention,\n aiUsageShare,\n type AiUsageByUserMonth,\n} from '../model/ai-usage-by-user'\nimport {\n readOrgAiUsageByUser,\n readUserAiUsageMonths,\n} from '../usage/ai-usage-by-user'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport {\n AI_USAGE_CSV_HEADER,\n AI_USAGE_EXPORT_ROWS_HEADER,\n aiUsageCsvLine,\n toAiUsageWireRow,\n type OrgAiUsageTableWire,\n type UserAiUsageWire,\n} from '../usage/ai-usage-wire'\nimport { addAdminAudit } from '@aglyn/tenant-data-admin/server/admin-audit-write'\n\n// lockdown-423: exempt — a READ-ONLY usage report that writes nothing to the\n// workspace, the posture of ai/billing/credits beside it: a billing-locked\n// owner working out who spent the credits needs this table more, not less.\n\n/**\n * WHO IS GENERATING WHAT, PER SITE (AGL-2928) — the customer's read of the\n * per-user AI usage rollup.\n *\n * ## Three questions, one route\n *\n * - **The month's table** (`orgId`, `month`): every current member with a\n * month document, dearest first, with each person's share of the\n * workspace's spend. Gated on `billing.view`, the Usage page's gate, and\n * served as JSON or — `format=csv` — as a streamed file.\n * - **One person** (`uid`): that person's months, newest first, for the\n * member detail card. The subject reads their own; anyone else needs\n * `billing.view` or `org.auditLog`, which is the team page's gate and the\n * pair the security rules admit for the same documents.\n * - **One site** (`hostId`): the table with each row's credits ON THAT SITE\n * beside it, for the site's collaborators card — the agency question,\n * \"which client site's collaborators spend\".\n *\n * ## No dollar figure crosses this boundary\n *\n * The month document carries `estCostUsd`, our provider bill. The rows here\n * carry credits and a SHARE, and the share is computed on the dollars\n * server-side (`aiUsageShare`) so it is exact — a roster's credits each round\n * up, the org's round once — without the dollars ever being serialized.\n *\n * ## The month bound\n *\n * `month` must be inside the retention window (`aiUsageMonthKeys`): a\n * request for an older month is refused rather than answered empty, because\n * \"nothing for that month\" and \"that month has been reaped\" must not read\n * the same on a report somebody exports.\n */\n\n/** The most months one person's card is handed. */\nconst MAX_USER_MONTHS = 13\n\nconst json = (body: unknown, status: number) => Response.json(body, { status })\n\nasync function handler(request: Request): Promise<Response> {\n const { method, query, headers: rawHeaders } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'GET') return json({ error: 'Method not allowed' }, 405)\n\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return json({ error: 'Unauthenticated' }, 401)\n\n const params = (query ?? {}) as Record<string, unknown>\n const orgId = String(params['orgId'] ?? '').trim()\n if (!orgId) return json({ error: 'Missing orgId' }, 400)\n const now = new Date()\n const months = aiUsageMonthKeys(now)\n const month = String(params['month'] ?? months[0]).trim()\n if (!aiUsageMonthWithinRetention(month, now)) {\n return json(\n {\n error:\n `AI usage is kept for ${months.length} months; ` +\n `ask for one of ${months[months.length - 1]} through ${months[0]}.`,\n },\n 400,\n )\n }\n const subjectUid = String(params['uid'] ?? '').trim()\n const hostId = String(params['hostId'] ?? '').trim()\n const format = String(params['format'] ?? 'json').trim()\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n const staff = decoded['staff'] === true\n const membership = await resolveOrgMembership(decoded.uid, orgId)\n const member = membership?.member\n if (!member && !staff) return json({ error: 'Not found' }, 404)\n\n const firestore = firebaseAdmin.app().firestore()\n\n if (subjectUid) {\n // One person. Their own months are theirs to read; anyone else's need\n // the Usage page's permission or the team page's.\n const own = subjectUid === decoded.uid && Boolean(member)\n if (!own && !staff) {\n const allowed =\n (await memberHasOrgPermission(orgId, member, 'billing.view')) ||\n (await memberHasOrgPermission(orgId, member, 'org.auditLog'))\n if (!allowed) return json({ error: 'billing.view required' }, 403)\n }\n const limit = Math.min(\n MAX_USER_MONTHS,\n Math.max(1, Math.floor(Number(params['limit'] ?? 2) || 2)),\n )\n const rows = await readUserAiUsageMonths(firestore, orgId, subjectUid, limit)\n const orgRef = firestore.collection('orgs').doc(orgId)\n const rollups = rows.length\n ? await firestore.getAll(\n ...rows.map((row) => orgRef.collection('assistUsage').doc(row.month)),\n )\n : []\n const wire: UserAiUsageWire = {\n uid: subjectUid,\n months: rows.map((row: AiUsageByUserMonth, index) => ({\n month: row.month,\n credits: row.credits,\n share: aiUsageShare(\n row.estCostUsd,\n Number(rollups[index]?.get('estCostUsd') ?? 0),\n ),\n requests: row.requests,\n refusals: row.refusals,\n byKind: row.byKind,\n byHost: row.byHost,\n })),\n }\n return json(wire, 200)\n }\n\n // The table, which is about everyone: the Usage page's permission.\n if (!staff && !(await memberHasOrgPermission(orgId, member, 'billing.view'))) {\n return json({ error: 'billing.view required' }, 403)\n }\n const usage = await readOrgAiUsageByUser(firestore, orgId, month)\n const rows = usage.rows.map((row) => toAiUsageWireRow(row, hostId))\n if (hostId) {\n rows.sort(\n (a, b) =>\n (b.hostCredits ?? 0) - (a.hostCredits ?? 0) || b.credits - a.credits,\n )\n }\n\n if (format !== 'csv') {\n const table: OrgAiUsageTableWire = {\n month,\n months,\n orgCredits: usage.orgCredits,\n rows,\n }\n return json(table, 200)\n }\n\n /*\n * The file, streamed: the header first, then the rows in pages, so a\n * roster of any size arrives without being held whole. The row count\n * travels in a header the client checks the body against — a stream\n * that dies halfway yields a well-formed shorter file, and nothing about\n * the bytes says it is short.\n */\n const encoder = new TextEncoder()\n const PAGE = 200\n let cursor = 0\n let headed = false\n const stream = new ReadableStream<Uint8Array>({\n pull(controller) {\n if (!headed) {\n headed = true\n controller.enqueue(encoder.encode(AI_USAGE_CSV_HEADER.map(csvCell).join(',')))\n return\n }\n if (cursor < rows.length) {\n const page = rows.slice(cursor, cursor + PAGE)\n cursor += page.length\n controller.enqueue(\n encoder.encode(`\\n${page.map(aiUsageCsvLine).join('\\n')}`),\n )\n return\n }\n controller.enqueue(encoder.encode('\\n'))\n controller.close()\n },\n })\n\n // Ids and counts only, never content: a report about people leaving\n // the platform is worth a row; who was in it is the workspace's own.\n void addAdminAudit(firestore, {\n actorUid: decoded.uid,\n action: 'ai-usage.exported',\n target: `orgs/${orgId}/aiUsageByUser`,\n before: null,\n after: { month, rows: rows.length, hostId: hostId || null },\n at: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n\n return new Response(stream, {\n status: 200,\n headers: {\n 'Content-Type': 'text/csv; charset=utf-8',\n 'Content-Disposition': `attachment; filename=\"ai-usage-${month}.csv\"`,\n [AI_USAGE_EXPORT_ROWS_HEADER]: String(rows.length),\n 'Cache-Control': 'no-store, private',\n },\n })\n } catch (error) {\n // A refused credential is a 401, not a fault of ours (AGL-1993). Null\n // for anything else, so a real failure keeps the answer below.\n const unauthenticated = invalidIdTokenResponse(error)\n if (unauthenticated) return unauthenticated\n console.error('[ai/usage] read failed', orgId, error)\n return json({ error: 'AI usage unavailable' }, 500)\n }\n}\n\nexport { handler as GET }\n"],"names":["csvCell","pluginRequestFromWeb","emailUnverifiedResponse","firebaseAdmin","isImpersonationSession","memberHasOrgPermission","resolveOrgMembership","aiUsageMonthKeys","aiUsageMonthWithinRetention","aiUsageShare","readOrgAiUsageByUser","readUserAiUsageMonths","FieldValue","invalidIdTokenResponse","AI_USAGE_CSV_HEADER","AI_USAGE_EXPORT_ROWS_HEADER","aiUsageCsvLine","toAiUsageWireRow","addAdminAudit","MAX_USER_MONTHS","json","body","status","Response","handler","request","headers","params","method","query","rawHeaders","error","authorization","idToken","startsWith","slice","length","undefined","orgId","String","trim","now","Date","months","month","subjectUid","hostId","format","decoded","app","auth","verifyIdToken","email_verified","staff","membership","uid","member","firestore","own","Boolean","allowed","limit","Math","min","max","floor","Number","rows","orgRef","collection","doc","rollups","getAll","map","row","wire","index","credits","share","estCostUsd","get","requests","refusals","byKind","byHost","usage","sort","a","b","hostCredits","table","orgCredits","encoder","TextEncoder","PAGE","cursor","headed","stream","ReadableStream","pull","controller","enqueue","encode","join","page","close","actorUid","action","target","before","after","at","serverTimestamp","catch","unauthenticated","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ACAH,WAAWC,OAAO,CAACT,QAAQU,MAAM,CAAC;gBAClCF,WAAWK,KAAK;YAClB;QACF;QAEA,oEAAoE;QACpE,qEAAqE;QACrE,KAAKvF,cAAcuC,WAAW;YAC5BiD,UAAU1D,QAAQO,GAAG;YACrBoD,QAAQ;YACRC,QAAQ,CAAC,KAAK,EAAEtE,MAAM,cAAc,CAAC;YACrCuE,QAAQ;YACRC,OAAO;gBAAElE;gBAAOuB,MAAMA,KAAK/B,MAAM;gBAAEU,QAAQA,UAAU;YAAK;YAC1DiE,IAAInG,WAAWoG,eAAe;QAChC,GACGC,KAAK,CAAC,IAAM5E;QAEf,OAAO,IAAId,SAAS0E,QAAQ;YAC1B3E,QAAQ;YACRI,SAAS;gBACP,gBAAgB;gBAChB,uBAAuB,CAAC,+BAA+B,EAAEkB,MAAM,KAAK,CAAC;gBACrE,CAAC7B,4BAA4B,EAAEwB,OAAO4B,KAAK/B,MAAM;gBACjD,iBAAiB;YACnB;QACF;IACF,EAAE,OAAOL,OAAO;QACd,sEAAsE;QACtE,+DAA+D;QAC/D,MAAMmF,kBAAkBrG,uBAAuBkB;QAC/C,IAAImF,iBAAiB,OAAOA;QAC5BC,QAAQpF,KAAK,CAAC,0BAA0BO,OAAOP;QAC/C,OAAOX,KAAK;YAAEW,OAAO;QAAuB,GAAG;IACjD;AACF;AAEA,SAASP,WAAW4F,GAAG,GAAE"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-usage.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 { csvCell, pluginRequestFromWeb } from '@aglyn/aglyn/server'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n isImpersonationSession,\n memberHasOrgPermission,\n resolveOrgMembership,\n} from '@aglyn/tenant-data-admin'\nimport {\n aiUsageMonthKeys,\n aiUsageMonthWithinRetention,\n aiUsageShare,\n type AiUsageByUserMonth,\n} from '../model/ai-usage-by-user'\nimport {\n readOrgAiUsageByUser,\n readUserAiUsageMonths,\n} from '../usage/ai-usage-by-user'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport {\n AI_USAGE_CSV_HEADER,\n AI_USAGE_EXPORT_ROWS_HEADER,\n aiUsageCsvLine,\n aiUsageHostCells,\n toAiUsageWireRow,\n type OrgAiUsageTableWire,\n type UserAiUsageWire,\n} from '../usage/ai-usage-wire'\nimport { addAdminAudit } from '@aglyn/tenant-data-admin/server/admin-audit-write'\n\n// lockdown-423: exempt — a READ-ONLY usage report that writes nothing to the\n// workspace, the posture of ai/billing/credits beside it: a billing-locked\n// owner working out who spent the credits needs this table more, not less.\n\n/**\n * WHO IS GENERATING WHAT, PER SITE (AGL-2928) — the customer's read of the\n * per-user AI usage rollup.\n *\n * ## Three questions, one route\n *\n * - **The month's table** (`orgId`, `month`): every current member with a\n * month document, dearest first, with each person's share of the\n * workspace's spend. Gated on `billing.view`, the Usage page's gate, and\n * served as JSON or — `format=csv` — as a streamed file.\n * - **One person** (`uid`): that person's months, newest first, for the\n * member detail card. The subject reads their own; anyone else needs\n * `billing.view` or `org.auditLog`, which is the team page's gate and the\n * pair the security rules admit for the same documents.\n * - **One site** (`hostId`): the table with each row's credits ON THAT SITE\n * beside it, for the site's collaborators card — the agency question,\n * \"which client site's collaborators spend\".\n *\n * ## No dollar figure crosses this boundary\n *\n * The month document carries `estCostUsd`, our provider bill. The rows here\n * carry credits and a SHARE, and the share is computed on the dollars\n * server-side (`aiUsageShare`) so it is exact — a roster's credits each round\n * up, the org's round once — without the dollars ever being serialized.\n *\n * ## The month bound\n *\n * `month` must be inside the retention window (`aiUsageMonthKeys`): a\n * request for an older month is refused rather than answered empty, because\n * \"nothing for that month\" and \"that month has been reaped\" must not read\n * the same on a report somebody exports.\n */\n\n/** The most months one person's card is handed. */\nconst MAX_USER_MONTHS = 13\n\nconst json = (body: unknown, status: number) => Response.json(body, { status })\n\nasync function handler(request: Request): Promise<Response> {\n const { method, query, headers: rawHeaders } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'GET') return json({ error: 'Method not allowed' }, 405)\n\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return json({ error: 'Unauthenticated' }, 401)\n\n const params = (query ?? {}) as Record<string, unknown>\n const orgId = String(params['orgId'] ?? '').trim()\n if (!orgId) return json({ error: 'Missing orgId' }, 400)\n const now = new Date()\n const months = aiUsageMonthKeys(now)\n const month = String(params['month'] ?? months[0]).trim()\n if (!aiUsageMonthWithinRetention(month, now)) {\n return json(\n {\n error:\n `AI usage is kept for ${months.length} months; ` +\n `ask for one of ${months[months.length - 1]} through ${months[0]}.`,\n },\n 400,\n )\n }\n const subjectUid = String(params['uid'] ?? '').trim()\n const hostId = String(params['hostId'] ?? '').trim()\n const format = String(params['format'] ?? 'json').trim()\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n const staff = decoded['staff'] === true\n const membership = await resolveOrgMembership(decoded.uid, orgId)\n const member = membership?.member\n if (!member && !staff) return json({ error: 'Not found' }, 404)\n\n const firestore = firebaseAdmin.app().firestore()\n\n if (subjectUid) {\n // One person. Their own months are theirs to read; anyone else's need\n // the Usage page's permission or the team page's.\n const own = subjectUid === decoded.uid && Boolean(member)\n if (!own && !staff) {\n const allowed =\n (await memberHasOrgPermission(orgId, member, 'billing.view')) ||\n (await memberHasOrgPermission(orgId, member, 'org.auditLog'))\n if (!allowed) return json({ error: 'billing.view required' }, 403)\n }\n const limit = Math.min(\n MAX_USER_MONTHS,\n Math.max(1, Math.floor(Number(params['limit'] ?? 2) || 2)),\n )\n const rows = await readUserAiUsageMonths(firestore, orgId, subjectUid, limit)\n const orgRef = firestore.collection('orgs').doc(orgId)\n const rollups = rows.length\n ? await firestore.getAll(\n ...rows.map((row) => orgRef.collection('assistUsage').doc(row.month)),\n )\n : []\n const wire: UserAiUsageWire = {\n uid: subjectUid,\n months: rows.map((row: AiUsageByUserMonth, index) => ({\n month: row.month,\n credits: row.credits,\n share: aiUsageShare(\n row.estCostUsd,\n Number(rollups[index]?.get('estCostUsd') ?? 0),\n ),\n requests: row.requests,\n refusals: row.refusals,\n byKind: row.byKind,\n byHost: row.byHost,\n })),\n }\n return json(wire, 200)\n }\n\n // The table, which is about everyone: the Usage page's permission.\n if (!staff && !(await memberHasOrgPermission(orgId, member, 'billing.view'))) {\n return json({ error: 'billing.view required' }, 403)\n }\n const usage = await readOrgAiUsageByUser(firestore, orgId, month)\n const rows = usage.rows.map((row) => toAiUsageWireRow(row, hostId))\n if (hostId) {\n rows.sort(\n (a, b) =>\n (b.hostCredits ?? 0) - (a.hostCredits ?? 0) || b.credits - a.credits,\n )\n }\n\n if (format !== 'csv') {\n const table: OrgAiUsageTableWire = {\n month,\n months,\n orgCredits: usage.orgCredits,\n rows,\n }\n // The apps' collaborators column: one cell per asked person.\n if (hostId && String(params['view'] ?? '') === 'prepared') {\n table.hostCells = aiUsageHostCells(rows, String(params['uids'] ?? '').split(','))\n }\n return json(table, 200)\n }\n\n /*\n * The file, streamed: the header first, then the rows in pages, so a\n * roster of any size arrives without being held whole. The row count\n * travels in a header the client checks the body against — a stream\n * that dies halfway yields a well-formed shorter file, and nothing about\n * the bytes says it is short.\n */\n const encoder = new TextEncoder()\n const PAGE = 200\n let cursor = 0\n let headed = false\n const stream = new ReadableStream<Uint8Array>({\n pull(controller) {\n if (!headed) {\n headed = true\n controller.enqueue(encoder.encode(AI_USAGE_CSV_HEADER.map(csvCell).join(',')))\n return\n }\n if (cursor < rows.length) {\n const page = rows.slice(cursor, cursor + PAGE)\n cursor += page.length\n controller.enqueue(\n encoder.encode(`\\n${page.map(aiUsageCsvLine).join('\\n')}`),\n )\n return\n }\n controller.enqueue(encoder.encode('\\n'))\n controller.close()\n },\n })\n\n // Ids and counts only, never content: a report about people leaving\n // the platform is worth a row; who was in it is the workspace's own.\n void addAdminAudit(firestore, {\n actorUid: decoded.uid,\n action: 'ai-usage.exported',\n target: `orgs/${orgId}/aiUsageByUser`,\n before: null,\n after: { month, rows: rows.length, hostId: hostId || null },\n at: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n\n return new Response(stream, {\n status: 200,\n headers: {\n 'Content-Type': 'text/csv; charset=utf-8',\n 'Content-Disposition': `attachment; filename=\"ai-usage-${month}.csv\"`,\n [AI_USAGE_EXPORT_ROWS_HEADER]: String(rows.length),\n 'Cache-Control': 'no-store, private',\n },\n })\n } catch (error) {\n // A refused credential is a 401, not a fault of ours (AGL-1993). Null\n // for anything else, so a real failure keeps the answer below.\n const unauthenticated = invalidIdTokenResponse(error)\n if (unauthenticated) return unauthenticated\n console.error('[ai/usage] read failed', orgId, error)\n return json({ error: 'AI usage unavailable' }, 500)\n }\n}\n\nexport { handler as GET }\n"],"names":["csvCell","pluginRequestFromWeb","emailUnverifiedResponse","firebaseAdmin","isImpersonationSession","memberHasOrgPermission","resolveOrgMembership","aiUsageMonthKeys","aiUsageMonthWithinRetention","aiUsageShare","readOrgAiUsageByUser","readUserAiUsageMonths","FieldValue","invalidIdTokenResponse","AI_USAGE_CSV_HEADER","AI_USAGE_EXPORT_ROWS_HEADER","aiUsageCsvLine","aiUsageHostCells","toAiUsageWireRow","addAdminAudit","MAX_USER_MONTHS","json","body","status","Response","handler","request","headers","params","method","query","rawHeaders","error","authorization","idToken","startsWith","slice","length","undefined","orgId","String","trim","now","Date","months","month","subjectUid","hostId","format","decoded","app","auth","verifyIdToken","email_verified","staff","membership","uid","member","firestore","own","Boolean","allowed","limit","Math","min","max","floor","Number","rows","orgRef","collection","doc","rollups","getAll","map","row","wire","index","credits","share","estCostUsd","get","requests","refusals","byKind","byHost","usage","sort","a","b","hostCredits","table","orgCredits","hostCells","split","encoder","TextEncoder","PAGE","cursor","headed","stream","ReadableStream","pull","controller","enqueue","encode","join","page","close","actorUid","action","target","before","after","at","serverTimestamp","catch","unauthenticated","console","GET"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,OAAO,EAAEC,oBAAoB,QAAQ,sBAAqB;AACnE,SACEC,uBAAuB,EACvBC,aAAa,EACbC,sBAAsB,EACtBC,sBAAsB,EACtBC,oBAAoB,QACf,2BAA0B;AACjC,SACEC,gBAAgB,EAChBC,2BAA2B,EAC3BC,YAAY,QAEP,+BAA2B;AAClC,SACEC,oBAAoB,EACpBC,qBAAqB,QAChB,+BAA2B;AAClC,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SACEC,mBAAmB,EACnBC,2BAA2B,EAC3BC,cAAc,EACdC,gBAAgB,EAChBC,gBAAgB,QAGX,4BAAwB;AAC/B,SAASC,aAAa,QAAQ,oDAAmD;AAEjF,6EAA6E;AAC7E,2EAA2E;AAC3E,2EAA2E;AAE3E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+BC,GAED,iDAAiD,GACjD,MAAMC,kBAAkB;AAExB,MAAMC,OAAO,CAACC,MAAeC,SAAmBC,SAASH,IAAI,CAACC,MAAM;QAAEC;IAAO;AAE7E,eAAeE,QAAQC,OAAgB;QAKfC,wBAODC,eAIAA,eAWKA,aACJA,gBACAA;IA5BtB,MAAM,EAAEC,MAAM,EAAEC,KAAK,EAAEH,SAASI,UAAU,EAAE,GAAG,MAAM9B,qBAAqByB;IAC1E,MAAMC,UAAUI;IAChB,IAAIF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;QACtE,+DAA+D;QAC/D,MAAMqF,kBAAkBxG,uBAAuBmB;QAC/C,IAAIqF,iBAAiB,OAAOA;QAC5BC,QAAQtF,KAAK,CAAC,0BAA0BO,OAAOP;QAC/C,OAAOX,KAAK;YAAEW,OAAO;QAAuB,GAAG;IACjD;AACF;AAEA,SAASP,WAAW8F,GAAG,GAAE"}
@@ -14,7 +14,9 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
- import { type AssistEditCanvasContext, type AssistEditDocumentKind, type AssistEditProposal, type AssistEditTarget } from '../model/assist-edit';
17
+ import { type ScreenSeoTextField } from '@aglyn/aglyn/app-utils/screen-seo-fields';
18
+ import { type NodeInteraction } from '@aglyn/aglyn/app-utils/node-interactions';
19
+ import { type AssistEditCanvasContext, type AssistEditCanvasNode, type AssistEditDocumentKind, type AssistEditOp, type AssistEditProposal, type AssistEditTarget } from '../model/assist-edit';
18
20
  import type { AiInventoryDataset } from '../model/ai-site-inventory';
19
21
  import type { AiTool } from '../providers/contract';
20
22
  import { type AiGenerationCheckResult } from '../runtime/ai-doctrine';
@@ -56,6 +58,8 @@ export declare const ASSIST_EDIT_MAX_OUTPUT_TOKENS = 4096;
56
58
  * own list, so the tool and the Screen Properties form cannot drift.
57
59
  */
58
60
  export declare function assistEditTool(kind: AssistEditDocumentKind): AiTool;
61
+ /** The motion settings every element takes and what each holds, for a reader that lists them (AGL-4235). */
62
+ export declare const ASSIST_EDIT_MOTION_SETTINGS: Readonly<Record<string, readonly string[] | number | 'switch'>>;
59
63
  /**
60
64
  * The line of the edit protocol that offers motion: a pure function of the
61
65
  * vocabulary, so it sits in the cached prefix with the rest of the block.
@@ -160,6 +164,106 @@ export declare const ASSIST_EDIT_MAX_DATASETS = 12;
160
164
  * block it follows, and empty where the site holds none.
161
165
  */
162
166
  export declare function editDatasetsBlock(datasets: readonly AssistEditDataset[]): string;
167
+ /** A structurally sound op, before its content has met the validators. */
168
+ export type PendingEditOp = {
169
+ op: 'insertSubtree';
170
+ parentId: string;
171
+ parentComponentId: string;
172
+ index: number | null;
173
+ tree: {
174
+ rootId: string;
175
+ nodes: Record<string, Record<string, unknown>>;
176
+ };
177
+ } | {
178
+ op: 'updateProps';
179
+ nodeId: string;
180
+ componentId: string;
181
+ props: Record<string, unknown>;
182
+ } | {
183
+ op: 'updateSx';
184
+ nodeId: string;
185
+ componentId: string;
186
+ sx: Record<string, unknown>;
187
+ } | {
188
+ op: 'move';
189
+ nodeId: string;
190
+ componentId: string;
191
+ parentId: string;
192
+ parentComponentId: string;
193
+ index: number | null;
194
+ } | {
195
+ op: 'remove';
196
+ nodeId: string;
197
+ componentId: string;
198
+ } | {
199
+ op: 'rename';
200
+ nodeId: string;
201
+ componentId: string;
202
+ name: string;
203
+ } | {
204
+ op: 'setSeo';
205
+ fields: Partial<Record<ScreenSeoTextField, string>>;
206
+ } | {
207
+ op: 'addInteraction';
208
+ nodeId: string;
209
+ componentId: string;
210
+ interaction: NodeInteraction;
211
+ targets: Array<{
212
+ nodeId: string;
213
+ componentId: string;
214
+ }>;
215
+ };
216
+ /** Why an op may not act on an element it names. */
217
+ export type AssistEditClosedWorldRefusal = 'unknown' | 'root' | 'removed';
218
+ /** The words each refusal is given in, after the change's label. */
219
+ export declare const ASSIST_EDIT_CLOSED_WORLD_REFUSALS: Readonly<Record<AssistEditClosedWorldRefusal, string>>;
220
+ /** The closed world one edit's ops are held to, as they are read in order. */
221
+ export interface AssistEditClosedWorld {
222
+ /** Every element described, by id. */
223
+ byId: ReadonlyMap<string, AssistEditCanvasNode>;
224
+ /** The element an op acts on, or why it may not: not described, the root, or inside one an earlier op removes. */
225
+ element(nodeId: unknown): AssistEditCanvasNode | AssistEditClosedWorldRefusal;
226
+ /** The element an op adds or moves into — the root included — or null when it is not described or is removed. */
227
+ parent(parentId: unknown): AssistEditCanvasNode | null;
228
+ /** Whether moving `nodeId` into `parentId` would put it inside itself, as the earlier ops leave the tree. */
229
+ movesInsideItself(nodeId: string, parentId: string): boolean;
230
+ /** An earlier op removes this element: nothing later may act inside it. */
231
+ remove(nodeId: string): void;
232
+ /** An earlier op moves this element under a new parent. */
233
+ move(nodeId: string, parentId: string): void;
234
+ }
235
+ /**
236
+ * The closed world, for every door that turns a request into ops (AGL-4235):
237
+ * an op names only an element the request described, never the document root
238
+ * itself, and never one an earlier op removed. One implementation, for the
239
+ * model's tool call and for the public API's edits alike, so the two cannot
240
+ * disagree about what an edit may touch.
241
+ */
242
+ export declare function assistEditClosedWorld(context: AssistEditCanvasContext): AssistEditClosedWorld;
243
+ /** The longest layer name an element takes. */
244
+ export declare const ASSIST_EDIT_LAYER_NAME_CHARS = 80;
245
+ /**
246
+ * Why a layer name written by a caller that is not a model is refused, or
247
+ * null (AGL-4235): the rule the model's rename is held to — no markup, not
248
+ * empty, at most {@link ASSIST_EDIT_LAYER_NAME_CHARS} characters — where the
249
+ * model's name is cleaned to fit, this one must already fit.
250
+ */
251
+ export declare function assistEditLayerNameRefusal(name: string): string | null;
252
+ /** One change validation refused: the op it is in, by its position, and why. */
253
+ export interface AssistEditViolation {
254
+ position: number;
255
+ message: string;
256
+ /**
257
+ * A repair the validators would have made — a prop dropped, text cut, a
258
+ * value normalized — refused because the caller is strict. The message is
259
+ * the validator's own line, naming the element and the field.
260
+ */
261
+ repair?: true;
262
+ }
263
+ interface ValidatedEdit {
264
+ ops: AssistEditOp[];
265
+ violations: AssistEditViolation[];
266
+ }
163
267
  /**
164
268
  * What an edit knows of the site's datasets (AGL-3616): the ones the door
165
269
  * read, and the page's own record where the page is a dataset's record page.
@@ -171,6 +275,36 @@ export interface AssistEditDatasetScope {
171
275
  /** The dataset whose records this page is the page of, which fills its `{{item.*}}` anywhere on it. */
172
276
  recordDatasetId?: string | null;
173
277
  }
278
+ /**
279
+ * What a strict caller grounds an edit's references in (AGL-4235): the pages
280
+ * a `screen` setting may link to, and the media library scopes a `media:`
281
+ * reference may name. Absent, any well-formed id or reference passes, as for
282
+ * the chat door.
283
+ */
284
+ export interface AssistEditReferences {
285
+ screenIds?: Iterable<string>;
286
+ mediaScopes?: Iterable<string>;
287
+ }
288
+ /**
289
+ * Where an edit's content meets the validators: every new subtree through
290
+ * `validateAiNodeTree`, inside the real ancestor chain; every prop and style
291
+ * patch through `validateAiNodePatch`; every move through the palette's
292
+ * lineage rule. A violation drops its op and says why.
293
+ *
294
+ * `strict` is a caller that is not a model (AGL-4235): the public API, whose
295
+ * request says exactly what to write. Every repair the validators would make
296
+ * for a model — a setting dropped, text cut to its limit, a value coerced or
297
+ * normalized — is a violation instead, one per repair, and values are held to
298
+ * their types as written. The same validators and the same rules otherwise.
299
+ */
300
+ export declare function validatePendingEdit(output: {
301
+ surface: AssistEditDocumentKind;
302
+ context: AssistEditCanvasContext;
303
+ pending: readonly PendingEditOp[];
304
+ datasets?: AssistEditDatasetScope;
305
+ strict?: boolean;
306
+ references?: AssistEditReferences;
307
+ }): ValidatedEdit;
174
308
  /**
175
309
  * The edit's check: the model's tool call held to the canvas the request
176
310
  * described and to the palette validators, resolved into a proposal. Its
@@ -200,3 +334,4 @@ export declare function resolveAssistEdit(input: Record<string, unknown>, scope:
200
334
  proposal: AssistEditProposal | null;
201
335
  dropped: string[];
202
336
  };
337
+ export {};